2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "Database/DatabaseEnv.h"
24 #include "ObjectMgr.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #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 "CreatureAI.h"
50 #include "SpellAuras.h"
52 #include "Transports.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
58 #include "Database/DatabaseImpl.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
81 CHARACTER_FLAG_NONE
= 0x00000000,
82 CHARACTER_FLAG_UNK1
= 0x00000001,
83 CHARACTER_FLAG_UNK2
= 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
85 CHARACTER_FLAG_UNK4
= 0x00000008,
86 CHARACTER_FLAG_UNK5
= 0x00000010,
87 CHARACTER_FLAG_UNK6
= 0x00000020,
88 CHARACTER_FLAG_UNK7
= 0x00000040,
89 CHARACTER_FLAG_UNK8
= 0x00000080,
90 CHARACTER_FLAG_UNK9
= 0x00000100,
91 CHARACTER_FLAG_UNK10
= 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
94 CHARACTER_FLAG_UNK13
= 0x00001000,
95 CHARACTER_FLAG_GHOST
= 0x00002000,
96 CHARACTER_FLAG_RENAME
= 0x00004000,
97 CHARACTER_FLAG_UNK16
= 0x00008000,
98 CHARACTER_FLAG_UNK17
= 0x00010000,
99 CHARACTER_FLAG_UNK18
= 0x00020000,
100 CHARACTER_FLAG_UNK19
= 0x00040000,
101 CHARACTER_FLAG_UNK20
= 0x00080000,
102 CHARACTER_FLAG_UNK21
= 0x00100000,
103 CHARACTER_FLAG_UNK22
= 0x00200000,
104 CHARACTER_FLAG_UNK23
= 0x00400000,
105 CHARACTER_FLAG_UNK24
= 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
107 CHARACTER_FLAG_DECLINED
= 0x02000000,
108 CHARACTER_FLAG_UNK27
= 0x04000000,
109 CHARACTER_FLAG_UNK28
= 0x08000000,
110 CHARACTER_FLAG_UNK29
= 0x10000000,
111 CHARACTER_FLAG_UNK30
= 0x20000000,
112 CHARACTER_FLAG_UNK31
= 0x40000000,
113 CHARACTER_FLAG_UNK32
= 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
127 memset(m_taximask
, 0, sizeof(m_taximask
));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
132 // capital and taxi hub masks
135 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
136 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF
: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
150 case CLASS_DEATH_KNIGHT
: // TODO: figure out initial known nodes
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race
))
157 case ALLIANCE
: SetTaximaskNode(100); break;
158 case HORDE
: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data
)
167 Tokens tokens
= StrSplit(data
, " ");
170 Tokens::iterator iter
;
171 for (iter
= tokens
.begin(), index
= 0;
172 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
174 // load and set bits only for existed taxi nodes
175 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
183 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
184 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
188 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
189 data
<< uint32(m_taximask
[i
]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
195 ClearTaxiDestinations();
197 Tokens tokens
= StrSplit(values
," ");
199 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
201 uint32 node
= uint32(atol(iter
->c_str()));
202 AddTaxiDestination(node
);
205 if(m_TaxiDestinations
.empty())
209 if(m_TaxiDestinations
.size() < 2)
212 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
216 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
))
228 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations
.empty())
233 std::ostringstream ss
;
235 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
236 ss
<< m_TaxiDestinations
[i
] << " ";
241 uint32
PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations
.size() < 2)
249 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
254 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
257 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
258 ss
<< taxi
.m_taximask
[i
] << " ";
263 //== Player ====================================================
265 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask
Player::updateVisualBits
;
269 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this)
276 m_objectType
|= TYPEMASK_PLAYER
;
277 m_objectTypeId
= TYPEID_PLAYER
;
279 m_valuesCount
= PLAYER_END
;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER
)
291 SetAcceptWhispers(true);
299 m_usedTalentCount
= 0;
300 m_questRewardTalentCount
= 0;
303 m_weaponChangeTimer
= 0;
306 m_zoneUpdateTimer
= 0;
310 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount
= 0;
320 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL
);
326 m_groupUpdateMask
= 0;
327 m_auraUpdateMask
= 0;
331 m_GuildIdInvited
= 0;
332 m_ArenaTeamIdInvited
= 0;
334 m_atLoginFlags
= AT_LOGIN_NONE
;
343 PlayerTalkClass
= new PlayerMenu( GetSession() );
344 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
346 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
347 m_Tutorials
[ aX
] = 0x00;
348 m_TutorialsChanged
= false;
350 m_DailyQuestChanged
= false;
351 m_lastDailyQuestTime
= 0;
354 m_weaponChangeTimer
= 0;
356 m_isunderwater
= UNDERWATER_NONE
;
362 m_deathExpireTime
= 0;
366 m_DetectInvTimer
= 1000;
368 m_bgBattleGroundID
= 0;
369 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
371 m_bgBattleGroundQueueID
[j
].bgQueueType
= 0;
372 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
376 m_logintime
= time(NULL
);
377 m_Last_tick
= m_logintime
;
378 m_WeaponProficiency
= 0;
379 m_ArmorProficiency
= 0;
382 m_canDualWield
= false;
383 m_canTitanGrip
= false;
386 m_temporaryUnsummonedPetNumber
= 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
392 ////////////////////Rest System/////////////////////
399 rest_type
=REST_TYPE_NO
;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded
= false;
403 m_mailsUpdated
= false;
405 m_nextMailDelivereTime
= 0;
407 m_resetTalentsCost
= 0;
408 m_resetTalentsTime
= 0;
409 m_itemUpdateQueueBlocked
= false;
411 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
412 m_forced_speed_changes
[i
] = 0;
416 /////////////////// Instance System /////////////////////
419 m_InstanceValid
= true;
420 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
422 for (int i
= 0; i
< BASEMOD_END
; i
++)
424 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
425 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
428 for (int i
= 0; i
< MAX_COMBAT_RATING
; i
++)
429 m_baseRatingValue
[i
] = 0;
431 m_baseSpellDamage
= 0;
432 m_baseSpellHealing
= 0;
437 m_lastHonorUpdateTime
= time(NULL
);
446 //Default movement to run mode
447 m_unit_movement_flags
= 0;
452 m_bgAfkReportedTimer
= 0;
453 m_contestedPvPTimer
= 0;
455 m_declinedname
= NULL
;
461 CleanupsBeforeDelete();
463 // it must be unloaded already in PlayerLogout and accessed only for loggined player
466 // Note: buy back item already deleted from DB when player was saved
467 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
474 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
477 //all mailed items should be deleted, also all mail should be deallocated
478 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
481 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
482 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
484 delete PlayerTalkClass
;
488 m_transport
->RemovePassenger(this);
491 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
493 delete ItemSetEff
[x
];
495 // clean up player-instance binds, may unload some instance saves
496 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
497 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
498 itr
->second
.save
->RemovePlayer(this);
500 delete m_declinedname
;
504 void Player::CleanupsBeforeDelete()
506 if(m_uint32Values
) // only for fully created Object
509 DuelComplete(DUEL_INTERUPTED
);
511 Unit::CleanupsBeforeDelete();
514 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
)
516 //FIXME: outfitId not used in player creating
518 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
522 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
525 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
529 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
535 SetMapId(info
->mapId
);
536 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
538 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
541 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
545 uint8 powertype
= cEntry
->powerType
;
547 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
548 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
553 SetDisplayId(info
->displayId_f
);
554 SetNativeDisplayId(info
->displayId_f
);
557 SetDisplayId(info
->displayId_m
);
558 SetNativeDisplayId(info
->displayId_m
);
561 sLog
.outError("Invalid gender %u for player",gender
);
566 setFactionForRace(m_race
);
568 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
570 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
571 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
572 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
573 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
574 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
575 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
577 // -1 is default value
578 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
580 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
581 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
582 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
584 SetUInt32Value( PLAYER_GUILDID
, 0 );
585 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
586 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
588 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
590 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
591 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
592 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
593 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
594 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
596 // set starting level
597 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
598 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
599 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
601 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
603 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
604 if(gm_level
> start_level
)
605 start_level
= gm_level
;
608 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
612 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
613 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
614 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
617 m_Last_tick
= time(NULL
);
618 m_Played_time
[0] = 0;
619 m_Played_time
[1] = 0;
621 // base stats and related field values
623 InitTaxiNodesForLevel();
624 InitGlyphsForLevel();
625 InitTalentForLevel();
626 InitPrimaryProffesions(); // to max set before any spell added
628 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
629 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
630 SetHealth(GetMaxHealth());
631 if (getPowerType()==POWER_MANA
)
633 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
634 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
637 if(getPowerType() == POWER_RUNIC_POWER
)
639 SetPower(POWER_RUNE
, 8);
640 SetMaxPower(POWER_RUNE
, 8);
641 SetPower(POWER_RUNIC_POWER
, 0);
642 SetMaxPower(POWER_RUNIC_POWER
, 1000);
646 learnDefaultSpells();
648 // original action bar
649 std::list
<uint16
>::const_iterator action_itr
[4];
650 for(int i
=0; i
<4; i
++)
651 action_itr
[i
] = info
->action
[i
].begin();
653 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
656 for(int i
=0; i
<4 ;i
++)
657 taction
[i
] = (*action_itr
[i
]);
659 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
661 for(int i
=0; i
<4 ;i
++)
666 CharStartOutfitEntry
const* oEntry
= NULL
;
667 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
669 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
671 if(entry
->RaceClassGender
== RaceClassGender
)
681 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
683 if(oEntry
->ItemId
[j
] <= 0)
686 uint32 item_id
= oEntry
->ItemId
[j
];
689 // Hack for not existed item id in dbc 3.0.3
693 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
696 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
700 // max stack by default (mostly 1), 1 for infinity stackable
701 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
703 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
705 switch(iProto
->Spells
[0].SpellCategory
)
708 if(iProto
->Stackable
> 4)
712 if(iProto
->Stackable
> 2)
718 StoreNewItemInBestSlots(item_id
, count
);
722 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
723 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
725 // bags and main-hand weapon must equipped at this moment
726 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
727 // or ammo not equipped in special bag
728 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
730 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
733 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
734 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
735 if( msg
== EQUIP_ERR_OK
)
737 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
738 EquipItem( eDest
, pItem
, true);
740 // move other items to more appropriate slots (ammo not equipped in special bag)
743 ItemPosCountVec sDest
;
744 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
745 if( msg
== EQUIP_ERR_OK
)
747 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
748 pItem
= StoreItem( sDest
, pItem
, true);
751 // if this is ammo then use it
752 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
753 if( msg
== EQUIP_ERR_OK
)
754 SetAmmo( pItem
->GetProto()->ItemId
);
758 // all item positions resolved
763 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
765 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
767 // attempt equip by one
768 while(titem_amount
> 0)
771 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
772 if( msg
!= EQUIP_ERR_OK
)
775 EquipNewItem( eDest
, titem_id
, true);
776 AutoUnequipOffhandIfNeed();
780 if(titem_amount
== 0)
781 return true; // equipped
784 ItemPosCountVec sDest
;
785 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
786 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
787 if( msg
== EQUIP_ERR_OK
)
789 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
790 return true; // stored
793 // item can't be added
794 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
798 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
800 uint32 BreathRegen
= (uint32
)-1;
802 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
803 data
<< (uint32
)Type
;
808 data
<< (uint32
)0; // spell id
809 GetSession()->SendPacket(&data
);
812 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
814 if(Type
==BREATH_TIMER
)
815 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
817 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
818 data
<< (uint32
)Type
;
819 data
<< CurrentValue
;
823 data
<< (uint32
)0; // spell id
824 GetSession()->SendPacket( &data
);
827 void Player::StopMirrorTimer(MirrorTimerType Type
)
829 if(Type
==BREATH_TIMER
)
832 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
833 data
<< (uint32
)Type
;
834 GetSession()->SendPacket( &data
);
837 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
839 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
840 data
<< (uint64
)guid
;
841 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
842 data
<< (uint32
)damage
;
845 SendMessageToSet(&data
, true);
847 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
849 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
851 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
852 DurabilityLossAll(0.10f
,false);
853 // durability lost message
854 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
855 GetSession()->SendPacket(&data
);
859 void Player::HandleDrowning()
861 if(!(m_isunderwater
&~UNDERWATER_INLAVA
))
864 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
865 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
867 StopMirrorTimer(BREATH_TIMER
);
868 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
869 m_isunderwater
&= UNDERWATER_INLAVA
;
873 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default length 1 min
875 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
876 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
877 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
879 if ((m_isunderwater
& UNDERWATER_INWATER
) && !(m_isunderwater
& UNDERWATER_INLAVA
) && isAlive())
881 //single trigger timer
882 if (!(m_isunderwater
& UNDERWATER_WATER_TRIGGER
))
884 m_isunderwater
|= UNDERWATER_WATER_TRIGGER
;
885 m_breathTimer
= UnderWaterTime
+ 1000;
887 //single trigger "show Breathbar"
888 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& UNDERWATER_WATER_BREATHB
))
890 m_isunderwater
|= UNDERWATER_WATER_BREATHB
;
891 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
893 //continuous trigger drowning "Damage"
894 if ((m_breathTimer
== 0) && (m_isunderwater
& UNDERWATER_INWATER
))
896 //TODO: Check this formula
897 uint64 guid
= GetGUID();
898 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
900 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
901 m_breathTimer
= 2000;
904 //single trigger retract bar
905 else if (!(m_isunderwater
& UNDERWATER_INWATER
) && (m_isunderwater
& UNDERWATER_WATER_TRIGGER
) && (m_breathTimer
> 0) && isAlive())
907 uint32 BreathRegen
= 10;
908 // m_breathTimer will be reduced in ModifyMirrorTimer
909 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
910 m_isunderwater
= UNDERWATER_WATER_BREATHB_RETRACTING
;
913 else if ((m_breathTimer
< 50) && !(m_isunderwater
& UNDERWATER_INWATER
) && (m_isunderwater
== UNDERWATER_WATER_BREATHB_RETRACTING
))
915 StopMirrorTimer(BREATH_TIMER
);
916 m_isunderwater
= UNDERWATER_NONE
;
920 void Player::HandleLava()
922 if ((m_isunderwater
& UNDERWATER_INLAVA
) && isAlive())
925 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
926 // Single trigger Set BreathTimer
927 if (!(m_isunderwater & UNDERWATER_INLAVA))
929 m_isunderwater|= UNDERWATER_WATER_BREATHB;
930 m_breathTimer = 1000;
933 // Reset BreathTimer and still in the lava
936 uint64 guid
= GetGUID();
937 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
939 // if not gamemaster then deal damage
940 if ( !isGameMaster() )
941 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
943 m_breathTimer
= 1000;
946 else if (!isAlive()) // Disable breath timer and reset underwater flags
949 m_isunderwater
= UNDERWATER_NONE
;
953 ///The player sobers by 256 every 10 seconds
954 void Player::HandleSobering()
958 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
959 SetDrunkValue(drunk
);
962 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
965 return DRUNKEN_SMASHED
;
967 return DRUNKEN_DRUNK
;
969 return DRUNKEN_TIPSY
;
970 return DRUNKEN_SOBER
;
973 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
975 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
977 m_drunk
= newDrunkenValue
;
978 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
980 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
982 // special drunk invisibility detection
983 if(newDrunkenState
>= DRUNKEN_DRUNK
)
984 m_detectInvisibilityMask
|= (1<<6);
986 m_detectInvisibilityMask
&= ~(1<<6);
988 if(newDrunkenState
== oldDrunkenState
)
991 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
992 data
<< uint64(GetGUID());
993 data
<< uint32(newDrunkenState
);
994 data
<< uint32(itemId
);
996 SendMessageToSet(&data
, true);
999 void Player::Update( uint32 p_time
)
1005 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1010 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1011 m_nextMailDelivereTime
= 0;
1014 Unit::Update( p_time
);
1016 // update player only attacks
1017 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1019 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1022 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1024 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1027 time_t now
= time (NULL
);
1031 UpdateContestedPvP(p_time
);
1033 UpdateDuelFlag(now
);
1035 CheckDuelDistance(now
);
1037 UpdateAfkReport(now
);
1039 CheckExploreSystem();
1041 // Update items that have just a limited lifetime
1042 if (now
>m_Last_tick
)
1043 UpdateItemDuration(uint32(now
- m_Last_tick
));
1045 if (!m_timedquests
.empty())
1047 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1048 while (iter
!= m_timedquests
.end())
1050 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1051 if( q_status
.m_timer
<= p_time
)
1053 uint32 quest_id
= *iter
;
1054 ++iter
; // current iter will be removed in FailTimedQuest
1055 FailTimedQuest( quest_id
);
1059 q_status
.m_timer
-= p_time
;
1060 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1066 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1068 Unit
*pVictim
= getVictim();
1069 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1071 // default combat reach 10
1072 // TODO add weapon,skill check
1074 float pldistance
= ATTACK_DISTANCE
;
1076 if (isAttackReady(BASE_ATTACK
))
1078 if(!IsWithinDistInMap(pVictim
, pldistance
))
1080 setAttackTimer(BASE_ATTACK
,100);
1081 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1083 SendAttackSwingNotInRange();
1084 m_swingErrorMsg
= 1;
1087 //120 degrees of radiant range
1088 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1090 setAttackTimer(BASE_ATTACK
,100);
1091 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1093 SendAttackSwingBadFacingAttack();
1094 m_swingErrorMsg
= 2;
1099 m_swingErrorMsg
= 0; // reset swing error state
1101 // prevent base and off attack in same time, delay attack at 0.2 sec
1102 if(haveOffhandWeapon())
1104 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1105 if(off_att
< ATTACK_DISPLAY_DELAY
)
1106 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1108 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1109 resetAttackTimer(BASE_ATTACK
);
1113 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1115 if(!IsWithinDistInMap(pVictim
, pldistance
))
1117 setAttackTimer(OFF_ATTACK
,100);
1119 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1121 setAttackTimer(OFF_ATTACK
,100);
1125 // prevent base and off attack in same time, delay attack at 0.2 sec
1126 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1127 if(base_att
< ATTACK_DISPLAY_DELAY
)
1128 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1130 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1131 resetAttackTimer(OFF_ATTACK
);
1135 Unit
*owner
= pVictim
->GetOwner();
1136 Unit
*u
= owner
? owner
: pVictim
;
1137 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1140 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1145 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1147 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1149 int time_inn
= time(NULL
)-GetTimeInnEnter();
1150 if (time_inn
>= 10) //freeze update
1152 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1153 //speed collect rest bonus (section/in hour)
1154 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1155 UpdateInnerTime(time(NULL
));
1160 if(m_regenTimer
> 0)
1162 if(p_time
>= m_regenTimer
)
1165 m_regenTimer
-= p_time
;
1168 if (m_weaponChangeTimer
> 0)
1170 if(p_time
>= m_weaponChangeTimer
)
1171 m_weaponChangeTimer
= 0;
1173 m_weaponChangeTimer
-= p_time
;
1176 if (m_zoneUpdateTimer
> 0)
1178 if(p_time
>= m_zoneUpdateTimer
)
1180 uint32 newzone
= GetZoneId();
1181 if( m_zoneUpdateId
!= newzone
)
1182 UpdateZone(newzone
); // also update area
1185 // use area updates as well
1186 // needed for free far all arenas for example
1187 uint32 newarea
= GetAreaId();
1188 if( m_areaUpdateId
!= newarea
)
1189 UpdateArea(newarea
);
1191 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1195 m_zoneUpdateTimer
-= p_time
;
1203 if (m_deathState
== JUST_DIED
)
1210 if(p_time
>= m_nextSave
)
1212 // m_nextSave reseted in SaveToDB call
1214 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1218 m_nextSave
-= p_time
;
1223 if(m_breathTimer
> 0)
1225 if(p_time
>= m_breathTimer
)
1228 m_breathTimer
-= p_time
;
1232 //Handle Water/drowning
1238 //Handle detect stealth players
1239 if (m_DetectInvTimer
> 0)
1241 if (p_time
>= m_DetectInvTimer
)
1243 m_DetectInvTimer
= 3000;
1244 HandleStealthedUnitsDetection();
1247 m_DetectInvTimer
-= p_time
;
1251 if (now
> m_Last_tick
)
1253 uint32 elapsed
= uint32(now
- m_Last_tick
);
1254 m_Played_time
[0] += elapsed
; // Total played time
1255 m_Played_time
[1] += elapsed
; // Level played time
1261 m_drunkTimer
+= p_time
;
1263 if (m_drunkTimer
> 10000)
1267 // not auto-free ghost from body in instances
1268 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1270 if(p_time
>= m_deathTimer
)
1277 m_deathTimer
-= p_time
;
1280 UpdateEnchantTime(p_time
);
1281 UpdateHomebindTime(p_time
);
1284 SendUpdateToOutOfRangeGroupMembers();
1286 Pet
* pet
= GetPet();
1287 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1289 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1294 void Player::setDeathState(DeathState s
)
1296 uint32 ressSpellId
= 0;
1298 bool cur
= isAlive();
1300 if(s
== JUST_DIED
&& cur
)
1302 // drunken state is cleared on death
1304 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1307 clearResurrectRequestData();
1309 // remove form before other mods to prevent incorrect stats calculation
1310 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1312 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1313 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1315 // remove uncontrolled pets
1319 // save value before aura remove in Unit::setDeathState
1320 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1324 ressSpellId
= GetResurrectionSpellId();
1325 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1327 Unit::setDeathState(s
);
1329 // restore resurrection spell id for player after aura remove
1330 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1331 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1333 if(isAlive() && !cur
)
1335 //clear aura case after resurrection by another way (spells will be applied before next death)
1336 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1338 // restore default warrior stance
1339 if(getClass()== CLASS_WARRIOR
)
1340 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1344 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1346 Field
*fields
= result
->Fetch();
1348 *p_data
<< uint64(GetGUID());
1351 *p_data
<< uint8(getRace());
1352 uint8 pClass
= getClass();
1353 *p_data
<< uint8(pClass
);
1354 *p_data
<< uint8(getGender());
1356 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1357 *p_data
<< uint8(bytes
);
1358 *p_data
<< uint8(bytes
>> 8);
1359 *p_data
<< uint8(bytes
>> 16);
1360 *p_data
<< uint8(bytes
>> 24);
1362 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1363 *p_data
<< uint8(bytes
);
1365 *p_data
<< uint8(getLevel()); // player level
1366 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1367 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1368 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1369 *p_data
<< uint32(zoneId
);
1370 *p_data
<< uint32(GetMapId());
1372 *p_data
<< GetPositionX();
1373 *p_data
<< GetPositionY();
1374 *p_data
<< GetPositionZ();
1377 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1379 uint32 char_flags
= 0;
1380 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1381 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1382 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1383 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1384 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1385 char_flags
|= CHARACTER_FLAG_GHOST
;
1386 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1387 char_flags
|= CHARACTER_FLAG_RENAME
;
1388 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1389 char_flags
|= CHARACTER_FLAG_DECLINED
;
1391 *p_data
<< uint32(char_flags
); // character flags
1392 // character customize (flags?)
1393 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1394 *p_data
<< uint8(1); // unknown
1398 uint32 petDisplayId
= 0;
1399 uint32 petLevel
= 0;
1400 uint32 petFamily
= 0;
1402 // show pet at selection character in character list only for non-ghost character
1403 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1405 uint32 entry
= fields
[10].GetUInt32();
1406 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1409 petDisplayId
= fields
[11].GetUInt32();
1410 petLevel
= fields
[12].GetUInt32();
1411 petFamily
= cInfo
->family
;
1415 *p_data
<< uint32(petDisplayId
);
1416 *p_data
<< uint32(petLevel
);
1417 *p_data
<< uint32(petFamily
);
1420 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1422 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1423 uint32 item_id
= GetUInt32Value(visualbase
);
1424 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1425 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1427 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1429 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1430 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1436 *p_data
<< uint32(proto
->DisplayInfoID
);
1437 *p_data
<< uint8(proto
->InventoryType
);
1438 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1442 *p_data
<< uint32(0);
1443 *p_data
<< uint8(0);
1444 *p_data
<< uint32(0); // enchant?
1447 *p_data
<< uint32(0); // first bag display id
1448 *p_data
<< uint8(0); // first bag inventory type
1449 *p_data
<< uint32(0); // enchant?
1452 bool Player::ToggleAFK()
1454 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1456 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1458 // afk player not allowed in battleground
1459 if(state
&& InBattleGround())
1460 LeaveBattleground();
1465 bool Player::ToggleDND()
1467 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1469 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1472 uint8
Player::chatTag() const
1489 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1491 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1493 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1497 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1498 Pet
* pet
= GetPet();
1500 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1502 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1503 // don't let gm level > 1 either
1504 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1507 // client without expansion support
1508 if(GetSession()->Expansion() < mEntry
->Expansion())
1510 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1513 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1515 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1517 return false; // normal client can't teleport to this map...
1521 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1524 // if we were on a transport, leave
1525 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1527 m_transport
->RemovePassenger(this);
1529 m_movementInfo
.t_x
= 0.0f
;
1530 m_movementInfo
.t_y
= 0.0f
;
1531 m_movementInfo
.t_z
= 0.0f
;
1532 m_movementInfo
.t_o
= 0.0f
;
1533 m_movementInfo
.t_time
= 0;
1536 SetSemaphoreTeleport(true);
1538 // The player was ported to another map and looses the duel immediately.
1539 // We have to perform this check before the teleport, otherwise the
1540 // ObjectAccessor won't find the flag.
1541 if (duel
&& GetMapId()!=mapid
)
1543 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1545 DuelComplete(DUEL_FLED
);
1548 // reset movement flags at teleport, because player will continue move with these flags after teleport
1549 SetUnitMovementFlags(0);
1551 if ((GetMapId() == mapid
) && (!m_transport
))
1553 // prepare zone change detect
1554 uint32 old_zone
= GetZoneId();
1557 if(!GetSession()->PlayerLogout())
1560 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1561 GetSession()->SendPacket(&data
);
1562 SetPosition( x
, y
, z
, orientation
, true);
1565 // this will be used instead of the current location in SaveToDB
1566 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1567 SetFallInformation(0, z
);
1569 //BuildHeartBeatMsg(&data);
1570 //SendMessageToSet(&data, true);
1571 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1573 //same map, only remove pet if out of range
1574 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1576 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1577 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1579 m_temporaryUnsummonedPetNumber
= 0;
1581 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1585 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1588 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1591 if(pet
&& m_temporaryUnsummonedPetNumber
)
1593 Pet
* NewPet
= new Pet
;
1594 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1597 m_temporaryUnsummonedPetNumber
= 0;
1601 if(!GetSession()->PlayerLogout())
1603 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1604 SetSemaphoreTeleport(false);
1606 UpdateZone(GetZoneId());
1610 if(old_zone
!= GetZoneId())
1613 if(pvpInfo
.inHostileArea
)
1614 CastSpell(this, 2479, true);
1619 // far teleport to another map
1620 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1621 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1623 // Check enter rights before map getting to avoid creating instance copy for player
1624 // this check not dependent from map instance copy and same for all instance copies of selected map
1625 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1627 SetSemaphoreTeleport(false);
1631 // If the map is not created, assume it is possible to enter it.
1632 // It will be created in the WorldPortAck.
1633 Map
*map
= MapManager::Instance().FindMap(mapid
);
1634 if (!map
|| map
->CanEnter(this))
1640 ResetContestedPvP();
1642 // remove player from battleground on far teleport (when changing maps)
1643 if(BattleGround
const* bg
= GetBattleGround())
1645 // Note: at battleground join battleground id set before teleport
1646 // and we already will found "current" battleground
1647 // just need check that this is targeted map or leave
1648 if(bg
->GetMapId() != mapid
)
1649 LeaveBattleground(false); // don't teleport to entry point
1652 // remove pet on map change
1655 //leaving map -> delete pet right away (doing this later will cause problems)
1656 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1657 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1659 m_temporaryUnsummonedPetNumber
= 0;
1661 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1664 // remove all dyn objects
1665 RemoveAllDynObjects();
1667 // stop spellcasting
1668 // not attempt interrupt teleportation spell at caster teleport
1669 if(!(options
& TELE_TO_SPELL
))
1670 if(IsNonMeleeSpellCasted(true))
1671 InterruptNonMeleeSpells(true);
1673 if(!GetSession()->PlayerLogout())
1675 // send transfer packets
1676 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1677 data
<< uint32(mapid
);
1680 data
<< m_transport
->GetEntry() << GetMapId();
1682 GetSession()->SendPacket(&data
);
1684 data
.Initialize(SMSG_NEW_WORLD
, (20));
1687 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1691 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1693 GetSession()->SendPacket( &data
);
1694 SendSavedInstances();
1696 // remove from old map now
1697 if(oldmap
) oldmap
->Remove(this, false);
1700 // new final coordinates
1704 float final_o
= orientation
;
1708 final_x
+= m_movementInfo
.t_x
;
1709 final_y
+= m_movementInfo
.t_y
;
1710 final_z
+= m_movementInfo
.t_z
;
1711 final_o
+= m_movementInfo
.t_o
;
1714 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1715 SetFallInformation(0, final_z
);
1716 // if the player is saved before worldportack (at logout for example)
1717 // this will be used instead of the current location in SaveToDB
1719 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1721 // move packet sent by client always after far teleport
1722 // SetPosition(final_x, final_y, final_z, final_o, true);
1725 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1733 void Player::AddToWorld()
1735 ///- Do not add/remove the player from the object storage
1736 ///- It will crash when updating the ObjectAccessor
1737 ///- The player should only be added when logging in
1740 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1743 m_items
[i
]->AddToWorld();
1747 void Player::RemoveFromWorld()
1752 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1754 UnsummonAllTotems();
1759 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1762 m_items
[i
]->RemoveFromWorld();
1765 ///- Do not add/remove the player from the object storage
1766 ///- It will crash when updating the ObjectAccessor
1767 ///- The player should only be removed when logging out
1768 Unit::RemoveFromWorld();
1771 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1775 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1779 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1781 // talent who gave more rage on attack
1782 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1786 addRage
= damage
/rageconversion
*2.5;
1788 // Berserker Rage effect
1789 if(HasAura(18499,0))
1793 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1795 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1798 void Player::RegenerateAll()
1800 if (m_regenTimer
!= 0)
1802 uint32 regenDelay
= 2000;
1804 // Not in combat or they have regeneration
1805 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1806 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1809 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1811 Regenerate(POWER_RAGE
);
1812 if(getClass() == CLASS_DEATH_KNIGHT
)
1813 Regenerate(POWER_RUNIC_POWER
);
1817 Regenerate( POWER_ENERGY
);
1819 Regenerate( POWER_MANA
);
1821 if(getClass() == CLASS_DEATH_KNIGHT
)
1822 Regenerate( POWER_RUNE
);
1824 m_regenTimer
= regenDelay
;
1827 void Player::Regenerate(Powers power
)
1829 uint32 curValue
= GetPower(power
);
1830 uint32 maxValue
= GetMaxPower(power
);
1832 float addvalue
= 0.0f
;
1838 bool recentCast
= IsUnderLastManaUseEffect();
1839 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1842 // Mangos Updates Mana in intervals of 2s, which is correct
1843 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1847 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1850 case POWER_RAGE
: // Regenerate rage
1852 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1853 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1855 case POWER_ENERGY
: // Regenerate energy (rogue)
1858 case POWER_RUNIC_POWER
:
1860 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1861 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1865 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1866 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1867 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1870 case POWER_HAPPINESS
:
1874 // Mana regen calculated in Player::UpdateManaRegen()
1875 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1876 if(power
!= POWER_MANA
)
1878 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1879 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1880 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1881 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1884 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1886 curValue
+= uint32(addvalue
);
1887 if (curValue
> maxValue
)
1888 curValue
= maxValue
;
1892 if(curValue
<= uint32(addvalue
))
1895 curValue
-= uint32(addvalue
);
1897 SetPower(power
, curValue
);
1900 void Player::RegenerateHealth()
1902 uint32 curValue
= GetHealth();
1903 uint32 maxValue
= GetMaxHealth();
1905 if (curValue
>= maxValue
) return;
1907 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1909 float addvalue
= 0.0f
;
1912 if ( IsPolymorphed() )
1913 addvalue
= GetMaxHealth()/3;
1914 // normal regen case (maybe partly in combat case)
1915 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1917 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1920 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1921 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1922 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1924 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1925 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1931 // always regeneration bonus (including combat)
1932 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1937 ModifyHealth(int32(addvalue
));
1940 bool Player::CanInteractWithNPCs(bool alive
) const
1942 if(alive
&& !isAlive())
1950 bool Player::IsUnderWater() const
1952 return IsInWater() &&
1953 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1956 void Player::SetInWater(bool apply
)
1958 if(m_isInWater
==apply
)
1961 //define player in water by opcodes
1962 //move player's guid into HateOfflineList of those mobs
1963 //which can't swim and move guid back into ThreatList when
1965 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1966 m_isInWater
= apply
;
1968 // remove auras that need water/land
1969 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
1971 getHostilRefManager().updateThreatTables();
1974 void Player::SetGameMaster(bool on
)
1978 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
1980 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1982 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
1983 ResetContestedPvP();
1985 getHostilRefManager().setOnlineOfflineState(false);
1988 SetPhaseMask(PHASEMASK_ANYWHERE
); // see and visible in all phases
1993 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
1994 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
);
1996 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
1997 setFactionForRace(getRace());
1998 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2000 // restore FFA PvP Server state
2001 if(sWorld
.IsFFAPvPRealm())
2002 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2004 // restore FFA PvP area state, remove not allowed for GM mounts
2005 UpdateArea(m_areaUpdateId
);
2007 getHostilRefManager().setOnlineOfflineState(true);
2010 ObjectAccessor::UpdateVisibilityForPlayer(this);
2013 void Player::SetGMVisible(bool on
)
2017 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2019 // Reapply stealth/invisibility if active or show if not any
2020 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2021 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2022 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2023 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2025 SetVisibility(VISIBILITY_ON
);
2029 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2031 SetAcceptWhispers(false);
2032 SetGameMaster(true);
2034 SetVisibility(VISIBILITY_OFF
);
2038 bool Player::IsGroupVisibleFor(Player
* p
) const
2040 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2042 default: return IsInSameGroupWith(p
);
2043 case 1: return IsInSameRaidWith(p
);
2044 case 2: return GetTeam()==p
->GetTeam();
2048 bool Player::IsInSameGroupWith(Player
const* p
) const
2050 return p
==this || GetGroup() != NULL
&&
2051 GetGroup() == p
->GetGroup() &&
2052 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2055 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2056 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2057 void Player::UninviteFromGroup()
2059 Group
* group
= GetGroupInvite();
2063 group
->RemoveInvite(this);
2065 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2067 if(group
->IsCreated())
2069 group
->Disband(true);
2070 objmgr
.RemoveGroup(group
);
2073 group
->RemoveAllInvites();
2079 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2083 if (group
->RemoveMember(guid
, 0) <= 1)
2085 // group->Disband(); already disbanded in RemoveMember
2086 objmgr
.RemoveGroup(group
);
2088 // removemember sets the player's group pointer to NULL
2093 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2095 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2096 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2097 data
<< uint32(GivenXP
+RestXP
); // given experience
2098 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2101 data
<< uint32(GivenXP
); // experience without rested bonus
2102 data
<< float(1); // 1 - none 0 - 100% group bonus output
2104 data
<< uint8(0); // new 2.4.0
2105 GetSession()->SendPacket(&data
);
2108 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2116 uint32 level
= getLevel();
2118 // XP to money conversion processed in Player::RewardQuest
2119 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2122 // handle SPELL_AURA_MOD_XP_PCT auras
2123 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2124 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2125 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2127 // XP resting bonus for kill
2128 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2130 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2132 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2133 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2134 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2136 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2140 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2141 GiveLevel(level
+ 1);
2144 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2147 SetUInt32Value(PLAYER_XP
, newXP
);
2150 // Update player to next level
2151 // Current player experience not update (must be update by caller)
2152 void Player::GiveLevel(uint32 level
)
2154 if ( level
== getLevel() )
2157 PlayerLevelInfo info
;
2158 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2160 PlayerClassLevelInfo classInfo
;
2161 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2163 // send levelup info to client
2164 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2165 data
<< uint32(level
);
2166 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2167 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2168 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2176 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2177 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2179 GetSession()->SendPacket(&data
);
2181 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2183 //update level, max level of skills
2184 if(getLevel()!= level
)
2185 m_Played_time
[1] = 0; // Level Played Time reset
2187 UpdateSkillsForLevel ();
2189 // save base values (bonuses already included in stored stats
2190 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2191 SetCreateStat(Stats(i
), info
.stats
[i
]);
2193 SetCreateHealth(classInfo
.basehealth
);
2194 SetCreateMana(classInfo
.basemana
);
2196 InitTalentForLevel();
2197 InitTaxiNodesForLevel();
2198 InitGlyphsForLevel();
2202 // set current level health and mana/energy to maximum after applying all mods.
2203 SetHealth(GetMaxHealth());
2204 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2205 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2206 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2207 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2208 SetPower(POWER_FOCUS
, 0);
2209 SetPower(POWER_HAPPINESS
, 0);
2211 // give level to summoned pet
2212 Pet
* pet
= GetPet();
2213 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2214 pet
->GivePetLevel(level
);
2215 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2218 void Player::InitTalentForLevel()
2220 uint32 level
= getLevel();
2221 // talents base at level diff ( talents = level - 9 but some can be used already)
2224 // Remove all talent points
2225 if(m_usedTalentCount
> 0) // Free any used talents
2228 SetFreeTalentPoints(0);
2233 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2235 // if used more that have then reset
2236 if(m_usedTalentCount
> talentPointsForLevel
)
2238 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2241 SetFreeTalentPoints(0);
2243 // else update amount of free points
2245 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2249 void Player::InitStatsForLevel(bool reapplyMods
)
2251 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2252 _RemoveAllStatBonuses();
2254 PlayerClassLevelInfo classInfo
;
2255 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2257 PlayerLevelInfo info
;
2258 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2260 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2261 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2263 UpdateSkillsForLevel ();
2265 // set default cast time multiplier
2266 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2268 // reset size before reapply auras
2269 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2271 // save base values (bonuses already included in stored stats
2272 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2273 SetCreateStat(Stats(i
), info
.stats
[i
]);
2275 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2276 SetStat(Stats(i
), info
.stats
[i
]);
2278 SetCreateHealth(classInfo
.basehealth
);
2281 SetCreateMana(classInfo
.basemana
);
2283 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2287 //reset rating fields values
2288 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2289 SetUInt32Value(index
, 0);
2291 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2292 for (int i
= 0; i
< 7; i
++)
2294 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2295 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2296 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2299 //reset attack power, damage and attack speed fields
2300 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2301 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2302 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2304 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2305 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2306 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2307 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2308 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2309 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2311 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2312 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2313 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2314 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2315 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2316 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2318 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2319 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2320 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2321 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2323 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2324 for (uint8 i
= 0; i
< 7; ++i
)
2325 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2327 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2328 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2329 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2332 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2334 // set armor (resistance 0) to original value (create_agility*2)
2335 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2336 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2337 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2338 // set other resistance to original value (0)
2339 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2341 SetResistance(SpellSchools(i
), 0);
2342 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2343 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2346 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2347 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2348 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2350 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2351 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2353 // Reset no reagent cost field
2354 for(int i
= 0; i
< 3; i
++)
2355 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2356 // Init data for form but skip reapply item mods for form
2357 InitDataForForm(reapplyMods
);
2360 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2361 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2363 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2365 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2366 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2368 // cleanup unit flags (will be re-applied if need at aura load).
2369 RemoveFlag( UNIT_FIELD_FLAGS
,
2370 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2371 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2372 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2373 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2374 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2375 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2377 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2378 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2380 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2381 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2383 // restore if need some important flags
2384 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2386 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2387 _ApplyAllStatBonuses();
2389 // set current level health and mana/energy to maximum after applying all mods.
2390 SetHealth(GetMaxHealth());
2391 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2392 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2393 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2394 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2395 SetPower(POWER_FOCUS
, 0);
2396 SetPower(POWER_HAPPINESS
, 0);
2397 SetPower(POWER_RUNIC_POWER
, 0);
2400 void Player::SendInitialSpells()
2402 uint16 spellCount
= 0;
2404 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2407 size_t countPos
= data
.wpos();
2408 data
<< uint16(spellCount
); // spell count placeholder
2410 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2412 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2415 if(!itr
->second
->active
|| itr
->second
->disabled
)
2418 data
<< uint16(itr
->first
);
2419 data
<< uint16(0); // it's not slot id
2424 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2426 uint16 spellCooldowns
= m_spellCooldowns
.size();
2427 data
<< uint16(spellCooldowns
);
2428 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2430 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2434 data
<< uint16(itr
->first
);
2436 time_t cooldown
= 0;
2437 time_t curTime
= time(NULL
);
2438 if(itr
->second
.end
> curTime
)
2439 cooldown
= (itr
->second
.end
-curTime
)*1000;
2441 data
<< uint16(itr
->second
.itemid
); // cast item id
2442 data
<< uint16(sEntry
->Category
); // spell category
2443 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2445 data
<< uint32(0); // cooldown
2446 data
<< uint32(cooldown
); // category cooldown
2450 data
<< uint32(cooldown
); // cooldown
2451 data
<< uint32(0); // category cooldown
2455 GetSession()->SendPacket(&data
);
2457 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2460 void Player::RemoveMail(uint32 id
)
2462 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2464 if ((*itr
)->messageID
== id
)
2466 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2473 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2475 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2476 data
<< (uint32
) mailId
;
2477 data
<< (uint32
) mailAction
;
2478 data
<< (uint32
) mailError
;
2479 if ( mailError
== MAIL_ERR_BAG_FULL
)
2480 data
<< (uint32
) equipError
;
2481 else if( mailAction
== MAIL_ITEM_TAKEN
)
2483 data
<< (uint32
) item_guid
; // item guid low?
2484 data
<< (uint32
) item_count
; // item count?
2486 GetSession()->SendPacket(&data
);
2489 void Player::SendNewMail()
2491 // deliver undelivered mail
2492 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2494 GetSession()->SendPacket(&data
);
2497 void Player::UpdateNextMailTimeAndUnreads()
2499 // calculate next delivery time (min. from non-delivered mails
2500 // and recalculate unReadMail
2501 time_t cTime
= time(NULL
);
2502 m_nextMailDelivereTime
= 0;
2504 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2506 if((*itr
)->deliver_time
> cTime
)
2508 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2509 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2511 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2516 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2518 if(deliver_time
<= time(NULL
)) // ready now
2523 else // not ready and no have ready mails
2525 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2526 m_nextMailDelivereTime
= deliver_time
;
2530 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2532 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2535 // do character spell book cleanup (all characters)
2536 if(!IsInWorld() && !learning
) // spell load case
2538 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2539 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2542 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2547 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2549 // do character spell book cleanup (all characters)
2550 if(!IsInWorld() && !learning
) // spell load case
2552 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2553 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2556 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2561 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2563 bool dependent_set
= false;
2564 bool disabled_case
= false;
2565 bool superceded_old
= false;
2567 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2568 if (itr
!= m_spells
.end())
2570 uint32 next_active_spell_id
= 0;
2571 // fix activate state for non-stackable low rank (and find next spell for !active case)
2572 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2574 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2575 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2577 if(HasSpell(next_itr
->second
))
2579 // high rank already known so this must !active
2581 next_active_spell_id
= next_itr
->second
;
2587 // not do anything if already known in expected state
2588 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2589 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2591 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2592 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2597 // dependent spell known as not dependent, overwrite state
2598 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2600 itr
->second
->dependent
= dependent
;
2601 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2602 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2603 dependent_set
= true;
2606 // update active state for known spell
2607 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2609 itr
->second
->active
= active
;
2611 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2612 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2613 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2614 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2618 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2619 CastSpell (this,spell_id
,true);
2621 else if(IsInWorld())
2623 if(next_active_spell_id
)
2625 // update spell ranks in spellbook and action bar
2626 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2627 data
<< uint16(spell_id
);
2628 data
<< uint16(next_active_spell_id
);
2629 GetSession()->SendPacket( &data
);
2633 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2634 data
<< uint16(spell_id
);
2635 GetSession()->SendPacket(&data
);
2639 return active
; // learn (show in spell book if active now)
2642 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2644 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2645 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2646 itr
->second
->disabled
= disabled
;
2651 disabled_case
= true;
2653 else switch(itr
->second
->state
)
2655 case PLAYERSPELL_UNCHANGED
: // known saved spell
2657 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2660 m_spells
.erase(itr
);
2661 state
= PLAYERSPELL_CHANGED
;
2662 break; // need re-add
2664 default: // known not saved yet spell (new or modified)
2666 // can be in case spell loading but learned at some previous spell loading
2667 if(!IsInWorld() && !learning
&& !dependent_set
)
2668 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2675 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2677 // talent: unlearn all other talent ranks (high and low)
2678 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2680 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2682 for(int i
=0; i
<5; ++i
)
2684 // skip learning spell and no rank spell case
2685 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2686 if(!rankSpellId
|| rankSpellId
==spell_id
)
2689 removeSpell(rankSpellId
);
2693 // non talent spell: learn low ranks (recursive call)
2694 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2696 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2697 addSpell(prev_spell
,active
,true,true,disabled
);
2698 else // at normal learning
2699 learnSpell(prev_spell
,true);
2702 PlayerSpell
*newspell
= new PlayerSpell
;
2703 newspell
->state
= state
;
2704 newspell
->active
= active
;
2705 newspell
->dependent
= dependent
;
2706 newspell
->disabled
= disabled
;
2708 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2709 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2711 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2713 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2714 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2715 if(!i_spellInfo
) continue;
2717 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2719 if(itr
->second
->active
)
2721 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2723 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2725 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2726 data
<< uint16(itr
->first
);
2727 data
<< uint16(spell_id
);
2728 GetSession()->SendPacket( &data
);
2731 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2732 itr
->second
->active
= false;
2733 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2734 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2735 superceded_old
= true; // new spell replace old in action bars and spell book.
2737 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2739 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2741 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2742 data
<< uint16(spell_id
);
2743 data
<< uint16(itr
->first
);
2744 GetSession()->SendPacket( &data
);
2747 // mark new spell as disable (not learned yet for client and will not learned)
2748 newspell
->active
= false;
2749 if(newspell
->state
!= PLAYERSPELL_NEW
)
2750 newspell
->state
= PLAYERSPELL_CHANGED
;
2757 m_spells
[spell_id
] = newspell
;
2759 // return false if spell disabled
2760 if (newspell
->disabled
)
2764 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2766 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2767 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2768 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2770 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2771 CastSpell(this, spell_id
, true);
2773 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2774 else if (IsPassiveSpell(spell_id
))
2776 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2777 CastSpell(this, spell_id
, true);
2779 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2781 CastSpell(this, spell_id
, true);
2785 // update used talent points count
2786 m_usedTalentCount
+= talentCost
;
2788 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2789 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2791 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2792 SetFreePrimaryProffesions(freeProfs
-1);
2795 // add dependent skills
2796 uint16 maxskill
= GetMaxSkillValueForLevel();
2798 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2802 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2803 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2805 if(skill_value
< spellLearnSkill
->value
)
2806 skill_value
= spellLearnSkill
->value
;
2808 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2810 if(skill_max_value
< new_skill_max_value
)
2811 skill_max_value
= new_skill_max_value
;
2813 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2817 // not ranked skills
2818 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2819 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2821 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2823 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2827 if(HasSkill(pSkill
->id
))
2830 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2831 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2832 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2834 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2836 case SKILL_RANGE_LANGUAGE
:
2837 SetSkill(pSkill
->id
, 300, 300 );
2839 case SKILL_RANGE_LEVEL
:
2840 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2842 case SKILL_RANGE_MONO
:
2843 SetSkill(pSkill
->id
, 1, 1 );
2852 // learn dependent spells
2853 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2854 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2856 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2858 if(!itr
->second
.autoLearned
)
2860 if(!IsInWorld() || !itr
->second
.active
) // at spells loading, no output, but allow save
2861 addSpell(itr
->second
.spell
,itr
->second
.active
,true,true,false);
2862 else // at normal learning
2863 learnSpell(itr
->second
.spell
,true);
2869 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
);
2870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
);
2873 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2874 return active
&& !disabled
&& !superceded_old
;
2877 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2879 bool need_cast
= false;
2881 switch(spellInfo
->Id
)
2883 // some spells not have stance data expacted cast at form change or present
2884 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2885 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2886 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2887 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2888 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2889 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2890 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2891 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2892 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2893 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2894 // another spells have proper stance data
2895 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2898 //Check CasterAuraStates
2899 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
2902 void Player::learnSpell(uint32 spell_id
, bool dependent
)
2904 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2906 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2907 bool active
= disabled
? itr
->second
->active
: true;
2909 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
2911 // learn all disabled higher ranks (recursive)
2914 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2915 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2917 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2918 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
2919 learnSpell(i
->second
,false);
2923 // prevent duplicated entires in spell book, also not send if not in world (loading)
2924 if(!learning
|| !IsInWorld ())
2927 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2928 data
<< uint32(spell_id
);
2929 GetSession()->SendPacket(&data
);
2932 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
2934 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2935 if (itr
== m_spells
.end())
2938 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2941 // unlearn non talent higher ranks (recursive)
2942 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2943 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2944 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2945 removeSpell(itr2
->second
,disabled
);
2947 bool cur_active
= itr
->second
->active
;
2948 bool cur_dependent
= itr
->second
->dependent
;
2952 itr
->second
->disabled
= disabled
;
2953 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2954 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2958 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2961 m_spells
.erase(itr
);
2964 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2967 RemoveAurasDueToSpell(spell_id
);
2970 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2971 RemovePetAura(petSpell
);
2973 // free talent points
2974 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2977 if(talentCosts
< m_usedTalentCount
)
2978 m_usedTalentCount
-= talentCosts
;
2980 m_usedTalentCount
= 0;
2983 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2984 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2986 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2987 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2988 SetFreePrimaryProffesions(freeProfs
);
2991 // remove dependent skill
2992 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2995 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2996 if(!prev_spell
) // first rank, remove skill
2997 SetSkill(spellLearnSkill
->skill
,0,0);
3000 // search prev. skill setting by spell ranks chain
3001 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3002 while(!prevSkill
&& prev_spell
)
3004 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3005 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3008 if(!prevSkill
) // not found prev skill setting, remove skill
3009 SetSkill(spellLearnSkill
->skill
,0,0);
3010 else // set to prev. skill setting values
3012 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3013 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3015 if(skill_value
> prevSkill
->value
)
3016 skill_value
= prevSkill
->value
;
3018 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3020 if(skill_max_value
> new_skill_max_value
)
3021 skill_max_value
= new_skill_max_value
;
3023 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3030 // not ranked skills
3031 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3032 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3034 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3036 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3040 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3041 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3042 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
3044 // not reset skills for professions and racial abilities
3045 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3046 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3049 SetSkill(pSkill
->id
, 0, 0 );
3054 // remove dependent spells
3055 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3056 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3058 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3059 removeSpell(itr2
->second
.spell
, disabled
);
3061 // activate lesser rank in spellbook/action bar, and cast it if need
3062 bool prev_activate
= false;
3064 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3066 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3068 // if talent then lesser rank also talent and need learn
3070 learnSpell (prev_id
,false);
3071 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3072 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3074 // need manually update dependence state (learn spell ignore like attempts)
3075 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3076 if (prev_itr
!= m_spells
.end())
3078 if(prev_itr
->second
->dependent
!= cur_dependent
)
3080 prev_itr
->second
->dependent
= cur_dependent
;
3081 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3082 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3085 // now re-learn if need re-activate
3086 if(cur_active
&& !prev_itr
->second
->active
)
3088 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3090 if(update_action_bar_for_low_rank
)
3092 // downgrade spell ranks in spellbook and action bar
3093 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3094 data
<< uint16(spell_id
);
3095 data
<< uint16(prev_id
);
3096 GetSession()->SendPacket( &data
);
3097 prev_activate
= true;
3105 // remove from spell book if not replaced by lesser rank
3108 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3109 data
<< uint16(spell_id
);
3110 GetSession()->SendPacket(&data
);
3114 void Player::RemoveArenaSpellCooldowns()
3116 // remove cooldowns on spells that has < 15 min CD
3117 SpellCooldowns::iterator itr
, next
;
3118 // iterate spell cooldowns
3119 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3123 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3124 // check if spellentry is present and if the cooldown is less than 15 mins
3126 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
3127 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
3130 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3131 data
<< uint32(itr
->first
);
3133 GetSession()->SendPacket(&data
);
3135 m_spellCooldowns
.erase(itr
);
3140 void Player::RemoveAllSpellCooldown()
3142 if(!m_spellCooldowns
.empty())
3144 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3146 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3147 data
<< uint32(itr
->first
);
3148 data
<< uint64(GetGUID());
3149 GetSession()->SendPacket(&data
);
3151 m_spellCooldowns
.clear();
3155 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3157 m_spellCooldowns
.clear();
3159 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3163 time_t curTime
= time(NULL
);
3167 Field
*fields
= result
->Fetch();
3169 uint32 spell_id
= fields
[0].GetUInt32();
3170 uint32 item_id
= fields
[1].GetUInt32();
3171 time_t db_time
= (time_t)fields
[2].GetUInt64();
3173 if(!sSpellStore
.LookupEntry(spell_id
))
3175 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3179 // skip outdated cooldown
3180 if(db_time
<= curTime
)
3183 AddSpellCooldown(spell_id
, item_id
, db_time
);
3185 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3187 while( result
->NextRow() );
3193 void Player::_SaveSpellCooldowns()
3195 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3197 time_t curTime
= time(NULL
);
3199 // remove outdated and save active
3200 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3202 if(itr
->second
.end
<= curTime
)
3203 m_spellCooldowns
.erase(itr
++);
3206 CharacterDatabase
.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD
"')", GetGUIDLow(), itr
->first
, itr
->second
.itemid
, uint64(itr
->second
.end
));
3212 uint32
Player::resetTalentsCost() const
3214 // The first time reset costs 1 gold
3215 if(m_resetTalentsCost
< 1*GOLD
)
3218 else if(m_resetTalentsCost
< 5*GOLD
)
3220 // After that it increases in increments of 5 gold
3221 else if(m_resetTalentsCost
< 10*GOLD
)
3225 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3228 // This cost will be reduced by a rate of 5 gold per month
3229 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3230 // to a minimum of 10 gold.
3231 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3235 // After that it increases in increments of 5 gold
3236 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3237 // until it hits a cap of 50 gold.
3238 if(new_cost
> 50*GOLD
)
3245 bool Player::resetTalents(bool no_cost
)
3247 // not need after this call
3248 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3250 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3251 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3254 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3256 if (m_usedTalentCount
== 0)
3258 SetFreeTalentPoints(talentPointsForLevel
);
3266 cost
= resetTalentsCost();
3268 if (GetMoney() < cost
)
3270 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3275 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3277 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3279 if (!talentInfo
) continue;
3281 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3286 // unlearn only talents for character class
3287 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3288 // to prevent unexpected lost normal learned spell skip another class talents
3289 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3292 for (int j
= 0; j
< 5; j
++)
3294 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3296 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3302 // remove learned spells (all ranks)
3303 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3305 // unlearn if first rank is talent or learned by talent
3306 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3308 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3309 itr
= GetSpellMap().begin();
3318 SetFreeTalentPoints(talentPointsForLevel
);
3322 ModifyMoney(-(int32
)cost
);
3324 m_resetTalentsCost
= cost
;
3325 m_resetTalentsTime
= time(NULL
);
3328 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3329 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3334 Mail
* Player::GetMail(uint32 id
)
3336 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3338 if ((*itr
)->messageID
== id
)
3346 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3350 Object::_SetCreateBits(updateMask
, target
);
3354 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3356 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3357 updateMask
->SetBit(index
);
3362 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3366 Object::_SetUpdateBits(updateMask
, target
);
3370 Object::_SetUpdateBits(updateMask
, target
);
3371 *updateMask
&= updateVisualBits
;
3375 void Player::InitVisibleBits()
3377 updateVisualBits
.SetCount(PLAYER_END
);
3379 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3380 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3381 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3382 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3383 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3384 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3385 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3386 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3387 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3388 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3389 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3390 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3391 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3392 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3393 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3394 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3395 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3396 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3397 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3398 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3399 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3400 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3401 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3402 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3403 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3404 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3405 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3406 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3407 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3408 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3409 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3410 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3411 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3412 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3413 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3414 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3415 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3416 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3417 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3418 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3419 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3420 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3421 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3422 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3423 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3424 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3425 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3426 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3427 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3428 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3429 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3430 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3431 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3432 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3433 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3435 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3436 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3437 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3438 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3439 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3440 updateVisualBits
.SetBit(PLAYER_BYTES
);
3441 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3442 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3443 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3444 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3446 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3447 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3448 updateVisualBits
.SetBit(i
);
3450 // Players visible items are not inventory stuff
3451 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3453 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3456 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3457 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3460 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3462 // item enchantments
3463 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3464 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3466 // random properties
3467 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3468 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3469 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3472 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3475 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3477 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3479 if(m_items
[i
] == NULL
)
3482 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3487 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3489 if(m_items
[i
] == NULL
)
3492 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3494 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3496 if(m_items
[i
] == NULL
)
3499 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3503 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3506 void Player::DestroyForPlayer( Player
*target
) const
3508 Unit::DestroyForPlayer( target
);
3510 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3512 if(m_items
[i
] == NULL
)
3515 m_items
[i
]->DestroyForPlayer( target
);
3520 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3522 if(m_items
[i
] == NULL
)
3525 m_items
[i
]->DestroyForPlayer( target
);
3527 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3529 if(m_items
[i
] == NULL
)
3532 m_items
[i
]->DestroyForPlayer( target
);
3537 bool Player::HasSpell(uint32 spell
) const
3539 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3540 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3541 !itr
->second
->disabled
);
3544 bool Player::HasActiveSpell(uint32 spell
) const
3546 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3547 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3548 itr
->second
->active
&& !itr
->second
->disabled
);
3551 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3554 return TRAINER_SPELL_RED
;
3556 if (!trainer_spell
->learned_spell
)
3557 return TRAINER_SPELL_RED
;
3560 if(HasSpell(trainer_spell
->learned_spell
))
3561 return TRAINER_SPELL_GRAY
;
3563 // check race/class requirement
3564 if(!IsSpellFitByClassAndRace(trainer_spell
->learned_spell
))
3565 return TRAINER_SPELL_RED
;
3567 // check level requirement
3568 if(getLevel() < trainer_spell
->reqlevel
)
3569 return TRAINER_SPELL_RED
;
3571 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learned_spell
))
3573 // check prev.rank requirement
3574 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3575 return TRAINER_SPELL_RED
;
3577 // check additional spell requirement
3578 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3579 return TRAINER_SPELL_RED
;
3582 // check skill requirement
3583 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3584 return TRAINER_SPELL_RED
;
3586 // exist, already checked at loading
3587 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learned_spell
);
3589 // secondary prof. or not prof. spell
3590 uint32 skill
= spell
->EffectMiscValue
[1];
3592 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3593 return TRAINER_SPELL_GREEN
;
3595 // check primary prof. limit
3596 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3597 return TRAINER_SPELL_RED
;
3599 return TRAINER_SPELL_GREEN
;
3602 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3604 uint32 guid
= GUID_LOPART(playerguid
);
3606 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3607 // bones will be deleted by corpse/bones deleting thread shortly
3608 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3610 // remove from guild
3611 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3614 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3616 guild
->DelMember(guid
);
3619 // remove from arena teams
3620 LeaveAllArenaTeams(playerguid
);
3622 // the player was uninvited already on logout so just remove from group
3623 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3626 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3628 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3631 RemoveFromGroup(group
, playerguid
);
3635 // remove signs from petitions (also remove petitions if owner);
3636 RemovePetitionsAndSigns(playerguid
, 10);
3638 // return back all mails with COD and Item 0 1 2 3 4 5 6
3639 QueryResult
*resultMail
= CharacterDatabase
.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid
);
3644 Field
*fields
= resultMail
->Fetch();
3646 uint32 mail_id
= fields
[0].GetUInt32();
3647 uint16 mailTemplateId
= fields
[1].GetUInt16();
3648 uint32 sender
= fields
[2].GetUInt32();
3649 std::string subject
= fields
[3].GetCppString();
3650 uint32 itemTextId
= fields
[4].GetUInt32();
3651 uint32 money
= fields
[5].GetUInt32();
3652 bool has_items
= fields
[6].GetBool();
3654 //we can return mail now
3655 //so firstly delete the old one
3656 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3661 // data needs to be at first place for Item::LoadFromDB
3662 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id
);
3667 Field
*fields2
= resultItems
->Fetch();
3669 uint32 item_guidlow
= fields2
[1].GetUInt32();
3670 uint32 item_template
= fields2
[2].GetUInt32();
3672 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3675 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3679 Item
*pItem
= NewItemOrBag(itemProto
);
3680 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3682 pItem
->FSetState(ITEM_REMOVED
);
3683 pItem
->SaveToDB(); // it also deletes item object !
3687 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3689 while (resultItems
->NextRow());
3695 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3697 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3699 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3701 while (resultMail
->NextRow());
3706 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3707 // Get guids of character's pets, will deleted in transaction
3708 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3710 // NOW we can finally clear other DB data related to character
3711 CharacterDatabase
.BeginTransaction();
3716 Field
*fields3
= resultPets
->Fetch();
3717 uint32 petguidlow
= fields3
[0].GetUInt32();
3718 Pet::DeleteFromDB(petguidlow
);
3719 } while (resultPets
->NextRow());
3723 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3724 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3725 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3726 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3727 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3728 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3729 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3730 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3731 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3732 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3733 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3734 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3735 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3736 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3737 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3738 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3739 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3740 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3741 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3742 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3743 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3744 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3745 CharacterDatabase
.CommitTransaction();
3747 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3748 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3751 void Player::SetMovement(PlayerMovementType pType
)
3756 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3757 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3758 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3759 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3761 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3764 data
.append(GetPackGUID());
3766 GetSession()->SendPacket( &data
);
3770 - a resurrectable corpse must not be loaded for the player (only bones)
3771 - the player must be in world
3773 void Player::BuildPlayerRepop()
3775 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3776 data
.append(GetPackGUID());
3777 GetSession()->SendPacket(&data
);
3779 if(getRace() == RACE_NIGHTELF
)
3780 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)
3781 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3783 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3784 // there must be SMSG.STOP_MIRROR_TIMER
3785 // there we must send 888 opcode
3787 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3790 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3794 // create a corpse and place it at the player's location
3796 Corpse
*corpse
= GetCorpse();
3799 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3802 GetMap()->Add(corpse
);
3804 // convert player body to ghost
3807 SetMovement(MOVE_WATER_WALK
);
3808 if(!GetSession()->isLogingOut())
3809 SetMovement(MOVE_UNROOT
);
3811 // BG - remove insignia related
3812 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3814 SendCorpseReclaimDelay();
3816 // to prevent cheating
3817 corpse
->ResetGhostTime();
3819 StopMirrorTimers(); //disable timers(bars)
3821 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3823 // set and clear other
3824 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3827 void Player::SendDelayResponse(const uint32 ml_seconds
)
3829 //FIXME: is this delay time arg really need? 50msec by default in code
3830 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3831 data
<< (uint32
)time(NULL
);
3833 GetSession()->SendPacket( &data
);
3836 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3838 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3843 GetSession()->SendPacket(&data
);
3845 // speed change, land walk
3847 // remove death flag + set aura
3848 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3849 if(getRace() == RACE_NIGHTELF
)
3850 RemoveAurasDueToSpell(20584); // speed bonuses
3851 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3853 setDeathState(ALIVE
);
3855 SetMovement(MOVE_LAND_WALK
);
3856 SetMovement(MOVE_UNROOT
);
3860 // set health/powers (0- will be set in caller)
3861 if(restore_percent
>0.0f
)
3863 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3864 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3865 SetPower(POWER_RAGE
, 0);
3866 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3869 // update visibility
3870 ObjectAccessor::UpdateVisibilityForPlayer(this);
3872 // some items limited to specific map
3873 DestroyZoneLimitedItem( true, GetZoneId());
3878 //Characters from level 1-10 are not affected by resurrection sickness.
3879 //Characters from level 11-19 will suffer from one minute of sickness
3880 //for each level they are above 10.
3881 //Characters level 20 and up suffer from ten minutes of sickness.
3882 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3884 if(int32(getLevel()) >= startLevel
)
3886 // set resurrection sickness
3887 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3889 // not full duration
3890 if(int32(getLevel()) < startLevel
+9)
3892 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3894 for(int i
=0; i
< 3; ++i
)
3896 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3898 Aur
->SetAuraDuration(delta
*1000);
3899 Aur
->SendAuraUpdate(false);
3906 void Player::KillPlayer()
3908 SetMovement(MOVE_ROOT
);
3910 StopMirrorTimers(); //disable timers(bars)
3912 setDeathState(CORPSE
);
3913 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3915 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3916 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3918 // 6 minutes until repop at graveyard
3919 m_deathTimer
= 6*MINUTE
*1000;
3921 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3923 // don't create corpse at this moment, player might be falling
3925 // update visibility
3926 ObjectAccessor::UpdateObjectVisibility(this);
3929 void Player::CreateCorpse()
3931 // prevent existence 2 corpse for player
3934 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3936 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3939 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3940 GetPositionY(), GetPositionZ(), GetOrientation()))
3946 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3947 _pb
= GetUInt32Value(PLAYER_BYTES
);
3948 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3950 uint8 race
= (uint8
)(_uf
);
3951 uint8 skin
= (uint8
)(_pb
);
3952 uint8 face
= (uint8
)(_pb
>> 8);
3953 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3954 uint8 haircolor
= (uint8
)(_pb
>> 24);
3955 uint8 facialhair
= (uint8
)(_pb2
);
3957 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3958 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3960 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3961 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3963 uint32 flags
= CORPSE_FLAG_UNK2
;
3964 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3965 flags
|= CORPSE_FLAG_HIDE_HELM
;
3966 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3967 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3968 if(InBattleGround())
3969 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3970 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3972 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3974 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3977 uint16 iIventoryType
;
3979 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3983 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3984 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3986 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3987 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3991 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3992 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3994 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3997 // register for player, but not show
3998 ObjectAccessor::Instance().AddCorpse(corpse
);
4001 void Player::SpawnCorpseBones()
4003 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4004 SaveToDB(); // prevent loading as ghost without corpse
4007 Corpse
* Player::GetCorpse() const
4009 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4012 void Player::DurabilityLossAll(double percent
, bool inventory
)
4014 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4015 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4016 DurabilityLoss(pItem
,percent
);
4020 // bags not have durability
4021 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4023 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4024 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4025 DurabilityLoss(pItem
,percent
);
4027 // keys not have durability
4028 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4030 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4031 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4032 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4033 if(Item
* pItem
= GetItemByPos( i
, j
))
4034 DurabilityLoss(pItem
,percent
);
4038 void Player::DurabilityLoss(Item
* item
, double percent
)
4043 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4048 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4050 if(pDurabilityLoss
< 1 )
4051 pDurabilityLoss
= 1;
4053 DurabilityPointsLoss(item
,pDurabilityLoss
);
4056 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4058 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4059 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4060 DurabilityPointsLoss(pItem
,points
);
4064 // bags not have durability
4065 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4067 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4068 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4069 DurabilityPointsLoss(pItem
,points
);
4071 // keys not have durability
4072 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4074 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4075 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4076 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4077 if(Item
* pItem
= GetItemByPos( i
, j
))
4078 DurabilityPointsLoss(pItem
,points
);
4082 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4084 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4085 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4086 int32 pNewDurability
= pOldDurability
- points
;
4088 if (pNewDurability
< 0)
4090 else if (pNewDurability
> pMaxDurability
)
4091 pNewDurability
= pMaxDurability
;
4093 if (pOldDurability
!= pNewDurability
)
4095 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4096 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4097 _ApplyItemMods(item
,item
->GetSlot(), false);
4099 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4101 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4102 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4103 _ApplyItemMods(item
,item
->GetSlot(), true);
4105 item
->SetState(ITEM_CHANGED
, this);
4109 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4111 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4112 DurabilityPointsLoss(pItem
,1);
4115 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4117 uint32 TotalCost
= 0;
4118 // equipped, backpack, bags itself
4119 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4120 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4122 // bank, buyback and keys not repaired
4124 // items in inventory bags
4125 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4126 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4127 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4131 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4133 Item
* item
= GetItemByPos(pos
);
4135 uint32 TotalCost
= 0;
4139 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4143 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4147 uint32 LostDurability
= maxDurability
- curDurability
;
4148 if(LostDurability
>0)
4150 ItemPrototype
const *ditemProto
= item
->GetProto();
4152 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4155 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4159 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4160 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4161 if(!dQualitymodEntry
)
4163 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4167 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4168 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4170 costs
= uint32(costs
* discountMod
);
4172 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4177 if (GetGuildId()==0)
4179 DEBUG_LOG("You are not member of a guild");
4183 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4187 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4189 DEBUG_LOG("You do not have rights to withdraw for repairs");
4193 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4195 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4199 if (pGuild
->GetGuildBankMoney() < costs
)
4201 DEBUG_LOG("There is not enough money in bank");
4205 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4208 else if (GetMoney() < costs
)
4210 DEBUG_LOG("You do not have enough money");
4214 ModifyMoney( -int32(costs
) );
4218 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4219 item
->SetState(ITEM_CHANGED
, this);
4221 // reapply mods for total broken and repaired item if equipped
4222 if(IsEquipmentPos(pos
) && !curDurability
)
4223 _ApplyItemMods(item
,pos
& 255, true);
4227 void Player::RepopAtGraveyard()
4229 // note: this can be called also when the player is alive
4230 // for example from WorldSession::HandleMovementOpcodes
4232 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4234 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4235 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4237 ResurrectPlayer(0.5f
);
4241 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4243 // Special handle for battleground maps
4244 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4246 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4247 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4249 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4251 // stop countdown until repop
4254 // if no grave found, stay at the current location
4255 // and don't show spirit healer location
4258 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4259 if(isDead()) // not send if alive, because it used in TeleportTo()
4261 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4262 data
<< ClosestGrave
->map_id
;
4263 data
<< ClosestGrave
->x
;
4264 data
<< ClosestGrave
->y
;
4265 data
<< ClosestGrave
->z
;
4266 GetSession()->SendPacket(&data
);
4271 void Player::JoinedChannel(Channel
*c
)
4273 m_channels
.push_back(c
);
4276 void Player::LeftChannel(Channel
*c
)
4278 m_channels
.remove(c
);
4281 void Player::CleanupChannels()
4283 while(!m_channels
.empty())
4285 Channel
* ch
= *m_channels
.begin();
4286 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4287 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4288 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4289 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4292 sLog
.outDebug("Player: channels cleaned up!");
4295 void Player::UpdateLocalChannels(uint32 newZone
)
4297 if(m_channels
.empty())
4300 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4304 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4308 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4310 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4314 // skip non built-in channels
4315 if(!(*i
)->IsConstant())
4318 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4322 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4326 char new_channel_name_buf
[100];
4327 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4328 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4330 if((*i
)!=new_channel
)
4332 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4334 // leave old channel
4335 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4336 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4337 LeftChannel(*i
); // remove from player's channel list
4338 cMgr
->LeftChannel(name
); // delete if empty
4341 sLog
.outDebug("Player: channels cleaned up!");
4344 void Player::LeaveLFGChannel()
4346 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4350 (*i
)->Leave(GetGUID());
4356 void Player::UpdateDefense()
4358 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4360 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4362 // update dependent from defense skill part
4363 UpdateDefenseBonusesMod();
4367 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4369 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4371 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4380 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4383 if(amount
<= -100.0f
)
4386 val
= (100.0f
+ amount
) / 100.0f
;
4387 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4391 if(!CanModifyStats())
4396 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4397 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4398 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4399 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4404 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4406 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4408 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4412 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4415 return m_auraBaseMod
[modGroup
][modType
];
4418 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4420 if(modGroup
>= BASEMOD_END
)
4422 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4426 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4429 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4432 uint32
Player::GetShieldBlockValue() const
4434 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4436 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
) * 0.5f
- 10;
4438 value
= (value
< 0) ? 0 : value
;
4440 return uint32(value
);
4443 float Player::GetMeleeCritFromAgility()
4445 uint32 level
= getLevel();
4446 uint32 pclass
= getClass();
4448 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4450 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4451 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4452 if (critBase
==NULL
|| critRatio
==NULL
)
4455 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4459 float Player::GetDodgeFromAgility()
4461 // Table for base dodge values
4462 float dodge_base
[MAX_CLASSES
] = {
4464 0.00652f
, // Paladin
4471 0.02011f
, // Warlock
4475 // Crit/agility to dodge/agility coefficient multipliers
4476 float crit_to_dodge
[MAX_CLASSES
] = {
4490 uint32 level
= getLevel();
4491 uint32 pclass
= getClass();
4493 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4495 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4496 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4497 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4500 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4501 return dodge
*100.0f
;
4504 float Player::GetSpellCritFromIntellect()
4506 uint32 level
= getLevel();
4507 uint32 pclass
= getClass();
4509 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4511 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4512 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4513 if (critBase
==NULL
|| critRatio
==NULL
)
4516 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4520 float Player::GetRatingCoefficient(CombatRating cr
) const
4522 uint32 level
= getLevel();
4524 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4526 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4528 return 1.0f
; // By default use minimum coefficient (not must be called)
4530 return Rating
->ratio
;
4533 float Player::GetRatingBonusValue(CombatRating cr
) const
4535 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4538 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4540 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4541 if (melee
>25.0f
) melee
= 25.0f
;
4542 return uint32 (melee
* damage
/100.0f
);
4545 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4547 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4548 if (ranged
>25.0f
) ranged
=25.0f
;
4549 return uint32 (ranged
* damage
/100.0f
);
4552 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4554 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4555 // In wow script resilience limited to 25%
4558 return uint32 (spell
* damage
/ 100.0f
);
4561 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4563 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4564 // Dot resilience not limited (limit it by 100%)
4565 if (spellDot
> 100.0f
)
4567 return uint32 (spellDot
* damage
/ 100.0f
);
4570 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4575 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4577 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4584 float Player::OCTRegenHPPerSpirit()
4586 uint32 level
= getLevel();
4587 uint32 pclass
= getClass();
4589 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4591 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4592 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4593 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4596 // Formula from PaperDollFrame script
4597 float spirit
= GetStat(STAT_SPIRIT
);
4598 float baseSpirit
= spirit
;
4599 if (baseSpirit
>50) baseSpirit
= 50;
4600 float moreSpirit
= spirit
- baseSpirit
;
4601 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4605 float Player::OCTRegenMPPerSpirit()
4607 uint32 level
= getLevel();
4608 uint32 pclass
= getClass();
4610 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4612 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4613 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4614 if (moreRatio
==NULL
)
4617 // Formula get from PaperDollFrame script
4618 float spirit
= GetStat(STAT_SPIRIT
);
4619 float regen
= spirit
* moreRatio
->ratio
;
4623 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4625 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4627 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4628 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4629 // stat used stored in miscValueB for this aura
4630 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4631 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4632 if ((*i
)->GetMiscValue() & (1<<cr
))
4633 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4636 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4638 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4639 float RatingChange
= 0.0f
;
4641 bool affectStats
= CanModifyStats();
4645 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4646 case CR_DEFENSE_SKILL
:
4647 UpdateDefenseBonusesMod();
4650 UpdateDodgePercentage();
4653 UpdateParryPercentage();
4656 UpdateBlockPercentage();
4659 UpdateMeleeHitChances();
4662 UpdateRangedHitChances();
4665 UpdateSpellHitChances();
4670 UpdateCritPercentage(BASE_ATTACK
);
4671 UpdateCritPercentage(OFF_ATTACK
);
4674 case CR_CRIT_RANGED
:
4676 UpdateCritPercentage(RANGED_ATTACK
);
4680 UpdateAllSpellCritChances();
4682 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4683 case CR_HIT_TAKEN_RANGED
:
4685 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4687 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4688 case CR_CRIT_TAKEN_RANGED
:
4690 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4692 case CR_HASTE_MELEE
:
4693 RatingChange
= value
/ RatingCoeffecient
;
4694 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4695 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4697 case CR_HASTE_RANGED
:
4698 RatingChange
= value
/ RatingCoeffecient
;
4699 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4701 case CR_HASTE_SPELL
:
4702 RatingChange
= value
/ RatingCoeffecient
;
4703 ApplyCastTimePercentMod(RatingChange
,apply
);
4705 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4706 case CR_WEAPON_SKILL_OFFHAND
:
4707 case CR_WEAPON_SKILL_RANGED
:
4712 UpdateExpertise(BASE_ATTACK
);
4713 UpdateExpertise(OFF_ATTACK
);
4719 void Player::SetRegularAttackTime()
4721 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4723 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4724 if(tmpitem
&& !tmpitem
->IsBroken())
4726 ItemPrototype
const *proto
= tmpitem
->GetProto();
4728 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4730 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4735 //skill+step, checking for max value
4736 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4742 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4743 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4746 if(i
>=PLAYER_MAX_SKILLS
)
4749 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4750 uint32 value
= SKILL_VALUE(data
);
4751 uint32 max
= SKILL_MAX(data
);
4753 if ((!max
) || (!value
) || (value
>= max
))
4756 if (value
*512 < max
*urand(0,512))
4758 uint32 new_value
= value
+step
;
4762 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4763 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4770 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4772 if ( SkillValue
>= GrayLevel
)
4773 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4774 if ( SkillValue
>= GreenLevel
)
4775 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4776 if ( SkillValue
>= YellowLevel
)
4777 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4778 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4781 bool Player::UpdateCraftSkill(uint32 spellid
)
4783 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4785 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4786 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4788 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4790 if(_spell_idx
->second
->skillId
)
4792 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4794 // Alchemy Discoveries here
4795 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4796 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4798 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4799 learnSpell(discoveredSpell
,false);
4802 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4804 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4805 _spell_idx
->second
->max_value
,
4806 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4807 _spell_idx
->second
->min_value
),
4814 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4816 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4818 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4820 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4823 case SKILL_HERBALISM
:
4824 case SKILL_LOCKPICKING
:
4825 case SKILL_JEWELCRAFTING
:
4826 case SKILL_INSCRIPTION
:
4827 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4828 case SKILL_SKINNING
:
4829 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4830 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4832 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4834 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4835 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4837 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4842 bool Player::UpdateFishingSkill()
4844 sLog
.outDebug("UpdateFishingSkill");
4846 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4848 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4850 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4852 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4855 // levels sync. with spell requirement for skill levels to learn
4856 // bonus abilities in sSkillLineAbilityStore
4857 // Used only to avoid scan DBC at each skill grow
4858 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4860 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4862 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4866 if(Chance
<= 0) // speedup in 0 chance case
4868 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4873 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4874 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4875 if ( i
>= PLAYER_MAX_SKILLS
)
4878 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4879 uint16 SkillValue
= SKILL_VALUE(data
);
4880 uint16 MaxValue
= SKILL_MAX(data
);
4882 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4885 int32 Roll
= irand(1,1000);
4887 if ( Roll
<= Chance
)
4889 uint32 new_value
= SkillValue
+step
;
4890 if(new_value
> MaxValue
)
4891 new_value
= MaxValue
;
4893 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4894 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
4896 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
4898 learnSkillRewardedSpells( SkillId
, new_value
);
4902 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4903 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4907 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4911 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4913 // no skill gain in pvp
4914 Unit
*pVictim
= getVictim();
4915 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4919 return; // always maximized SKILL_FERAL_COMBAT in fact
4921 if(m_form
== FORM_TREE
)
4922 return; // use weapon but not skill up
4924 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4930 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4933 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4934 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4935 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4941 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4943 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4947 UpdateAllCritPercentages();
4950 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
4952 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4953 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4954 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4955 if(moblevel
< greylevel
)
4958 if (moblevel
> plevel
+ 5)
4959 moblevel
= plevel
+ 5;
4961 uint32 lvldif
= moblevel
- greylevel
;
4965 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4969 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4972 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4973 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4976 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4978 if(roll_chance_f(chance
))
4983 UpdateWeaponSkill(attType
);
4989 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4991 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4992 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4994 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4995 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4996 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4998 if(talent
) // permanent bonus stored in high part
4999 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5000 else // temporary/item bonus stored in low part
5001 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5006 void Player::UpdateSkillsForLevel()
5008 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5009 uint32 maxSkill
= GetMaxSkillValueForLevel();
5011 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5013 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5014 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5016 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5018 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5022 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5025 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5026 uint32 max
= SKILL_MAX(data
);
5027 uint32 val
= SKILL_VALUE(data
);
5029 /// update only level dependent max skill values
5032 /// miximize skill always
5034 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5035 /// update max skill value if current max skill not maximized
5036 else if(max
!= maxconfskill
)
5037 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5042 void Player::UpdateSkillsToMaxSkillsForLevel()
5044 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5045 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5047 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5048 if( IsProfessionOrRidingSkill(pskill
))
5050 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5052 uint32 max
= SKILL_MAX(data
);
5055 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5057 if(pskill
== SKILL_DEFENSE
)
5058 UpdateDefenseBonusesMod();
5062 // This functions sets a skill line value (and adds if doesn't exist yet)
5063 // To "remove" a skill line, set it's values to zero
5064 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5070 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5071 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5073 if(i
<PLAYER_MAX_SKILLS
) //has skill
5077 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5078 learnSkillRewardedSpells(id
, currVal
);
5079 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5083 // clear skill fields
5084 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5085 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5086 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5088 // remove all spells that related to this skill
5089 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5090 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5091 if (pAbility
->skillId
==id
)
5092 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5095 else if(currVal
) //add
5097 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5098 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5100 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5103 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5106 // enable unlearn button for primary professions only
5107 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5108 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5110 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5111 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5112 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5114 // apply skill bonuses
5115 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5117 // temporary bonuses
5118 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5119 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5120 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5121 (*i
)->ApplyModifier(true);
5123 // permanent bonuses
5124 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5125 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5126 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5127 (*i
)->ApplyModifier(true);
5129 // Learn all spells for skill
5130 learnSkillRewardedSpells(id
, currVal
);
5136 bool Player::HasSkill(uint32 skill
) const
5138 if(!skill
)return false;
5139 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5141 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5149 uint16
Player::GetSkillValue(uint32 skill
) const
5154 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5156 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5158 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5160 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5161 result
+= SKILL_TEMP_BONUS(bonus
);
5162 result
+= SKILL_PERM_BONUS(bonus
);
5163 return result
< 0 ? 0 : result
;
5169 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5172 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5174 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5176 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5178 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5179 result
+= SKILL_TEMP_BONUS(bonus
);
5180 result
+= SKILL_PERM_BONUS(bonus
);
5181 return result
< 0 ? 0 : result
;
5187 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5190 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5192 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5194 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5200 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5203 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5205 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5207 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5208 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5209 return result
< 0 ? 0 : result
;
5215 uint16
Player::GetPureSkillValue(uint32 skill
) const
5218 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5220 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5222 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5228 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5233 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5235 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5237 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5244 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5249 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5251 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5253 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5260 void Player::SendInitialActionButtons()
5262 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5264 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5265 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5267 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5268 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5270 data
<< uint16(itr
->second
.action
);
5271 data
<< uint8(itr
->second
.misc
);
5272 data
<< uint8(itr
->second
.type
);
5280 GetSession()->SendPacket( &data
);
5281 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5284 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5286 if(button
>= MAX_ACTION_BUTTONS
)
5288 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5292 // check cheating with adding non-known spells to action bar
5293 if(type
==ACTION_BUTTON_SPELL
)
5295 if(!sSpellStore
.LookupEntry(action
))
5297 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5301 if(!HasSpell(action
))
5303 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5308 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5310 if (buttonItr
==m_actionButtons
.end())
5311 { // just add new button
5312 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5315 { // change state of current button
5316 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5317 buttonItr
->second
= ActionButton(action
,type
,misc
);
5318 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5321 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5324 void Player::removeActionButton(uint8 button
)
5326 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5327 if (buttonItr
==m_actionButtons
.end())
5330 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5331 m_actionButtons
.erase(buttonItr
); // new and not saved
5333 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5335 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5338 void Player::SetDontMove(bool dontMove
)
5340 m_dontMove
= dontMove
;
5343 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5345 // prevent crash when a bad coord is sent by the client
5346 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5348 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5354 const float old_x
= GetPositionX();
5355 const float old_y
= GetPositionY();
5356 const float old_z
= GetPositionZ();
5357 const float old_r
= GetOrientation();
5359 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5361 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5362 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5364 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5366 // move and update visible state if need
5367 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5369 // reread after Map::Relocation
5376 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5377 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5380 // code block for underwater state update
5381 UpdateUnderwaterState(m
, x
, y
, z
);
5383 CheckExploreSystem();
5388 void Player::SaveRecallPosition()
5390 m_recallMap
= GetMapId();
5391 m_recallX
= GetPositionX();
5392 m_recallY
= GetPositionY();
5393 m_recallZ
= GetPositionZ();
5394 m_recallO
= GetOrientation();
5397 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5399 GetMap()->MessageBroadcast(this, data
, self
);
5402 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5404 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5407 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5409 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5412 void Player::SendDirectMessage(WorldPacket
*data
)
5414 GetSession()->SendPacket(data
);
5417 void Player::CheckExploreSystem()
5425 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5426 if(areaFlag
==0xffff)
5428 int offset
= areaFlag
/ 32;
5432 sLog
.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5436 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5437 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5439 if( !(currFields
& val
) )
5441 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5443 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5445 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5448 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5450 else if(p
->area_level
> 0)
5452 uint32 area
= p
->ID
;
5453 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5455 SendExplorationExperience(area
,0);
5459 int32 diff
= int32(getLevel()) - p
->area_level
;
5463 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5467 int32 exploration_percent
= (100-((diff
-5)*5));
5468 if (exploration_percent
> 100)
5469 exploration_percent
= 100;
5470 else if (exploration_percent
< 0)
5471 exploration_percent
= 0;
5473 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5477 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5481 SendExplorationExperience(area
,XP
);
5483 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5488 uint32
Player::TeamForRace(uint8 race
)
5490 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5493 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5497 switch(rEntry
->TeamID
)
5499 case 7: return ALLIANCE
;
5500 case 1: return HORDE
;
5503 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5507 uint32
Player::getFactionForRace(uint8 race
)
5509 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5512 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5516 return rEntry
->FactionID
;
5519 void Player::setFactionForRace(uint8 race
)
5521 m_team
= TeamForRace(race
);
5522 setFaction( getFactionForRace(race
) );
5525 void Player::UpdateReputation() const
5527 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5529 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5531 SendFactionState(&(itr
->second
));
5535 void Player::SendFactionState(FactionState
const* faction
) const
5537 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5539 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5540 data
<< (float) 0; // unk 2.4.0
5541 data
<< (uint8
) 0; // wotlk 8634
5542 data
<< (uint32
) 1; // count
5544 data
<< (uint32
) faction
->ReputationListID
;
5545 data
<< (uint32
) faction
->Standing
;
5547 GetSession()->SendPacket(&data
);
5551 void Player::SendInitialReputations()
5553 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5554 data
<< uint32 (0x00000080);
5558 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5560 // fill in absent fields
5561 for (; a
!= itr
->first
; a
++)
5563 data
<< uint8 (0x00);
5564 data
<< uint32 (0x00000000);
5567 // fill in encountered data
5568 data
<< uint8 (itr
->second
.Flags
);
5569 data
<< uint32 (itr
->second
.Standing
);
5574 // fill in absent fields
5575 for (; a
!= 128; a
++)
5577 data
<< uint8 (0x00);
5578 data
<< uint32 (0x00000000);
5581 GetSession()->SendPacket(&data
);
5584 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5586 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5587 if (itr
!= m_factions
.end())
5588 return &itr
->second
;
5593 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5595 // not allow declare war to own faction
5596 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5600 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5604 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5606 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5608 faction
->Changed
= true;
5611 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5613 // always invisible or hidden faction can't be inactive
5614 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5618 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5622 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5624 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5626 faction
->Changed
= true;
5629 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5631 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5633 if(!factionTemplateEntry
)
5636 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5639 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5641 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5645 if(factionEntry
->reputationListID
< 0)
5648 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5649 if (itr
== m_factions
.end())
5652 SetFactionVisible(&itr
->second
);
5655 void Player::SetFactionVisible(FactionState
* faction
)
5657 // always invisible or hidden faction can't be make visible
5658 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5662 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5665 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5666 faction
->Changed
= true;
5668 if(!m_session
->PlayerLoading())
5670 // make faction visible in reputation list at client
5671 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5672 data
<< faction
->ReputationListID
;
5673 GetSession()->SendPacket(&data
);
5677 void Player::SetInitialFactions()
5679 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5681 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5683 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5685 FactionState newFaction
;
5686 newFaction
.ID
= factionEntry
->ID
;
5687 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5688 newFaction
.Standing
= 0;
5689 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5690 newFaction
.Changed
= true;
5692 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5697 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5702 uint32 raceMask
= getRaceMask();
5703 uint32 classMask
= getClassMask();
5704 for (int i
=0; i
< 4; i
++)
5706 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5707 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5708 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5709 return factionEntry
->ReputationFlags
[i
];
5714 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5719 uint32 raceMask
= getRaceMask();
5720 uint32 classMask
= getClassMask();
5721 for (int i
=0; i
< 4; i
++)
5723 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5724 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5725 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5726 return factionEntry
->BaseRepValue
[i
];
5729 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5733 int32
Player::GetReputation(uint32 faction_id
) const
5735 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5739 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5743 return GetReputation(factionEntry
);
5746 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5748 // Faction without recorded reputation. Just ignore.
5752 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5753 if (itr
!= m_factions
.end())
5754 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5759 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5761 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5763 return MIN_REPUTATION_RANK
;
5765 return GetReputationRank(factionEntry
);
5768 ReputationRank
Player::ReputationToRank(int32 standing
) const
5770 int32 Limit
= Reputation_Cap
+ 1;
5771 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5773 Limit
-= ReputationRank_Length
[i
];
5774 if (standing
>= Limit
)
5775 return ReputationRank(i
);
5777 return MIN_REPUTATION_RANK
;
5780 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5782 int32 Reputation
= GetReputation(factionEntry
);
5783 return ReputationToRank(Reputation
);
5786 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5788 int32 Reputation
= GetBaseReputation(factionEntry
);
5789 return ReputationToRank(Reputation
);
5792 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5794 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5796 if(!factionTemplateEntry
)
5798 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5802 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5804 // Faction without recorded reputation. Just ignore.
5808 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5811 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5813 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5817 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5819 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5820 if(factionEntryCalc
)
5821 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5826 return ModifyOneFactionReputation(factionEntry
, standing
);
5829 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5831 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5832 if (itr
!= m_factions
.end())
5834 int32 BaseRep
= GetBaseReputation(factionEntry
);
5835 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5837 if (new_rep
> Reputation_Cap
)
5838 new_rep
= Reputation_Cap
;
5840 if (new_rep
< Reputation_Bottom
)
5841 new_rep
= Reputation_Bottom
;
5843 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5844 SetFactionAtWar(&itr
->second
,true);
5846 itr
->second
.Standing
= new_rep
- BaseRep
;
5847 itr
->second
.Changed
= true;
5849 SetFactionVisible(&itr
->second
);
5851 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5853 if(uint32 questid
= GetQuestSlotQuestId(i
))
5855 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5856 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5858 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5859 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5861 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5862 if ( CanCompleteQuest( questid
) )
5863 CompleteQuest( questid
);
5865 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5867 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5868 IncompleteQuest( questid
);
5873 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5874 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5875 SendFactionState(&(itr
->second
));
5882 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5884 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5886 if(!factionTemplateEntry
)
5888 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5892 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5894 // Faction without recorded reputation. Just ignore.
5898 return SetFactionReputation(factionEntry
, standing
);
5901 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5903 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5907 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5909 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5910 if(factionEntryCalc
)
5911 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5916 return SetOneFactionReputation(factionEntry
, standing
);
5919 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5921 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5922 if (itr
!= m_factions
.end())
5924 if (standing
> Reputation_Cap
)
5925 standing
= Reputation_Cap
;
5927 if (standing
< Reputation_Bottom
)
5928 standing
= Reputation_Bottom
;
5930 int32 BaseRep
= GetBaseReputation(factionEntry
);
5931 itr
->second
.Standing
= standing
- BaseRep
;
5932 itr
->second
.Changed
= true;
5934 SetFactionVisible(&itr
->second
);
5936 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5937 SetFactionAtWar(&itr
->second
,true);
5939 SendFactionState(&(itr
->second
));
5940 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5941 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5947 //Calculate total reputation percent player gain with quest/creature level
5948 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5950 // for grey creature kill received 20%, in other case 100.
5951 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5953 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5955 percent
+= rep
> 0 ? repMod
: -repMod
;
5960 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5963 //Calculates how many reputation points player gains in victim's enemy factions
5964 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5966 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5969 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5974 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5976 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5977 donerep1
= int32(donerep1
*rate
);
5978 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5979 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5980 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5981 ModifyFactionReputation(factionEntry1
, donerep1
);
5983 // Wiki: Team factions value divided by 2
5984 if(Rep
->is_teamaward1
)
5986 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5987 if(team1_factionEntry
)
5988 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5992 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5994 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5995 donerep2
= int32(donerep2
*rate
);
5996 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5997 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5998 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5999 ModifyFactionReputation(factionEntry2
, donerep2
);
6001 // Wiki: Team factions value divided by 2
6002 if(Rep
->is_teamaward2
)
6004 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6005 if(team2_factionEntry
)
6006 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
6011 //Calculate how many reputation points player gain with the quest
6012 void Player::RewardReputation(Quest
const *pQuest
)
6014 // quest reputation reward/loss
6015 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6017 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
6019 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
6020 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
6022 ModifyFactionReputation(factionEntry
, rep
);
6026 // TODO: implement reputation spillover
6029 void Player::UpdateArenaFields(void)
6031 /* arena calcs go here */
6034 void Player::UpdateHonorFields()
6036 /// called when rewarding honor and at each save
6037 uint64 now
= time(NULL
);
6038 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
6040 if(m_lastHonorUpdateTime
< today
)
6042 uint64 yesterday
= today
- DAY
;
6044 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6046 // update yesterday's contribution
6047 if(m_lastHonorUpdateTime
>= yesterday
)
6049 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6051 // this is the first update today, reset today's contribution
6052 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6053 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6057 // no honor/kills yesterday or today, reset
6058 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6059 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6063 m_lastHonorUpdateTime
= now
;
6066 ///Calculate the amount of honor gained based on the victim
6067 ///and the size of the group for which the honor is divided
6068 ///An exact honor value can also be given (overriding the calcs)
6069 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6071 // do not reward honor in arenas, but enable onkill spellproc
6074 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6077 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6083 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6084 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6087 uint64 victim_guid
= 0;
6088 uint32 victim_rank
= 0;
6090 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6091 UpdateHonorFields();
6095 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6098 victim_guid
= uVictim
->GetGUID();
6100 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6102 Player
*pVictim
= (Player
*)uVictim
;
6104 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6107 float f
= 1; //need for total kills (?? need more info)
6109 uint32 k_level
= getLevel();
6110 uint32 v_level
= pVictim
->getLevel();
6113 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6115 // [1..14] Alliance honor titles and player name
6116 // [15..28] Horde honor titles and player name
6117 // [29..38] Other title and player name
6119 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6120 // Get Killer titles, CharTitlesEntry::bit_index
6122 // title[1..14] -> rank[5..18]
6123 // title[15..28] -> rank[5..18]
6124 // title[other] -> 0
6125 if (victim_title
== 0)
6126 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6127 else if (victim_title
< 15)
6128 victim_rank
= victim_title
+ 4;
6129 else if (victim_title
< 29)
6130 victim_rank
= victim_title
- 14 + 4;
6132 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6135 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6140 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6142 int32 v_rank
=1; //need more info
6144 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6145 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6147 // count the number of playerkills in one day
6148 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6149 // and those in a lifetime
6150 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6154 Creature
*cVictim
= (Creature
*)uVictim
;
6156 if (!cVictim
->isRacialLeader())
6159 honor
= 100; // ??? need more info
6160 victim_rank
= 19; // HK: Leader
6164 if (uVictim
!= NULL
)
6166 honor
*= sWorld
.getRate(RATE_HONOR
);
6171 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6174 // honor - for show honor points in log
6175 // victim_guid - for show victim name in log
6176 // victim_rank [1..4] HK: <dishonored rank>
6177 // victim_rank [5..19] HK: <alliance\horde rank>
6178 // victim_rank [0,20+] HK: <>
6179 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6180 data
<< (uint32
) honor
;
6181 data
<< (uint64
) victim_guid
;
6182 data
<< (uint32
) victim_rank
;
6184 GetSession()->SendPacket(&data
);
6187 ModifyHonorPoints(int32(honor
));
6189 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6193 void Player::ModifyHonorPoints( int32 value
)
6197 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6198 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6200 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6203 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6206 void Player::ModifyArenaPoints( int32 value
)
6210 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6211 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6213 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6216 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6219 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6221 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6225 uint32 id
= result
->Fetch()[0].GetUInt32();
6230 uint32
Player::GetRankFromDB(uint64 guid
)
6232 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6235 uint32 v
= result
->Fetch()[0].GetUInt32();
6243 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6245 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
);
6249 uint32 id
= (*result
)[0].GetUInt32();
6254 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6256 uint32 guidLow
= GUID_LOPART(guid
);
6257 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6260 Field
* fields
= result
->Fetch();
6261 uint32 zone
= fields
[0].GetUInt32();
6266 // stored zone is zero, use generic and slow zone detection
6267 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6270 fields
= result
->Fetch();
6271 uint32 map
= fields
[0].GetUInt32();
6272 float posx
= fields
[1].GetFloat();
6273 float posy
= fields
[2].GetFloat();
6274 float posz
= fields
[3].GetFloat();
6277 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6279 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6285 void Player::UpdateArea(uint32 newArea
)
6287 // FFA_PVP flags are area and not zone id dependent
6288 // so apply them accordingly
6289 m_areaUpdateId
= newArea
;
6291 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6293 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6296 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6300 // remove ffa flag only if not ffapvp realm
6301 // removal in sanctuaries and capitals is handled in zone update
6302 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6303 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6306 UpdateAreaDependentAuras(newArea
);
6309 void Player::UpdateZone(uint32 newZone
)
6311 m_zoneUpdateId
= newZone
;
6312 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6314 // zone changed, so area changed as well, update it
6315 UpdateArea(GetAreaId());
6317 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6321 if (sWorld
.getConfig(CONFIG_WEATHER
))
6323 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6326 wth
->SendWeatherUpdateToPlayer(this);
6330 if(!sWorld
.AddWeather(zone
->ID
))
6332 // send fine weather packet to remove old zone's weather
6333 Weather::SendFineWeatherUpdateToPlayer(this);
6338 pvpInfo
.inHostileArea
=
6339 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6340 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6341 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6342 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6344 if(pvpInfo
.inHostileArea
) // in hostile area
6346 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6347 UpdatePvP(true, true);
6349 else // in friendly area
6351 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6352 pvpInfo
.endTimer
= time(0); // start toggle-off
6355 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6357 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6358 if(sWorld
.IsFFAPvPRealm())
6359 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6363 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6366 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6368 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6369 SetRestType(REST_TYPE_IN_CITY
);
6370 InnEnter(time(0),GetMapId(),0,0,0);
6372 if(sWorld
.IsFFAPvPRealm())
6373 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6375 else // anywhere else
6377 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6379 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6381 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6383 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6384 SetRestType(REST_TYPE_NO
);
6386 if(sWorld
.IsFFAPvPRealm())
6387 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6390 else // not in tavern (leave city then)
6392 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6393 SetRestType(REST_TYPE_NO
);
6395 // Set player to FFA PVP when not in rested environment.
6396 if(sWorld
.IsFFAPvPRealm())
6397 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6402 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6403 // if player resurrected at teleport this will be applied in resurrect code
6405 DestroyZoneLimitedItem( true, newZone
);
6407 // recent client version not send leave/join channel packets for built-in local channels
6408 UpdateLocalChannels( newZone
);
6412 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6414 UpdateZoneDependentAuras(newZone
);
6417 //If players are too far way of duel flag... then player loose the duel
6418 void Player::CheckDuelDistance(time_t currTime
)
6423 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6424 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6428 if(duel
->outOfBound
== 0)
6430 if(!IsWithinDistInMap(obj
, 50))
6432 duel
->outOfBound
= currTime
;
6434 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6435 GetSession()->SendPacket(&data
);
6440 if(IsWithinDistInMap(obj
, 40))
6442 duel
->outOfBound
= 0;
6444 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6445 GetSession()->SendPacket(&data
);
6447 else if(currTime
>= (duel
->outOfBound
+10))
6449 DuelComplete(DUEL_FLED
);
6454 void Player::DuelComplete(DuelCompleteType type
)
6456 // duel not requested
6460 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6461 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6462 GetSession()->SendPacket(&data
);
6463 duel
->opponent
->GetSession()->SendPacket(&data
);
6465 if(type
!= DUEL_INTERUPTED
)
6467 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6468 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6469 data
<< duel
->opponent
->GetName();
6471 SendMessageToSet(&data
,true);
6474 // cool-down duel spell
6475 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6482 GetSession()->SendPacket(&data);
6483 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6484 data<<duel->opponent->GetGUID();
6488 duel->opponent->GetSession()->SendPacket(&data);*/
6490 //Remove Duel Flag object
6491 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6493 duel
->initiator
->RemoveGameObject(obj
,true);
6496 std::vector
<uint32
> auras2remove
;
6497 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6498 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6500 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6501 auras2remove
.push_back(i
->second
->GetId());
6504 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6505 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6507 auras2remove
.clear();
6508 AuraMap
const& auras
= GetAuras();
6509 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6511 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6512 auras2remove
.push_back(i
->second
->GetId());
6514 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6515 RemoveAurasDueToSpell(auras2remove
[i
]);
6517 // cleanup combo points
6518 if(GetComboTarget()==duel
->opponent
->GetGUID())
6520 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6523 if(duel
->opponent
->GetComboTarget()==GetGUID())
6524 duel
->opponent
->ClearComboPoints();
6525 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6526 duel
->opponent
->ClearComboPoints();
6529 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6530 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6531 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6532 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6534 delete duel
->opponent
->duel
;
6535 duel
->opponent
->duel
= NULL
;
6540 //---------------------------------------------------------//
6542 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6544 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6547 // not apply/remove mods for broken item
6548 if(item
->IsBroken())
6551 ItemPrototype
const *proto
= item
->GetProto();
6556 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6558 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6559 if(attacktype
< MAX_ATTACK
)
6560 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6562 _ApplyItemBonuses(proto
,slot
,apply
);
6564 if( slot
==EQUIPMENT_SLOT_RANGED
)
6565 _ApplyAmmoBonuses();
6567 ApplyItemEquipSpell(item
,apply
);
6568 ApplyEnchantment(item
, apply
);
6570 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6571 CorrectMetaGemEnchants(slot
, apply
);
6573 sLog
.outDebug("_ApplyItemMods complete.");
6576 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6578 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6581 for (int i
= 0; i
< 10; i
++)
6583 uint32 statType
= 0;
6586 if(proto
->ScalingStatDistribution
)
6588 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6590 statType
= ssd
->StatMod
[i
];
6592 if(uint32 modifier
= ssd
->Modifier
[i
])
6594 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6595 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6597 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6598 val
= (multiplier
* modifier
) / 10000;
6605 statType
= proto
->ItemStat
[i
].ItemStatType
;
6606 val
= proto
->ItemStat
[i
].ItemStatValue
;
6615 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6617 case ITEM_MOD_HEALTH
: // modify HP
6618 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6620 case ITEM_MOD_AGILITY
: // modify agility
6621 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6622 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6624 case ITEM_MOD_STRENGTH
: //modify strength
6625 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6626 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6628 case ITEM_MOD_INTELLECT
: //modify intellect
6629 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6630 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6632 case ITEM_MOD_SPIRIT
: //modify spirit
6633 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6634 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6636 case ITEM_MOD_STAMINA
: //modify stamina
6637 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6638 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6640 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6641 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6643 case ITEM_MOD_DODGE_RATING
:
6644 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6646 case ITEM_MOD_PARRY_RATING
:
6647 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6649 case ITEM_MOD_BLOCK_RATING
:
6650 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6652 case ITEM_MOD_HIT_MELEE_RATING
:
6653 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6655 case ITEM_MOD_HIT_RANGED_RATING
:
6656 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6658 case ITEM_MOD_HIT_SPELL_RATING
:
6659 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6661 case ITEM_MOD_CRIT_MELEE_RATING
:
6662 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6664 case ITEM_MOD_CRIT_RANGED_RATING
:
6665 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6667 case ITEM_MOD_CRIT_SPELL_RATING
:
6668 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6670 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6671 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6673 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6674 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6676 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6677 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6679 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6680 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6682 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6683 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6685 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6686 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6688 case ITEM_MOD_HASTE_MELEE_RATING
:
6689 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6691 case ITEM_MOD_HASTE_RANGED_RATING
:
6692 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6694 case ITEM_MOD_HASTE_SPELL_RATING
:
6695 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6697 case ITEM_MOD_HIT_RATING
:
6698 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6699 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6700 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6702 case ITEM_MOD_CRIT_RATING
:
6703 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6704 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6705 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6707 case ITEM_MOD_HIT_TAKEN_RATING
:
6708 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6709 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6710 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6712 case ITEM_MOD_CRIT_TAKEN_RATING
:
6713 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6714 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6715 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6717 case ITEM_MOD_RESILIENCE_RATING
:
6718 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6719 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6720 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6722 case ITEM_MOD_HASTE_RATING
:
6723 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6724 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6725 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6727 case ITEM_MOD_EXPERTISE_RATING
:
6728 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6730 case ITEM_MOD_ATTACK_POWER
:
6731 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6733 case ITEM_MOD_RANGED_ATTACK_POWER
:
6734 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6736 case ITEM_MOD_FERAL_ATTACK_POWER
:
6737 ApplyFeralAPBonus(int32(val
), apply
);
6739 case ITEM_MOD_SPELL_HEALING_DONE
:
6740 ApplySpellHealingBonus(int32(val
), apply
);
6742 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6743 ApplySpellDamageBonus(int32(val
), apply
);
6745 case ITEM_MOD_MANA_REGENERATION
:
6746 ApplyManaRegenBonus(int32(val
), apply
);
6748 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6749 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6751 case ITEM_MOD_SPELL_POWER
:
6752 ApplySpellHealingBonus(int32(val
), apply
);
6753 ApplySpellDamageBonus(int32(val
), apply
);
6759 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6762 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6765 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6768 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6770 if (proto
->NatureRes
)
6771 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6773 if (proto
->FrostRes
)
6774 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6776 if (proto
->ShadowRes
)
6777 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6779 if (proto
->ArcaneRes
)
6780 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6782 WeaponAttackType attType
= BASE_ATTACK
;
6783 float damage
= 0.0f
;
6785 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6786 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6787 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6789 attType
= RANGED_ATTACK
;
6791 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6793 attType
= OFF_ATTACK
;
6796 if (proto
->Damage
[0].DamageMin
> 0 )
6798 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6799 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6800 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6803 if (proto
->Damage
[0].DamageMax
> 0 )
6805 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6806 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6809 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6814 if(slot
== EQUIPMENT_SLOT_RANGED
)
6815 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6816 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6817 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6818 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6819 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6822 if(CanModifyStats() && (damage
|| proto
->Delay
))
6823 UpdateDamagePhysical(attType
);
6826 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6828 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6829 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6830 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6832 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6833 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6834 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6836 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6837 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6838 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6841 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6843 // generic not weapon specific case processes in aura code
6844 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6847 BaseModGroup mod
= BASEMOD_END
;
6850 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6851 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6852 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6856 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6858 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6862 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6864 // ignore spell mods for not wands
6865 Modifier
const* modifier
= aura
->GetModifier();
6866 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6869 // generic not weapon specific case processes in aura code
6870 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6873 UnitMods unitMod
= UNIT_MOD_END
;
6876 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6877 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6878 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6882 UnitModifierType unitModType
= TOTAL_VALUE
;
6883 switch(modifier
->m_auraname
)
6885 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6886 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6890 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6892 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6896 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6901 ItemPrototype
const *proto
= item
->GetProto();
6905 for (int i
= 0; i
< 5; i
++)
6907 _Spell
const& spellData
= proto
->Spells
[i
];
6910 if(!spellData
.SpellId
)
6913 // wrong triggering type
6914 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6917 // check if it is valid spell
6918 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6922 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6926 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6930 // Cannot be used in this stance/form
6931 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6934 if(form_change
) // check aura active state from other form
6937 for (int k
=0; k
< 3; ++k
)
6939 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6940 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6942 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6952 if(found
) // and skip re-cast already active aura at form change
6956 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6958 CastSpell(this,spellInfo
,true,item
);
6962 if(form_change
) // check aura compatibility
6964 // Cannot be used in this stance/form
6965 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6966 return; // and remove only not compatible at form change
6970 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6972 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6976 void Player::UpdateEquipSpellsAtFormChange()
6978 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6980 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6982 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6983 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6987 // item set bonuses not dependent from item broken state
6988 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6990 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6994 for(uint32 y
=0;y
<8; ++y
)
6996 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7000 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7001 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7006 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
7008 if(!item
|| item
->IsBroken())
7011 ItemPrototype
const *proto
= item
->GetProto();
7015 if (!Target
|| Target
== this )
7018 for (int i
= 0; i
< 5; i
++)
7020 _Spell
const& spellData
= proto
->Spells
[i
];
7023 if(!spellData
.SpellId
)
7026 // wrong triggering type
7027 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7030 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7033 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7037 // not allow proc extra attack spell at extra attack
7038 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7041 float chance
= spellInfo
->procChance
;
7043 if(spellData
.SpellPPMRate
)
7045 uint32 WeaponSpeed
= GetAttackTime(attType
);
7046 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7048 else if(chance
> 100.0f
)
7050 chance
= GetWeaponProcChance();
7053 if (roll_chance_f(chance
))
7054 CastSpell(Target
, spellInfo
->Id
, true, item
);
7057 // item combat enchantments
7058 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7060 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7061 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7062 if(!pEnchant
) continue;
7063 for (int s
=0;s
<3;s
++)
7065 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7068 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7071 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7075 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7076 if (roll_chance_f(chance
))
7078 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7079 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7081 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7087 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7089 ItemPrototype
const* proto
= item
->GetProto();
7090 // special learning case
7091 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7093 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7094 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7096 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7099 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7100 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7104 Spell
*spell
= new Spell(this, spellInfo
, false);
7105 spell
->m_CastItem
= item
;
7106 spell
->m_cast_count
= cast_count
; //set count of casts
7107 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7108 spell
->prepare(&targets
);
7112 // use triggered flag only for items with many spell casts and for not first cast
7115 // item spells casted at use
7116 for(int i
= 0; i
< 5; ++i
)
7118 _Spell
const& spellData
= proto
->Spells
[i
];
7121 if(!spellData
.SpellId
)
7124 // wrong triggering type
7125 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7128 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7131 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7135 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7136 spell
->m_CastItem
= item
;
7137 spell
->m_cast_count
= cast_count
; // set count of casts
7138 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7139 spell
->prepare(&targets
);
7144 // Item enchantments spells casted at use
7145 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7147 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7148 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7149 if(!pEnchant
) continue;
7150 for (int s
=0;s
<3;s
++)
7152 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7155 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7158 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7162 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7163 spell
->m_CastItem
= item
;
7164 spell
->m_cast_count
= cast_count
; // set count of casts
7165 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7166 spell
->prepare(&targets
);
7173 void Player::_RemoveAllItemMods()
7175 sLog
.outDebug("_RemoveAllItemMods start.");
7177 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7181 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7185 // item set bonuses not dependent from item broken state
7187 RemoveItemsSetItem(this,proto
);
7189 if(m_items
[i
]->IsBroken())
7192 ApplyItemEquipSpell(m_items
[i
],false);
7193 ApplyEnchantment(m_items
[i
], false);
7197 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7201 if(m_items
[i
]->IsBroken())
7203 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7207 uint32 attacktype
= Player::GetAttackBySlot(i
);
7208 if(attacktype
< MAX_ATTACK
)
7209 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7211 _ApplyItemBonuses(proto
,i
, false);
7213 if( i
== EQUIPMENT_SLOT_RANGED
)
7214 _ApplyAmmoBonuses();
7218 sLog
.outDebug("_RemoveAllItemMods complete.");
7221 void Player::_ApplyAllItemMods()
7223 sLog
.outDebug("_ApplyAllItemMods start.");
7225 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7229 if(m_items
[i
]->IsBroken())
7232 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7236 uint32 attacktype
= Player::GetAttackBySlot(i
);
7237 if(attacktype
< MAX_ATTACK
)
7238 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7240 _ApplyItemBonuses(proto
,i
, true);
7242 if( i
== EQUIPMENT_SLOT_RANGED
)
7243 _ApplyAmmoBonuses();
7247 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7251 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7255 // item set bonuses not dependent from item broken state
7257 AddItemsSetItem(this,m_items
[i
]);
7259 if(m_items
[i
]->IsBroken())
7262 ApplyItemEquipSpell(m_items
[i
],true);
7263 ApplyEnchantment(m_items
[i
], true);
7267 sLog
.outDebug("_ApplyAllItemMods complete.");
7270 void Player::_ApplyAmmoBonuses()
7273 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7277 float currentAmmoDPS
;
7279 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7280 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7281 currentAmmoDPS
= 0.0f
;
7283 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7285 if(currentAmmoDPS
== GetAmmoDPS())
7288 m_ammoDPS
= currentAmmoDPS
;
7290 if(CanModifyStats())
7291 UpdateDamagePhysical(RANGED_ATTACK
);
7294 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7299 // check ranged weapon
7300 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7301 if(!weapon
|| weapon
->IsBroken() )
7304 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7305 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7308 // check ammo ws. weapon compatibility
7309 switch(weapon_proto
->SubClass
)
7311 case ITEM_SUBCLASS_WEAPON_BOW
:
7312 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7313 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7316 case ITEM_SUBCLASS_WEAPON_GUN
:
7317 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7327 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7328 Called by remove insignia spell effect */
7329 void Player::RemovedInsignia(Player
* looterPlr
)
7331 if (!GetBattleGroundId())
7334 // If not released spirit, do it !
7335 if(m_deathTimer
> 0)
7342 Corpse
*corpse
= GetCorpse();
7346 // We have to convert player corpse to bones, not to be able to resurrect there
7347 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7348 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7352 // Now we must make bones lootable, and send player loot
7353 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7355 // We store the level of our player in the gold field
7356 // We retrieve this information at Player::SendLoot()
7357 bones
->loot
.gold
= getLevel();
7358 bones
->lootRecipient
= looterPlr
;
7359 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7368 void Player::SendLootRelease( uint64 guid
)
7370 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7371 data
<< uint64(guid
) << uint8(1);
7372 SendDirectMessage( &data
);
7375 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7378 PermissionTypes permission
= ALL_PERMISSION
;
7380 sLog
.outDebug("Player::SendLoot");
7381 if (IS_GAMEOBJECT_GUID(guid
))
7383 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7385 ObjectAccessor::GetGameObject(*this, guid
);
7387 // not check distance for GO in case owned GO (fishing bobber case, for example)
7388 // And permit out of range GO with no owner in case fishing hole
7389 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7391 SendLootRelease(guid
);
7397 if(go
->getLootState() == GO_READY
)
7399 uint32 lootid
= go
->GetLootId();
7403 sLog
.outDebug(" if(lootid)");
7405 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7408 if(loot_type
== LOOT_FISHING
)
7409 go
->getFishLoot(loot
);
7411 go
->SetLootState(GO_ACTIVATED
);
7414 else if (IS_ITEM_GUID(guid
))
7416 Item
*item
= GetItemByGuid( guid
);
7420 SendLootRelease(guid
);
7424 if(loot_type
== LOOT_DISENCHANTING
)
7428 if(!item
->m_lootGenerated
)
7430 item
->m_lootGenerated
= true;
7432 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7435 else if(loot_type
== LOOT_PROSPECTING
)
7439 if(!item
->m_lootGenerated
)
7441 item
->m_lootGenerated
= true;
7443 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7446 else if(loot_type
== LOOT_MILLING
)
7450 if(!item
->m_lootGenerated
)
7452 item
->m_lootGenerated
= true;
7454 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this);
7461 if(!item
->m_lootGenerated
)
7463 item
->m_lootGenerated
= true;
7465 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7467 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7471 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7473 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7475 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7477 SendLootRelease(guid
);
7481 loot
= &bones
->loot
;
7483 if (!bones
->lootForBody
)
7485 bones
->lootForBody
= true;
7486 uint32 pLevel
= bones
->loot
.gold
;
7487 bones
->loot
.clear();
7488 // It may need a better formula
7489 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7490 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7493 if (bones
->lootRecipient
!= this)
7494 permission
= NONE_PERMISSION
;
7498 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7500 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7501 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7503 SendLootRelease(guid
);
7507 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7509 SendLootRelease(guid
);
7513 loot
= &creature
->loot
;
7515 if(loot_type
== LOOT_PICKPOCKETING
)
7517 if ( !creature
->lootForPickPocketed
)
7519 creature
->lootForPickPocketed
= true;
7522 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7523 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7525 // Generate extra money for pick pocket loot
7526 const uint32 a
= urand(0, creature
->getLevel()/2);
7527 const uint32 b
= urand(0, getLevel()/2);
7528 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7533 // the player whose group may loot the corpse
7534 Player
*recipient
= creature
->GetLootRecipient();
7537 creature
->SetLootRecipient(this);
7541 if (creature
->lootForPickPocketed
)
7543 creature
->lootForPickPocketed
= false;
7547 if(!creature
->lootForBody
)
7549 creature
->lootForBody
= true;
7552 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7553 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7555 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7557 if(Group
* group
= recipient
->GetGroup())
7559 group
->UpdateLooterGuid(creature
,true);
7561 switch (group
->GetLootMethod())
7564 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7565 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7567 case NEED_BEFORE_GREED
:
7568 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7571 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7579 // possible only if creature->lootForBody && loot->empty() at spell cast check
7580 if (loot_type
== LOOT_SKINNING
)
7583 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7585 // set group rights only for loot_type != LOOT_SKINNING
7588 if(Group
* group
= GetGroup())
7590 if( group
== recipient
->GetGroup() )
7592 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7593 permission
= ALL_PERMISSION
;
7594 else if(group
->GetLooterGuid() == GetGUID())
7596 if(group
->GetLootMethod() == MASTER_LOOT
)
7597 permission
= MASTER_PERMISSION
;
7599 permission
= ALL_PERMISSION
;
7602 permission
= GROUP_PERMISSION
;
7605 permission
= NONE_PERMISSION
;
7607 else if(recipient
== this)
7608 permission
= ALL_PERMISSION
;
7610 permission
= NONE_PERMISSION
;
7617 QuestItemList
*q_list
= 0;
7618 if (permission
!= NONE_PERMISSION
)
7620 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7621 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7622 if (itr
== lootPlayerQuestItems
.end())
7623 q_list
= loot
->FillQuestLoot(this);
7625 q_list
= itr
->second
;
7628 QuestItemList
*ffa_list
= 0;
7629 if (permission
!= NONE_PERMISSION
)
7631 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7632 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7633 if (itr
== lootPlayerFFAItems
.end())
7634 ffa_list
= loot
->FillFFALoot(this);
7636 ffa_list
= itr
->second
;
7639 QuestItemList
*conditional_list
= 0;
7640 if (permission
!= NONE_PERMISSION
)
7642 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7643 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7644 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7645 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7647 conditional_list
= itr
->second
;
7650 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7651 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7652 loot_type
= LOOT_SKINNING
;
7654 if(loot_type
== LOOT_FISHINGHOLE
)
7655 loot_type
= LOOT_FISHING
;
7657 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7659 data
<< uint64(guid
);
7660 data
<< uint8(loot_type
);
7661 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7663 SendDirectMessage(&data
);
7665 // add 'this' player as one of the players that are looting 'loot'
7666 if (permission
!= NONE_PERMISSION
)
7667 loot
->AddLooter(GetGUID());
7669 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7670 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7673 void Player::SendNotifyLootMoneyRemoved()
7675 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7676 GetSession()->SendPacket( &data
);
7679 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7681 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7682 data
<< uint8(lootSlot
);
7683 GetSession()->SendPacket( &data
);
7686 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7688 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7691 GetSession()->SendPacket(&data
);
7694 void Player::SendInitWorldStates()
7696 // data depends on zoneid/mapid...
7697 BattleGround
* bg
= GetBattleGround();
7698 uint16 NumberOfFields
= 0;
7699 uint32 mapid
= GetMapId();
7700 uint32 zoneid
= GetZoneId();
7701 uint32 areaid
= GetAreaId();
7702 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7703 // may be exist better way to do this...
7726 NumberOfFields
= 41;
7729 NumberOfFields
= 15;
7732 NumberOfFields
= 83;
7735 NumberOfFields
= 16;
7739 NumberOfFields
= 40;
7742 NumberOfFields
= 27;
7745 NumberOfFields
= 39;
7748 NumberOfFields
= 38;
7751 NumberOfFields
= 37;
7756 NumberOfFields
= 11;
7759 NumberOfFields
= 11;
7762 NumberOfFields
= 12;
7766 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7767 data
<< uint32(mapid
); // mapid
7768 data
<< uint32(zoneid
); // zone id
7769 data
<< uint32(areaid
); // area id, new 2.1.0
7770 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7771 data
<< uint32(0x8d8) << uint32(0x0); // 1
7772 data
<< uint32(0x8d7) << uint32(0x0); // 2
7773 data
<< uint32(0x8d6) << uint32(0x0); // 3
7774 data
<< uint32(0x8d5) << uint32(0x0); // 4
7775 data
<< uint32(0x8d4) << uint32(0x0); // 5
7776 data
<< uint32(0x8d3) << uint32(0x0); // 6
7777 // 7 1 - Arena season in progress, 0 - end of season
7778 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7779 // 8 Arena season id
7780 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7781 if(mapid
== 530) // Outland
7783 data
<< uint32(0x9bf) << uint32(0x0); // 7
7784 data
<< uint32(0x9bd) << uint32(0xF); // 8
7785 data
<< uint32(0x9bb) << uint32(0xF); // 9
7800 data
<< uint32(0x7ae) << uint32(0x1); // 7
7801 data
<< uint32(0x532) << uint32(0x1); // 8
7802 data
<< uint32(0x531) << uint32(0x0); // 9
7803 data
<< uint32(0x52e) << uint32(0x0); // 10
7804 data
<< uint32(0x571) << uint32(0x0); // 11
7805 data
<< uint32(0x570) << uint32(0x0); // 12
7806 data
<< uint32(0x567) << uint32(0x1); // 13
7807 data
<< uint32(0x566) << uint32(0x1); // 14
7808 data
<< uint32(0x550) << uint32(0x1); // 15
7809 data
<< uint32(0x544) << uint32(0x0); // 16
7810 data
<< uint32(0x536) << uint32(0x0); // 17
7811 data
<< uint32(0x535) << uint32(0x1); // 18
7812 data
<< uint32(0x518) << uint32(0x0); // 19
7813 data
<< uint32(0x517) << uint32(0x0); // 20
7814 data
<< uint32(0x574) << uint32(0x0); // 21
7815 data
<< uint32(0x573) << uint32(0x0); // 22
7816 data
<< uint32(0x572) << uint32(0x0); // 23
7817 data
<< uint32(0x56f) << uint32(0x0); // 24
7818 data
<< uint32(0x56e) << uint32(0x0); // 25
7819 data
<< uint32(0x56d) << uint32(0x0); // 26
7820 data
<< uint32(0x56c) << uint32(0x0); // 27
7821 data
<< uint32(0x56b) << uint32(0x0); // 28
7822 data
<< uint32(0x56a) << uint32(0x1); // 29
7823 data
<< uint32(0x569) << uint32(0x1); // 30
7824 data
<< uint32(0x568) << uint32(0x1); // 13
7825 data
<< uint32(0x565) << uint32(0x0); // 32
7826 data
<< uint32(0x564) << uint32(0x0); // 33
7827 data
<< uint32(0x563) << uint32(0x0); // 34
7828 data
<< uint32(0x562) << uint32(0x0); // 35
7829 data
<< uint32(0x561) << uint32(0x0); // 36
7830 data
<< uint32(0x560) << uint32(0x0); // 37
7831 data
<< uint32(0x55f) << uint32(0x0); // 38
7832 data
<< uint32(0x55e) << uint32(0x0); // 39
7833 data
<< uint32(0x55d) << uint32(0x0); // 40
7834 data
<< uint32(0x3c6) << uint32(0x4); // 41
7835 data
<< uint32(0x3c4) << uint32(0x6); // 42
7836 data
<< uint32(0x3c2) << uint32(0x4); // 43
7837 data
<< uint32(0x516) << uint32(0x1); // 44
7838 data
<< uint32(0x515) << uint32(0x0); // 45
7839 data
<< uint32(0x3b6) << uint32(0x6); // 46
7840 data
<< uint32(0x55c) << uint32(0x0); // 47
7841 data
<< uint32(0x55b) << uint32(0x0); // 48
7842 data
<< uint32(0x55a) << uint32(0x0); // 49
7843 data
<< uint32(0x559) << uint32(0x0); // 50
7844 data
<< uint32(0x558) << uint32(0x0); // 51
7845 data
<< uint32(0x557) << uint32(0x0); // 52
7846 data
<< uint32(0x556) << uint32(0x0); // 53
7847 data
<< uint32(0x555) << uint32(0x0); // 54
7848 data
<< uint32(0x554) << uint32(0x1); // 55
7849 data
<< uint32(0x553) << uint32(0x1); // 56
7850 data
<< uint32(0x552) << uint32(0x1); // 57
7851 data
<< uint32(0x551) << uint32(0x1); // 58
7852 data
<< uint32(0x54f) << uint32(0x0); // 59
7853 data
<< uint32(0x54e) << uint32(0x0); // 60
7854 data
<< uint32(0x54d) << uint32(0x1); // 61
7855 data
<< uint32(0x54c) << uint32(0x0); // 62
7856 data
<< uint32(0x54b) << uint32(0x0); // 63
7857 data
<< uint32(0x545) << uint32(0x0); // 64
7858 data
<< uint32(0x543) << uint32(0x1); // 65
7859 data
<< uint32(0x542) << uint32(0x0); // 66
7860 data
<< uint32(0x540) << uint32(0x0); // 67
7861 data
<< uint32(0x53f) << uint32(0x0); // 68
7862 data
<< uint32(0x53e) << uint32(0x0); // 69
7863 data
<< uint32(0x53d) << uint32(0x0); // 70
7864 data
<< uint32(0x53c) << uint32(0x0); // 71
7865 data
<< uint32(0x53b) << uint32(0x0); // 72
7866 data
<< uint32(0x53a) << uint32(0x1); // 73
7867 data
<< uint32(0x539) << uint32(0x0); // 74
7868 data
<< uint32(0x538) << uint32(0x0); // 75
7869 data
<< uint32(0x537) << uint32(0x0); // 76
7870 data
<< uint32(0x534) << uint32(0x0); // 77
7871 data
<< uint32(0x533) << uint32(0x0); // 78
7872 data
<< uint32(0x530) << uint32(0x0); // 79
7873 data
<< uint32(0x52f) << uint32(0x0); // 80
7874 data
<< uint32(0x52d) << uint32(0x1); // 81
7877 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7878 bg
->FillInitialWorldStates(data
);
7881 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7882 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7883 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7884 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7885 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7886 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7887 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7888 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7892 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7893 bg
->FillInitialWorldStates(data
);
7896 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7897 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7898 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7899 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7900 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7901 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7902 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7903 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7904 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7905 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7906 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7907 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7908 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7909 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7910 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7911 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7912 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7913 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7914 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7915 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7916 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7917 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7918 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7919 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7920 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7921 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7922 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7923 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7924 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7925 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7926 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7927 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7931 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7932 bg
->FillInitialWorldStates(data
);
7935 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7936 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7937 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7938 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7939 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7940 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7941 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7942 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7943 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7944 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7945 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7946 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7947 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7948 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7949 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7950 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7951 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7952 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7953 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7954 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7955 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7956 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7957 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7958 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7959 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7960 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7961 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7962 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7963 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7964 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7965 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7966 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7967 // and some more ... unknown
7970 case 3483: // Hellfire Peninsula
7971 data
<< uint32(0x9ba) << uint32(0x1); // 10
7972 data
<< uint32(0x9b9) << uint32(0x1); // 11
7973 data
<< uint32(0x9b5) << uint32(0x0); // 12
7974 data
<< uint32(0x9b4) << uint32(0x1); // 13
7975 data
<< uint32(0x9b3) << uint32(0x0); // 14
7976 data
<< uint32(0x9b2) << uint32(0x0); // 15
7977 data
<< uint32(0x9b1) << uint32(0x1); // 16
7978 data
<< uint32(0x9b0) << uint32(0x0); // 17
7979 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7980 data
<< uint32(0x9ac) << uint32(0x0); // 19
7981 data
<< uint32(0x9a8) << uint32(0x0); // 20
7982 data
<< uint32(0x9a7) << uint32(0x0); // 21
7983 data
<< uint32(0x9a6) << uint32(0x1); // 22
7985 case 3519: // Terokkar Forest
7986 data
<< uint32(0xa41) << uint32(0x0); // 10
7987 data
<< uint32(0xa40) << uint32(0x14); // 11
7988 data
<< uint32(0xa3f) << uint32(0x0); // 12
7989 data
<< uint32(0xa3e) << uint32(0x0); // 13
7990 data
<< uint32(0xa3d) << uint32(0x5); // 14
7991 data
<< uint32(0xa3c) << uint32(0x0); // 15
7992 data
<< uint32(0xa87) << uint32(0x0); // 16
7993 data
<< uint32(0xa86) << uint32(0x0); // 17
7994 data
<< uint32(0xa85) << uint32(0x0); // 18
7995 data
<< uint32(0xa84) << uint32(0x0); // 19
7996 data
<< uint32(0xa83) << uint32(0x0); // 20
7997 data
<< uint32(0xa82) << uint32(0x0); // 21
7998 data
<< uint32(0xa81) << uint32(0x0); // 22
7999 data
<< uint32(0xa80) << uint32(0x0); // 23
8000 data
<< uint32(0xa7e) << uint32(0x0); // 24
8001 data
<< uint32(0xa7d) << uint32(0x0); // 25
8002 data
<< uint32(0xa7c) << uint32(0x0); // 26
8003 data
<< uint32(0xa7b) << uint32(0x0); // 27
8004 data
<< uint32(0xa7a) << uint32(0x0); // 28
8005 data
<< uint32(0xa79) << uint32(0x0); // 29
8006 data
<< uint32(0x9d0) << uint32(0x5); // 30
8007 data
<< uint32(0x9ce) << uint32(0x0); // 31
8008 data
<< uint32(0x9cd) << uint32(0x0); // 32
8009 data
<< uint32(0x9cc) << uint32(0x0); // 33
8010 data
<< uint32(0xa88) << uint32(0x0); // 34
8011 data
<< uint32(0xad0) << uint32(0x0); // 35
8012 data
<< uint32(0xacf) << uint32(0x1); // 36
8014 case 3521: // Zangarmarsh
8015 data
<< uint32(0x9e1) << uint32(0x0); // 10
8016 data
<< uint32(0x9e0) << uint32(0x0); // 11
8017 data
<< uint32(0x9df) << uint32(0x0); // 12
8018 data
<< uint32(0xa5d) << uint32(0x1); // 13
8019 data
<< uint32(0xa5c) << uint32(0x0); // 14
8020 data
<< uint32(0xa5b) << uint32(0x1); // 15
8021 data
<< uint32(0xa5a) << uint32(0x0); // 16
8022 data
<< uint32(0xa59) << uint32(0x1); // 17
8023 data
<< uint32(0xa58) << uint32(0x0); // 18
8024 data
<< uint32(0xa57) << uint32(0x0); // 19
8025 data
<< uint32(0xa56) << uint32(0x0); // 20
8026 data
<< uint32(0xa55) << uint32(0x1); // 21
8027 data
<< uint32(0xa54) << uint32(0x0); // 22
8028 data
<< uint32(0x9e7) << uint32(0x0); // 23
8029 data
<< uint32(0x9e6) << uint32(0x0); // 24
8030 data
<< uint32(0x9e5) << uint32(0x0); // 25
8031 data
<< uint32(0xa00) << uint32(0x0); // 26
8032 data
<< uint32(0x9ff) << uint32(0x1); // 27
8033 data
<< uint32(0x9fe) << uint32(0x0); // 28
8034 data
<< uint32(0x9fd) << uint32(0x0); // 29
8035 data
<< uint32(0x9fc) << uint32(0x1); // 30
8036 data
<< uint32(0x9fb) << uint32(0x0); // 31
8037 data
<< uint32(0xa62) << uint32(0x0); // 32
8038 data
<< uint32(0xa61) << uint32(0x1); // 33
8039 data
<< uint32(0xa60) << uint32(0x1); // 34
8040 data
<< uint32(0xa5f) << uint32(0x0); // 35
8042 case 3698: // Nagrand Arena
8043 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8044 bg
->FillInitialWorldStates(data
);
8047 data
<< uint32(0xa0f) << uint32(0x0); // 7
8048 data
<< uint32(0xa10) << uint32(0x0); // 8
8049 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8052 case 3702: // Blade's Edge Arena
8053 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8054 bg
->FillInitialWorldStates(data
);
8057 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8058 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8059 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8062 case 3968: // Ruins of Lordaeron
8063 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8064 bg
->FillInitialWorldStates(data
);
8067 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8068 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8069 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8072 case 3703: // Shattrath City
8075 data
<< uint32(0x914) << uint32(0x0); // 7
8076 data
<< uint32(0x913) << uint32(0x0); // 8
8077 data
<< uint32(0x912) << uint32(0x0); // 9
8078 data
<< uint32(0x915) << uint32(0x0); // 10
8081 GetSession()->SendPacket(&data
);
8084 uint32
Player::GetXPRestBonus(uint32 xp
)
8086 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8088 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8091 SetRestBonus( GetRestBonus() - rested_bonus
);
8093 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8094 return rested_bonus
;
8097 void Player::SetBindPoint(uint64 guid
)
8099 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8100 data
<< uint64(guid
);
8101 GetSession()->SendPacket( &data
);
8104 void Player::SendTalentWipeConfirm(uint64 guid
)
8106 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8107 data
<< uint64(guid
);
8108 data
<< uint32(resetTalentsCost());
8109 GetSession()->SendPacket( &data
);
8112 void Player::SendPetSkillWipeConfirm()
8114 Pet
* pet
= GetPet();
8117 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8118 data
<< pet
->GetGUID();
8119 data
<< uint32(pet
->resetTalentsCost());
8120 GetSession()->SendPacket( &data
);
8123 /*********************************************************/
8124 /*** STORAGE SYSTEM ***/
8125 /*********************************************************/
8127 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8132 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8134 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8138 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8139 else if(charges
<= 1)
8141 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8142 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8147 void Player::SetSheath( uint32 sheathed
)
8151 case SHEATH_STATE_UNARMED
: // no prepared weapon
8152 SetVirtualItemSlot(0,NULL
);
8153 SetVirtualItemSlot(1,NULL
);
8154 SetVirtualItemSlot(2,NULL
);
8156 case SHEATH_STATE_MELEE
: // prepared melee weapon
8158 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8159 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8160 SetVirtualItemSlot(2,NULL
);
8162 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8163 SetVirtualItemSlot(0,NULL
);
8164 SetVirtualItemSlot(1,NULL
);
8165 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8168 SetVirtualItemSlot(0,NULL
);
8169 SetVirtualItemSlot(1,NULL
);
8170 SetVirtualItemSlot(2,NULL
);
8173 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
8176 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8178 uint8 pClass
= getClass();
8181 slots
[0] = NULL_SLOT
;
8182 slots
[1] = NULL_SLOT
;
8183 slots
[2] = NULL_SLOT
;
8184 slots
[3] = NULL_SLOT
;
8185 switch( proto
->InventoryType
)
8188 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8191 slots
[0] = EQUIPMENT_SLOT_NECK
;
8193 case INVTYPE_SHOULDERS
:
8194 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8197 slots
[0] = EQUIPMENT_SLOT_BODY
;
8200 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8203 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8206 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8209 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8212 slots
[0] = EQUIPMENT_SLOT_FEET
;
8214 case INVTYPE_WRISTS
:
8215 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8218 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8220 case INVTYPE_FINGER
:
8221 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8222 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8224 case INVTYPE_TRINKET
:
8225 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8226 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8229 slots
[0] = EQUIPMENT_SLOT_BACK
;
8231 case INVTYPE_WEAPON
:
8233 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8235 // suggest offhand slot only if know dual wielding
8236 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8238 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8241 case INVTYPE_SHIELD
:
8242 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8244 case INVTYPE_RANGED
:
8245 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8247 case INVTYPE_2HWEAPON
:
8248 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8249 if (CanDualWield() && CanTitanGrip())
8250 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8252 case INVTYPE_TABARD
:
8253 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8255 case INVTYPE_WEAPONMAINHAND
:
8256 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8258 case INVTYPE_WEAPONOFFHAND
:
8259 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8261 case INVTYPE_HOLDABLE
:
8262 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8264 case INVTYPE_THROWN
:
8265 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8267 case INVTYPE_RANGEDRIGHT
:
8268 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8271 slots
[0] = INVENTORY_SLOT_BAG_1
;
8272 slots
[1] = INVENTORY_SLOT_BAG_2
;
8273 slots
[2] = INVENTORY_SLOT_BAG_3
;
8274 slots
[3] = INVENTORY_SLOT_BAG_4
;
8278 switch(proto
->SubClass
)
8280 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8281 if (pClass
== CLASS_PALADIN
)
8282 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8284 case ITEM_SUBCLASS_ARMOR_IDOL
:
8285 if (pClass
== CLASS_DRUID
)
8286 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8288 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8289 if (pClass
== CLASS_SHAMAN
)
8290 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8292 case ITEM_SUBCLASS_ARMOR_MISC
:
8293 if (pClass
== CLASS_WARLOCK
)
8294 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8296 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8297 if (pClass
== CLASS_DEATH_KNIGHT
)
8298 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8307 if( slot
!= NULL_SLOT
)
8309 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8311 for (int i
= 0; i
< 4; i
++)
8313 if ( slots
[i
] == slot
)
8320 // search free slot at first
8321 for (int i
= 0; i
< 4; i
++)
8323 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8325 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8326 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8331 // if not found free and can swap return first appropriate from used
8332 for (int i
= 0; i
< 4; i
++)
8334 if ( slots
[i
] != NULL_SLOT
&& swap
)
8343 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8346 uint32 tempcount
= 0;
8348 uint8 res
= EQUIP_ERR_OK
;
8350 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8352 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8353 if( pItem
&& pItem
->GetEntry() == item
)
8355 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8356 if(ires
==EQUIP_ERR_OK
)
8358 tempcount
+= pItem
->GetCount();
8359 if( tempcount
>= count
)
8360 return EQUIP_ERR_OK
;
8366 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8368 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8369 if( pItem
&& pItem
->GetEntry() == item
)
8371 tempcount
+= pItem
->GetCount();
8372 if( tempcount
>= count
)
8373 return EQUIP_ERR_OK
;
8376 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8378 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8379 if( pItem
&& pItem
->GetEntry() == item
)
8381 tempcount
+= pItem
->GetCount();
8382 if( tempcount
>= count
)
8383 return EQUIP_ERR_OK
;
8387 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8389 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8392 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8394 pItem
= GetItemByPos( i
, j
);
8395 if( pItem
&& pItem
->GetEntry() == item
)
8397 tempcount
+= pItem
->GetCount();
8398 if( tempcount
>= count
)
8399 return EQUIP_ERR_OK
;
8405 // not found req. item count and have unequippable items
8409 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8412 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8414 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8415 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8416 count
+= pItem
->GetCount();
8418 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8420 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8421 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8422 count
+= pItem
->GetCount();
8424 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8426 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8428 count
+= pBag
->GetItemCount(item
,skipItem
);
8431 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8433 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8435 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8436 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8437 count
+= pItem
->GetGemCountWithID(item
);
8443 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8445 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8446 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8447 count
+= pItem
->GetCount();
8449 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8451 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8453 count
+= pBag
->GetItemCount(item
,skipItem
);
8456 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8458 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8460 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8461 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8462 count
+= pItem
->GetGemCountWithID(item
);
8470 Item
* Player::GetItemByGuid( uint64 guid
) const
8472 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8474 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8475 if( pItem
&& pItem
->GetGUID() == guid
)
8478 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8480 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8481 if( pItem
&& pItem
->GetGUID() == guid
)
8485 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8487 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8490 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8492 Item
* pItem
= pBag
->GetItemByPos( j
);
8493 if( pItem
&& pItem
->GetGUID() == guid
)
8498 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8500 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8503 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8505 Item
* pItem
= pBag
->GetItemByPos( j
);
8506 if( pItem
&& pItem
->GetGUID() == guid
)
8515 Item
* Player::GetItemByPos( uint16 pos
) const
8517 uint8 bag
= pos
>> 8;
8518 uint8 slot
= pos
& 255;
8519 return GetItemByPos( bag
, slot
);
8522 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8524 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8525 return m_items
[slot
];
8526 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8527 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8529 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8531 return pBag
->GetItemByPos(slot
);
8536 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8541 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8542 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8543 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8544 default: return NULL
;
8547 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8548 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8554 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8560 Item
* Player::GetShield(bool useable
) const
8562 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8563 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8569 if( item
->IsBroken())
8575 uint32
Player::GetAttackBySlot( uint8 slot
)
8579 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8580 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8581 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8582 default: return MAX_ATTACK
;
8586 bool Player::HasBankBagSlot( uint8 slot
) const
8588 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8589 if( slot
< maxslot
)
8594 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8596 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8598 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8600 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8602 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8607 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8609 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8611 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8616 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8618 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8620 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8622 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8627 bool Player::IsBagPos( uint16 pos
)
8629 uint8 bag
= pos
>> 8;
8630 uint8 slot
= pos
& 255;
8631 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8633 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8638 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8644 if (bag
== INVENTORY_SLOT_BAG_0
)
8646 // any post selected
8647 if (slot
== NULL_SLOT
)
8651 if (slot
< EQUIPMENT_SLOT_END
)
8655 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8659 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8663 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8667 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8671 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8677 // bag content slots
8678 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8680 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8684 // any post selected
8685 if (slot
== NULL_SLOT
)
8688 return slot
< pBag
->GetBagSize();
8691 // bank bag content slots
8692 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8694 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8698 // any post selected
8699 if (slot
== NULL_SLOT
)
8702 return slot
< pBag
->GetBagSize();
8710 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8712 uint32 tempcount
= 0;
8713 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8715 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8716 if( pItem
&& pItem
->GetEntry() == item
)
8718 tempcount
+= pItem
->GetCount();
8719 if( tempcount
>= count
)
8723 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8725 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8726 if( pItem
&& pItem
->GetEntry() == item
)
8728 tempcount
+= pItem
->GetCount();
8729 if( tempcount
>= count
)
8733 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8735 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8737 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8739 Item
* pItem
= GetItemByPos( i
, j
);
8740 if( pItem
&& pItem
->GetEntry() == item
)
8742 tempcount
+= pItem
->GetCount();
8743 if( tempcount
>= count
)
8752 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8754 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8755 if( pItem
&& pItem
->GetEntry() == item
)
8757 tempcount
+= pItem
->GetCount();
8758 if( tempcount
>= count
)
8762 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8764 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8766 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8768 Item
* pItem
= GetItemByPos( i
, j
);
8769 if( pItem
&& pItem
->GetEntry() == item
)
8771 tempcount
+= pItem
->GetCount();
8772 if( tempcount
>= count
)
8783 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8786 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8788 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8789 if( pItem
&& pItem
->GetEntry() == item
)
8793 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8794 if (pProto
&& pProto
->GemProperties
)
8796 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8798 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8799 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8801 if (pItem
->GetGemCountWithID(item
) > 0 )
8810 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8812 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8816 *no_space_count
= count
;
8817 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8821 if(pProto
->MaxCount
<= 0)
8822 return EQUIP_ERR_OK
;
8824 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8826 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8829 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8830 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8833 return EQUIP_ERR_OK
;
8836 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8839 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8841 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8842 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8845 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8847 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8848 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8851 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8853 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8855 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8857 pItem
= GetItemByPos( i
, j
);
8858 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8866 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8868 Item
* pItem2
= GetItemByPos( bag
, slot
);
8870 // ignore move item (this slot will be empty at move)
8871 if(pItem2
==pSrcItem
)
8876 // empty specific slot - check item fit to slot
8877 if( !pItem2
|| swap
)
8879 if( bag
== INVENTORY_SLOT_BAG_0
)
8882 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8883 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8885 // vanitypet case (not use, vanity pets stored as spells)
8886 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8887 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8889 // currencytoken case (disabled until proper implement)
8890 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8891 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8893 // guestbag case (disabled until proper implement)
8894 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8895 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8898 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8899 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8903 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8905 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8907 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8909 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8911 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8912 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8915 // non empty stack with space
8916 need_space
= pProto
->GetMaxStackSize();
8918 // non empty slot, check item type
8922 if(pItem2
->GetEntry() != pProto
->ItemId
)
8923 return EQUIP_ERR_ITEM_CANT_STACK
;
8926 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8927 return EQUIP_ERR_ITEM_CANT_STACK
;
8929 // free stack space or infinity
8930 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8933 if(need_space
> count
)
8936 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8937 if(!newPosition
.isContainedIn(dest
))
8939 dest
.push_back(newPosition
);
8940 count
-= need_space
;
8942 return EQUIP_ERR_OK
;
8945 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
8947 // skip specific bag already processed in first called _CanStoreItem_InBag
8949 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8951 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8953 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8955 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8957 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8959 // specialized bag mode or non-specilized
8960 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8961 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8963 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8964 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8966 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8968 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8972 Item
* pItem2
= GetItemByPos( bag
, j
);
8974 // ignore move item (this slot will be empty at move)
8975 if(pItem2
==pSrcItem
)
8978 // if merge skip empty, if !merge skip non-empty
8979 if((pItem2
!=NULL
)!=merge
)
8984 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8986 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8987 if(need_space
> count
)
8990 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8991 if(!newPosition
.isContainedIn(dest
))
8993 dest
.push_back(newPosition
);
8994 count
-= need_space
;
8997 return EQUIP_ERR_OK
;
9003 uint32 need_space
= pProto
->GetMaxStackSize();
9004 if(need_space
> count
)
9007 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9008 if(!newPosition
.isContainedIn(dest
))
9010 dest
.push_back(newPosition
);
9011 count
-= need_space
;
9014 return EQUIP_ERR_OK
;
9018 return EQUIP_ERR_OK
;
9021 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
9023 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
9025 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9026 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9029 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9031 // ignore move item (this slot will be empty at move)
9032 if(pItem2
==pSrcItem
)
9035 // if merge skip empty, if !merge skip non-empty
9036 if((pItem2
!=NULL
)!=merge
)
9041 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9043 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9044 if(need_space
> count
)
9046 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9047 if(!newPosition
.isContainedIn(dest
))
9049 dest
.push_back(newPosition
);
9050 count
-= need_space
;
9053 return EQUIP_ERR_OK
;
9059 uint32 need_space
= pProto
->GetMaxStackSize();
9060 if(need_space
> count
)
9063 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9064 if(!newPosition
.isContainedIn(dest
))
9066 dest
.push_back(newPosition
);
9067 count
-= need_space
;
9070 return EQUIP_ERR_OK
;
9074 return EQUIP_ERR_OK
;
9077 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9079 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9081 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
9085 *no_space_count
= count
;
9086 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9089 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
9092 *no_space_count
= count
;
9093 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9096 // check count of items (skip for auto move for same player from bank)
9097 uint32 no_similar_count
= 0; // can't store this amount similar items
9098 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9099 if(res
!=EQUIP_ERR_OK
)
9101 if(count
==no_similar_count
)
9104 *no_space_count
= no_similar_count
;
9107 count
-= no_similar_count
;
9111 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9113 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9114 if(res
!=EQUIP_ERR_OK
)
9117 *no_space_count
= count
+ no_similar_count
;
9123 if(no_similar_count
==0)
9124 return EQUIP_ERR_OK
;
9127 *no_space_count
= count
+ no_similar_count
;
9128 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9132 // not specific slot or have space for partly store only in specific slot
9135 if( bag
!= NULL_BAG
)
9137 // search stack in bag for merge to
9138 if( pProto
->Stackable
!= 1 )
9140 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9142 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9143 if(res
!=EQUIP_ERR_OK
)
9146 *no_space_count
= count
+ no_similar_count
;
9152 if(no_similar_count
==0)
9153 return EQUIP_ERR_OK
;
9156 *no_space_count
= count
+ no_similar_count
;
9157 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9160 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9161 if(res
!=EQUIP_ERR_OK
)
9164 *no_space_count
= count
+ no_similar_count
;
9170 if(no_similar_count
==0)
9171 return EQUIP_ERR_OK
;
9174 *no_space_count
= count
+ no_similar_count
;
9175 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9178 else // equipped bag
9180 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9181 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9182 if(res
!=EQUIP_ERR_OK
)
9183 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9185 if(res
!=EQUIP_ERR_OK
)
9188 *no_space_count
= count
+ no_similar_count
;
9194 if(no_similar_count
==0)
9195 return EQUIP_ERR_OK
;
9198 *no_space_count
= count
+ no_similar_count
;
9199 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9204 // search free slot in bag for place to
9205 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9207 // search free slot - keyring case
9208 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9210 uint32 keyringSize
= GetMaxKeyringSize();
9211 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9212 if(res
!=EQUIP_ERR_OK
)
9215 *no_space_count
= count
+ no_similar_count
;
9221 if(no_similar_count
==0)
9222 return EQUIP_ERR_OK
;
9225 *no_space_count
= count
+ no_similar_count
;
9226 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9230 // Vanity pet case skipped as not used
9232 /* until proper implementation
9233 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9235 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9236 if(res!=EQUIP_ERR_OK)
9239 *no_space_count = count + no_similar_count;
9245 if(no_similar_count==0)
9246 return EQUIP_ERR_OK;
9249 *no_space_count = count + no_similar_count;
9250 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9254 /* until proper implementation
9255 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9257 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9258 if(res!=EQUIP_ERR_OK)
9261 *no_space_count = count + no_similar_count;
9267 if(no_similar_count==0)
9268 return EQUIP_ERR_OK;
9271 *no_space_count = count + no_similar_count;
9272 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9277 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9278 if(res
!=EQUIP_ERR_OK
)
9281 *no_space_count
= count
+ no_similar_count
;
9287 if(no_similar_count
==0)
9288 return EQUIP_ERR_OK
;
9291 *no_space_count
= count
+ no_similar_count
;
9292 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9295 else // equipped bag
9297 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9298 if(res
!=EQUIP_ERR_OK
)
9299 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9301 if(res
!=EQUIP_ERR_OK
)
9304 *no_space_count
= count
+ no_similar_count
;
9310 if(no_similar_count
==0)
9311 return EQUIP_ERR_OK
;
9314 *no_space_count
= count
+ no_similar_count
;
9315 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9320 // not specific bag or have space for partly store only in specific bag
9322 // search stack for merge to
9323 if( pProto
->Stackable
!= 1 )
9325 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9326 if(res
!=EQUIP_ERR_OK
)
9329 *no_space_count
= count
+ no_similar_count
;
9335 if(no_similar_count
==0)
9336 return EQUIP_ERR_OK
;
9339 *no_space_count
= count
+ no_similar_count
;
9340 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9343 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9344 if(res
!=EQUIP_ERR_OK
)
9347 *no_space_count
= count
+ no_similar_count
;
9353 if(no_similar_count
==0)
9354 return EQUIP_ERR_OK
;
9357 *no_space_count
= count
+ no_similar_count
;
9358 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9361 if( pProto
->BagFamily
)
9363 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9365 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9366 if(res
!=EQUIP_ERR_OK
)
9371 if(no_similar_count
==0)
9372 return EQUIP_ERR_OK
;
9375 *no_space_count
= count
+ no_similar_count
;
9376 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9381 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9383 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9384 if(res
!=EQUIP_ERR_OK
)
9389 if(no_similar_count
==0)
9390 return EQUIP_ERR_OK
;
9393 *no_space_count
= count
+ no_similar_count
;
9394 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9399 // search free slot - special bag case
9400 if( pProto
->BagFamily
)
9402 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9404 uint32 keyringSize
= GetMaxKeyringSize();
9405 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9406 if(res
!=EQUIP_ERR_OK
)
9409 *no_space_count
= count
+ no_similar_count
;
9415 if(no_similar_count
==0)
9416 return EQUIP_ERR_OK
;
9419 *no_space_count
= count
+ no_similar_count
;
9420 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9424 // Vanity pet case skipped as not used
9426 /* until proper implementation
9427 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9429 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9430 if(res!=EQUIP_ERR_OK)
9433 *no_space_count = count + no_similar_count;
9439 if(no_similar_count==0)
9440 return EQUIP_ERR_OK;
9443 *no_space_count = count + no_similar_count;
9444 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9448 /* until proper implementation
9449 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9451 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9452 if(res!=EQUIP_ERR_OK)
9455 *no_space_count = count + no_similar_count;
9461 if(no_similar_count==0)
9462 return EQUIP_ERR_OK;
9465 *no_space_count = count + no_similar_count;
9466 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9471 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9473 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9474 if(res
!=EQUIP_ERR_OK
)
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
;
9490 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9491 if(res
!=EQUIP_ERR_OK
)
9494 *no_space_count
= count
+ no_similar_count
;
9500 if(no_similar_count
==0)
9501 return EQUIP_ERR_OK
;
9504 *no_space_count
= count
+ no_similar_count
;
9505 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9508 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9510 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9511 if(res
!=EQUIP_ERR_OK
)
9516 if(no_similar_count
==0)
9517 return EQUIP_ERR_OK
;
9520 *no_space_count
= count
+ no_similar_count
;
9521 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9526 *no_space_count
= count
+ no_similar_count
;
9528 return EQUIP_ERR_INVENTORY_FULL
;
9531 //////////////////////////////////////////////////////////////////////////
9532 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9537 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9538 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9539 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9540 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9541 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9543 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9544 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9545 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9546 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9547 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9549 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9551 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9553 if (pItem2
&& !pItem2
->IsInTrade())
9555 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9559 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9561 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9563 if (pItem2
&& !pItem2
->IsInTrade())
9565 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9569 // Vanity pet case skipped as not used
9571 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9573 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9575 if (pItem2
&& !pItem2
->IsInTrade())
9577 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9581 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9583 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9585 if (pItem2
&& !pItem2
->IsInTrade())
9587 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9591 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9593 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9595 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9597 pItem2
= GetItemByPos( i
, j
);
9598 if (pItem2
&& !pItem2
->IsInTrade())
9600 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9606 // check free space for all items
9607 for (int k
=0;k
<count
;k
++)
9609 Item
*pItem
= pItems
[k
];
9612 if (!pItem
) continue;
9614 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9615 ItemPrototype
const *pProto
= pItem
->GetProto();
9619 return EQUIP_ERR_ITEM_NOT_FOUND
;
9622 if(pItem
->IsBindedNotWith(GetGUID()))
9623 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9626 ItemPrototype
const *pBagProto
;
9628 // item is 'one item only'
9629 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9630 if(res
!= EQUIP_ERR_OK
)
9633 // search stack for merge to
9634 if( pProto
->Stackable
!= 1 )
9636 bool b_found
= false;
9638 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9640 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9641 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9643 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9648 if (b_found
) continue;
9650 // Vanity pet case skipped as not used
9652 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9654 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9655 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9657 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9662 if (b_found
) continue;
9664 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9666 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9667 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9669 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9674 if (b_found
) continue;
9676 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9678 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9679 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9681 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9686 if (b_found
) continue;
9688 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9690 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9693 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9695 pItem2
= GetItemByPos( t
, j
);
9696 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9698 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9705 if (b_found
) continue;
9709 if( pProto
->BagFamily
)
9711 bool b_found
= false;
9712 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9714 uint32 keyringSize
= GetMaxKeyringSize();
9715 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9717 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9719 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9726 if (b_found
) continue;
9728 // Vanity pet case skipped as not used
9730 /* until proper implementation
9731 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9733 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9735 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9737 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9744 if (b_found) continue;
9746 /* until proper implementation
9747 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9749 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9751 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9753 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9760 if (b_found) continue;
9763 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9765 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9768 pBagProto
= pBag
->GetProto();
9770 // not plain container check
9771 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9772 ItemCanGoIntoBag(pProto
,pBagProto
) )
9774 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9776 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9778 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9786 if (b_found
) continue;
9790 bool b_found
= false;
9791 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9793 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9795 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9800 if (b_found
) continue;
9802 // search free slot in bags
9803 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9805 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9808 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9810 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9812 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9820 // no free slot found?
9822 return EQUIP_ERR_INVENTORY_FULL
;
9825 return EQUIP_ERR_OK
;
9828 //////////////////////////////////////////////////////////////////////////
9829 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9832 Item
*pItem
= Item::CreateItem( item
, 1, this );
9835 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9840 return EQUIP_ERR_ITEM_NOT_FOUND
;
9843 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9848 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9849 ItemPrototype
const *pProto
= pItem
->GetProto();
9852 // May be here should be more stronger checks; STUNNED checked
9853 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9854 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9855 return EQUIP_ERR_YOU_ARE_STUNNED
;
9857 if(pItem
->IsBindedNotWith(GetGUID()))
9858 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9860 // check count of items (skip for auto move for same player from bank)
9861 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9862 if(res
!= EQUIP_ERR_OK
)
9865 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9867 // - in-progress arenas
9868 if( !pProto
->CanChangeEquipStateInCombat() )
9871 return EQUIP_ERR_NOT_IN_COMBAT
;
9873 if(BattleGround
* bg
= GetBattleGround())
9874 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9875 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9878 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9879 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9881 if(IsNonMeleeSpellCasted(false))
9882 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9884 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9885 if( eslot
== NULL_SLOT
)
9886 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9888 uint8 msg
= CanUseItem( pItem
, not_loading
);
9889 if( msg
!= EQUIP_ERR_OK
)
9891 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9892 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9894 // check unique-equipped on item
9895 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9897 // there is an equip limit on this item
9898 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9899 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9900 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9903 // check unique-equipped on gems
9904 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9906 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9909 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9913 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9914 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9916 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9917 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9918 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9922 // check unique-equipped special item classes
9923 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9925 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9927 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9929 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9931 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9932 (!swap
|| pBag
->GetSlot() != eslot
) )
9934 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9935 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9937 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9944 uint32 type
= pProto
->InventoryType
;
9946 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9948 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9951 return EQUIP_ERR_CANT_DUAL_WIELD
;
9953 else if (type
== INVTYPE_2HWEAPON
)
9955 if(!CanDualWield() || !CanTitanGrip())
9956 return EQUIP_ERR_CANT_DUAL_WIELD
;
9960 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9963 // equip two-hand weapon case (with possible unequip 2 items)
9964 if( type
== INVTYPE_2HWEAPON
)
9966 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9968 if (!CanTitanGrip())
9969 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9971 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9972 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9974 if (!CanTitanGrip())
9976 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9977 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9978 ItemPosCountVec off_dest
;
9979 if( offItem
&& (!not_loading
||
9980 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9981 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9982 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9985 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9986 return EQUIP_ERR_OK
;
9990 return EQUIP_ERR_ITEM_NOT_FOUND
;
9992 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9995 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9997 // Applied only to equipped items and bank bags
9998 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9999 return EQUIP_ERR_OK
;
10001 Item
* pItem
= GetItemByPos(pos
);
10003 // Applied only to existed equipped item
10005 return EQUIP_ERR_OK
;
10007 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10009 ItemPrototype
const *pProto
= pItem
->GetProto();
10011 return EQUIP_ERR_ITEM_NOT_FOUND
;
10013 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10015 // - in-progress arenas
10016 if( !pProto
->CanChangeEquipStateInCombat() )
10019 return EQUIP_ERR_NOT_IN_COMBAT
;
10021 if(BattleGround
* bg
= GetBattleGround())
10022 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10023 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10026 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10027 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10029 return EQUIP_ERR_OK
;
10032 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10035 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10037 uint32 count
= pItem
->GetCount();
10039 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10040 ItemPrototype
const *pProto
= pItem
->GetProto();
10042 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10044 if( pItem
->IsBindedNotWith(GetGUID()) )
10045 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10047 // check count of items (skip for auto move for same player from bank)
10048 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10049 if(res
!= EQUIP_ERR_OK
)
10052 // in specific slot
10053 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10055 if( pProto
->InventoryType
== INVTYPE_BAG
)
10057 Bag
*pBag
= (Bag
*)pItem
;
10060 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10062 if( !HasBankBagSlot( slot
) )
10063 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10064 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10069 if( !pBag
->IsEmpty() )
10070 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10076 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10077 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10080 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10081 if(res
!=EQUIP_ERR_OK
)
10085 return EQUIP_ERR_OK
;
10088 // not specific slot or have space for partly store only in specific slot
10091 if( bag
!= NULL_BAG
)
10093 if( pProto
->InventoryType
== INVTYPE_BAG
)
10095 Bag
*pBag
= (Bag
*)pItem
;
10096 if( pBag
&& !pBag
->IsEmpty() )
10097 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10100 // search stack in bag for merge to
10101 if( pProto
->Stackable
!= 1 )
10103 if( bag
== INVENTORY_SLOT_BAG_0
)
10105 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10106 if(res
!=EQUIP_ERR_OK
)
10110 return EQUIP_ERR_OK
;
10114 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10115 if(res
!=EQUIP_ERR_OK
)
10116 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10118 if(res
!=EQUIP_ERR_OK
)
10122 return EQUIP_ERR_OK
;
10126 // search free slot in bag
10127 if( bag
== INVENTORY_SLOT_BAG_0
)
10129 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10130 if(res
!=EQUIP_ERR_OK
)
10134 return EQUIP_ERR_OK
;
10138 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
10139 if(res
!=EQUIP_ERR_OK
)
10140 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
10142 if(res
!=EQUIP_ERR_OK
)
10146 return EQUIP_ERR_OK
;
10150 // not specific bag or have space for partly store only in specific bag
10152 // search stack for merge to
10153 if( pProto
->Stackable
!= 1 )
10156 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10157 if(res
!=EQUIP_ERR_OK
)
10161 return EQUIP_ERR_OK
;
10164 if( pProto
->BagFamily
)
10166 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10168 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10169 if(res
!=EQUIP_ERR_OK
)
10173 return EQUIP_ERR_OK
;
10177 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10179 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10180 if(res
!=EQUIP_ERR_OK
)
10184 return EQUIP_ERR_OK
;
10188 // search free place in special bag
10189 if( pProto
->BagFamily
)
10191 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10193 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10194 if(res
!=EQUIP_ERR_OK
)
10198 return EQUIP_ERR_OK
;
10202 // search free space
10203 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10204 if(res
!=EQUIP_ERR_OK
)
10208 return EQUIP_ERR_OK
;
10210 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10212 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10213 if(res
!=EQUIP_ERR_OK
)
10217 return EQUIP_ERR_OK
;
10219 return EQUIP_ERR_BANK_FULL
;
10222 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10226 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10227 if( !isAlive() && not_loading
)
10228 return EQUIP_ERR_YOU_ARE_DEAD
;
10229 //if( isStunned() )
10230 // return EQUIP_ERR_YOU_ARE_STUNNED;
10231 ItemPrototype
const *pProto
= pItem
->GetProto();
10234 if( pItem
->IsBindedNotWith(GetGUID()) )
10235 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10236 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10237 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10238 if( pItem
->GetSkill() != 0 )
10240 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10241 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10243 if( pProto
->RequiredSkill
!= 0 )
10245 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10246 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10247 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10248 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10250 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10251 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10252 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10253 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10254 if( getLevel() < pProto
->RequiredLevel
)
10255 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10256 return EQUIP_ERR_OK
;
10259 return EQUIP_ERR_ITEM_NOT_FOUND
;
10262 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10264 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10268 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10270 if( pProto
->RequiredSkill
!= 0 )
10272 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10274 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10277 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10279 if( getLevel() < pProto
->RequiredLevel
)
10286 uint8
Player::CanUseAmmo( uint32 item
) const
10288 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10290 return EQUIP_ERR_YOU_ARE_DEAD
;
10291 //if( isStunned() )
10292 // return EQUIP_ERR_YOU_ARE_STUNNED;
10293 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10296 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10297 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10298 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10299 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10300 if( pProto
->RequiredSkill
!= 0 )
10302 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10303 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10304 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10305 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10307 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10308 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10309 /*if( GetReputation() < pProto->RequiredReputation )
10310 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10312 if( getLevel() < pProto
->RequiredLevel
)
10313 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10315 // Requires No Ammo
10316 if(GetDummyAura(46699))
10317 return EQUIP_ERR_BAG_FULL6
;
10319 return EQUIP_ERR_OK
;
10321 return EQUIP_ERR_ITEM_NOT_FOUND
;
10324 void Player::SetAmmo( uint32 item
)
10330 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10336 uint8 msg
= CanUseAmmo( item
);
10337 if( msg
!= EQUIP_ERR_OK
)
10339 SendEquipError( msg
, NULL
, NULL
);
10344 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10346 _ApplyAmmoBonuses();
10349 void Player::RemoveAmmo()
10351 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10355 if(CanModifyStats())
10356 UpdateDamagePhysical(RANGED_ATTACK
);
10359 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10360 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10363 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10364 count
+= itr
->count
;
10366 Item
*pItem
= Item::CreateItem( item
, count
, this );
10369 ItemAddedQuestCheck( item
, count
);
10370 if(randomPropertyId
)
10371 pItem
->SetItemRandomProperties(randomPropertyId
);
10372 pItem
= StoreItem( dest
, pItem
, update
);
10377 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10382 Item
* lastItem
= pItem
;
10384 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10386 uint16 pos
= itr
->pos
;
10387 uint32 count
= itr
->count
;
10391 if(itr
== dest
.end())
10393 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10397 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10403 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10404 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10409 uint8 bag
= pos
>> 8;
10410 uint8 slot
= pos
& 255;
10412 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10414 Item
*pItem2
= GetItemByPos( bag
, slot
);
10419 pItem
= pItem
->CloneItem(count
,this);
10421 pItem
->SetCount(count
);
10426 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10427 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10428 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10429 pItem
->SetBinding( true );
10431 if( bag
== INVENTORY_SLOT_BAG_0
)
10433 m_items
[slot
] = pItem
;
10434 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10435 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10436 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10438 pItem
->SetSlot( slot
);
10439 pItem
->SetContainer( NULL
);
10441 if( IsInWorld() && update
)
10443 pItem
->AddToWorld();
10444 pItem
->SendUpdateToPlayer( this );
10447 pItem
->SetState(ITEM_CHANGED
, this);
10451 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10454 pBag
->StoreItem( slot
, pItem
, update
);
10455 if( IsInWorld() && update
)
10457 pItem
->AddToWorld();
10458 pItem
->SendUpdateToPlayer( this );
10460 pItem
->SetState(ITEM_CHANGED
, this);
10461 pBag
->SetState(ITEM_CHANGED
, this);
10465 AddEnchantmentDurations(pItem
);
10466 AddItemDurations(pItem
);
10472 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10473 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10474 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10475 pItem2
->SetBinding( true );
10477 pItem2
->SetCount( pItem2
->GetCount() + count
);
10478 if( IsInWorld() && update
)
10479 pItem2
->SendUpdateToPlayer( this );
10483 // delete item (it not in any slot currently)
10484 if( IsInWorld() && update
)
10486 pItem
->RemoveFromWorld();
10487 pItem
->DestroyForPlayer( this );
10490 RemoveEnchantmentDurations(pItem
);
10491 RemoveItemDurations(pItem
);
10493 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10494 pItem
->SetState(ITEM_REMOVED
, this);
10496 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10497 AddEnchantmentDurations(pItem2
);
10499 pItem2
->SetState(ITEM_CHANGED
, this);
10505 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10507 Item
*pItem
= Item::CreateItem( item
, 1, this );
10510 ItemAddedQuestCheck( item
, 1 );
10511 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10518 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10522 AddEnchantmentDurations(pItem
);
10523 AddItemDurations(pItem
);
10525 uint8 bag
= pos
>> 8;
10526 uint8 slot
= pos
& 255;
10528 Item
*pItem2
= GetItemByPos( bag
, slot
);
10532 VisualizeItem( slot
, pItem
);
10536 ItemPrototype
const *pProto
= pItem
->GetProto();
10538 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10539 if(pProto
&& pProto
->ItemSet
)
10540 AddItemsSetItem(this,pItem
);
10542 _ApplyItemMods(pItem
, slot
, true);
10544 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10546 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10548 if (getClass() == CLASS_ROGUE
)
10549 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10551 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10554 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10557 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10559 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10560 data
<< uint64(GetGUID());
10562 data
<< uint32(cooldownSpell
);
10564 GetSession()->SendPacket(&data
);
10569 if( IsInWorld() && update
)
10571 pItem
->AddToWorld();
10572 pItem
->SendUpdateToPlayer( this );
10575 ApplyEquipCooldown(pItem
);
10577 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10578 UpdateExpertise(BASE_ATTACK
);
10579 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10580 UpdateExpertise(OFF_ATTACK
);
10584 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10585 if( IsInWorld() && update
)
10586 pItem2
->SendUpdateToPlayer( this );
10588 // delete item (it not in any slot currently)
10589 //pItem->DeleteFromDB();
10590 if( IsInWorld() && update
)
10592 pItem
->RemoveFromWorld();
10593 pItem
->DestroyForPlayer( this );
10596 RemoveEnchantmentDurations(pItem
);
10597 RemoveItemDurations(pItem
);
10599 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10600 pItem
->SetState(ITEM_REMOVED
, this);
10601 pItem2
->SetState(ITEM_CHANGED
, this);
10603 ApplyEquipCooldown(pItem2
);
10612 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10616 AddEnchantmentDurations(pItem
);
10617 AddItemDurations(pItem
);
10619 uint8 slot
= pos
& 255;
10620 VisualizeItem( slot
, pItem
);
10624 pItem
->AddToWorld();
10625 pItem
->SendUpdateToPlayer( this );
10630 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10632 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10633 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10634 // entry // Size: 1
10635 // inspected enchantments // Size: 6
10637 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10638 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10643 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10645 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10646 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10648 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10649 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10651 // Use SetInt16Value to prevent set high part to FFFF for negative value
10652 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10653 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10657 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10659 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10660 SetUInt32Value(VisibleBase
+ 0, 0);
10662 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10663 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10665 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10666 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10670 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10675 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10676 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10677 pItem
->SetBinding( true );
10679 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10681 m_items
[slot
] = pItem
;
10682 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10683 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10684 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10685 pItem
->SetSlot( slot
);
10686 pItem
->SetContainer( NULL
);
10688 if( slot
< EQUIPMENT_SLOT_END
)
10689 SetVisibleItemSlot(slot
,pItem
);
10691 pItem
->SetState(ITEM_CHANGED
, this);
10694 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10696 // note: removeitem does not actually change the item
10697 // it only takes the item out of storage temporarily
10698 // note2: if removeitem is to be used for delinking
10699 // the item must be removed from the player's updatequeue
10701 Item
*pItem
= GetItemByPos( bag
, slot
);
10704 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10706 RemoveEnchantmentDurations(pItem
);
10707 RemoveItemDurations(pItem
);
10709 if( bag
== INVENTORY_SLOT_BAG_0
)
10711 if ( slot
< INVENTORY_SLOT_BAG_END
)
10713 ItemPrototype
const *pProto
= pItem
->GetProto();
10714 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10716 if(pProto
&& pProto
->ItemSet
)
10717 RemoveItemsSetItem(this,pProto
);
10719 _ApplyItemMods(pItem
, slot
, false);
10721 // remove item dependent auras and casts (only weapon and armor slots)
10722 if(slot
< EQUIPMENT_SLOT_END
)
10723 RemoveItemDependentAurasAndCasts(pItem
);
10725 // remove held enchantments
10726 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10728 if (pItem
->GetItemSuffixFactor())
10730 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10731 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10735 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10736 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10741 m_items
[slot
] = NULL
;
10742 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10744 if ( slot
< EQUIPMENT_SLOT_END
)
10745 SetVisibleItemSlot(slot
,NULL
);
10749 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10751 pBag
->RemoveItem(slot
, update
);
10753 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10754 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10755 pItem
->SetSlot( NULL_SLOT
);
10756 if( IsInWorld() && update
)
10757 pItem
->SendUpdateToPlayer( this );
10759 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10760 UpdateExpertise(BASE_ATTACK
);
10761 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10762 UpdateExpertise(OFF_ATTACK
);
10766 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10767 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10769 if(Item
* it
= GetItemByPos(bag
,slot
))
10771 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10772 RemoveItem( bag
,slot
,update
);
10773 it
->RemoveFromUpdateQueueOf(this);
10774 if(it
->IsInWorld())
10776 it
->RemoveFromWorld();
10777 it
->DestroyForPlayer( this );
10782 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10783 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10785 // update quest counters
10786 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10789 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10791 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10792 if(pLastItem
==pItem
)
10794 // update owner for last item (this can be original item with wrong owner
10795 if(pLastItem
->GetOwnerGUID() != GetGUID())
10796 pLastItem
->SetOwnerGUID(GetGUID());
10798 // if this original item then it need create record in inventory
10799 // in case trade we already have item in other player inventory
10800 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10804 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10806 Item
*pItem
= GetItemByPos( bag
, slot
);
10809 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10811 // start from destroy contained items (only equipped bag can have its)
10812 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10814 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10815 DestroyItem(slot
,i
,update
);
10818 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10819 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10821 RemoveEnchantmentDurations(pItem
);
10822 RemoveItemDurations(pItem
);
10824 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10826 if( bag
== INVENTORY_SLOT_BAG_0
)
10828 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10830 // equipment and equipped bags can have applied bonuses
10831 if ( slot
< INVENTORY_SLOT_BAG_END
)
10833 ItemPrototype
const *pProto
= pItem
->GetProto();
10835 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10836 if(pProto
&& pProto
->ItemSet
)
10837 RemoveItemsSetItem(this,pProto
);
10839 _ApplyItemMods(pItem
, slot
, false);
10842 if ( slot
< EQUIPMENT_SLOT_END
)
10844 // remove item dependent auras and casts (only weapon and armor slots)
10845 RemoveItemDependentAurasAndCasts(pItem
);
10847 // equipment visual show
10848 SetVisibleItemSlot(slot
,NULL
);
10851 m_items
[slot
] = NULL
;
10853 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10854 pBag
->RemoveItem(slot
, update
);
10856 if( IsInWorld() && update
)
10858 pItem
->RemoveFromWorld();
10859 pItem
->DestroyForPlayer(this);
10862 //pItem->SetOwnerGUID(0);
10863 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10864 pItem
->SetSlot( NULL_SLOT
);
10865 pItem
->SetState(ITEM_REMOVED
, this);
10869 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10871 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10873 ItemPrototype
const *pProto
;
10874 uint32 remcount
= 0;
10877 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10879 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10880 if( pItem
&& pItem
->GetEntry() == item
)
10882 if( pItem
->GetCount() + remcount
<= count
)
10884 // all items in inventory can unequipped
10885 remcount
+= pItem
->GetCount();
10886 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10888 if(remcount
>=count
)
10893 pProto
= pItem
->GetProto();
10894 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10895 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10896 if( IsInWorld() & update
)
10897 pItem
->SendUpdateToPlayer( this );
10898 pItem
->SetState(ITEM_CHANGED
, this);
10903 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10905 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10906 if( pItem
&& pItem
->GetEntry() == item
)
10908 if( pItem
->GetCount() + remcount
<= count
)
10910 // all keys can be unequipped
10911 remcount
+= pItem
->GetCount();
10912 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10914 if(remcount
>=count
)
10919 pProto
= pItem
->GetProto();
10920 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10921 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10922 if( IsInWorld() & update
)
10923 pItem
->SendUpdateToPlayer( this );
10924 pItem
->SetState(ITEM_CHANGED
, this);
10930 // in inventory bags
10931 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10933 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10935 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10937 pItem
= pBag
->GetItemByPos(j
);
10938 if( pItem
&& pItem
->GetEntry() == item
)
10940 // all items in bags can be unequipped
10941 if( pItem
->GetCount() + remcount
<= count
)
10943 remcount
+= pItem
->GetCount();
10944 DestroyItem( i
, j
, update
);
10946 if(remcount
>=count
)
10951 pProto
= pItem
->GetProto();
10952 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10953 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10954 if( IsInWorld() && update
)
10955 pItem
->SendUpdateToPlayer( this );
10956 pItem
->SetState(ITEM_CHANGED
, this);
10964 // in equipment and bag list
10965 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10967 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10968 if( pItem
&& pItem
->GetEntry() == item
)
10970 if( pItem
->GetCount() + remcount
<= count
)
10972 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10974 remcount
+= pItem
->GetCount();
10975 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10977 if(remcount
>=count
)
10983 pProto
= pItem
->GetProto();
10984 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10985 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10986 if( IsInWorld() & update
)
10987 pItem
->SendUpdateToPlayer( this );
10988 pItem
->SetState(ITEM_CHANGED
, this);
10995 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10997 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
11000 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11002 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11003 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11004 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11006 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
11008 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11009 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11010 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11013 // in inventory bags
11014 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11016 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11019 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11021 Item
* pItem
= pBag
->GetItemByPos(j
);
11022 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11023 DestroyItem( i
, j
, update
);
11028 // in equipment and bag list
11029 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11031 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11032 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11033 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11037 void Player::DestroyConjuredItems( bool update
)
11039 // used when entering arena
11040 // destroys all conjured items
11041 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11044 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11046 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11047 if( pItem
&& pItem
->GetProto() &&
11048 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11049 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11050 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11053 // in inventory bags
11054 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11056 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11059 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11061 Item
* pItem
= pBag
->GetItemByPos(j
);
11062 if( pItem
&& pItem
->GetProto() &&
11063 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11064 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11065 DestroyItem( i
, j
, update
);
11070 // in equipment and bag list
11071 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11073 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11074 if( pItem
&& pItem
->GetProto() &&
11075 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11076 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11077 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11081 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11086 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11088 if( pItem
->GetCount() <= count
)
11090 count
-= pItem
->GetCount();
11092 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11096 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11097 pItem
->SetCount( pItem
->GetCount() - count
);
11099 if( IsInWorld() & update
)
11100 pItem
->SendUpdateToPlayer( this );
11101 pItem
->SetState(ITEM_CHANGED
, this);
11105 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11107 uint8 srcbag
= src
>> 8;
11108 uint8 srcslot
= src
& 255;
11110 uint8 dstbag
= dst
>> 8;
11111 uint8 dstslot
= dst
& 255;
11113 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11116 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11120 // not let split all items (can be only at cheating)
11121 if(pSrcItem
->GetCount() == count
)
11123 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11127 // not let split more existed items (can be only at cheating)
11128 if(pSrcItem
->GetCount() < count
)
11130 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11134 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11136 //best error message found for attempting to split while looting
11137 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11141 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11142 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11145 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11149 if( IsInventoryPos( dst
) )
11151 // change item amount before check (for unique max count check)
11152 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11154 ItemPosCountVec dest
;
11155 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11156 if( msg
!= EQUIP_ERR_OK
)
11159 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11160 SendEquipError( msg
, pSrcItem
, NULL
);
11165 pSrcItem
->SendUpdateToPlayer( this );
11166 pSrcItem
->SetState(ITEM_CHANGED
, this);
11167 StoreItem( dest
, pNewItem
, true);
11169 else if( IsBankPos ( dst
) )
11171 // change item amount before check (for unique max count check)
11172 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11174 ItemPosCountVec dest
;
11175 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11176 if( msg
!= EQUIP_ERR_OK
)
11179 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11180 SendEquipError( msg
, pSrcItem
, NULL
);
11185 pSrcItem
->SendUpdateToPlayer( this );
11186 pSrcItem
->SetState(ITEM_CHANGED
, this);
11187 BankItem( dest
, pNewItem
, true);
11189 else if( IsEquipmentPos ( dst
) )
11191 // change item amount before check (for unique max count check), provide space for splitted items
11192 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11195 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11196 if( msg
!= EQUIP_ERR_OK
)
11199 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11200 SendEquipError( msg
, pSrcItem
, NULL
);
11205 pSrcItem
->SendUpdateToPlayer( this );
11206 pSrcItem
->SetState(ITEM_CHANGED
, this);
11207 EquipItem( dest
, pNewItem
, true);
11208 AutoUnequipOffhandIfNeed();
11212 void Player::SwapItem( uint16 src
, uint16 dst
)
11214 uint8 srcbag
= src
>> 8;
11215 uint8 srcslot
= src
& 255;
11217 uint8 dstbag
= dst
>> 8;
11218 uint8 dstslot
= dst
& 255;
11220 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11221 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11226 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11230 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11234 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11236 //best error message found for attempting to swap while looting
11237 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11241 // check unequip potability for equipped items and bank bags
11242 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11244 // bags can be swapped with empty bag slots
11245 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
11246 if(msg
!= EQUIP_ERR_OK
)
11248 SendEquipError( msg
, pSrcItem
, pDstItem
);
11253 // prevent put equipped/bank bag in self
11254 if( IsBagPos ( src
) && srcslot
== dstbag
)
11256 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11262 if( IsInventoryPos( dst
) )
11264 ItemPosCountVec dest
;
11265 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11266 if( msg
!= EQUIP_ERR_OK
)
11268 SendEquipError( msg
, pSrcItem
, NULL
);
11272 RemoveItem(srcbag
, srcslot
, true);
11273 StoreItem( dest
, pSrcItem
, true);
11275 else if( IsBankPos ( dst
) )
11277 ItemPosCountVec dest
;
11278 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11279 if( msg
!= EQUIP_ERR_OK
)
11281 SendEquipError( msg
, pSrcItem
, NULL
);
11285 RemoveItem(srcbag
, srcslot
, true);
11286 BankItem( dest
, pSrcItem
, true);
11288 else if( IsEquipmentPos ( dst
) )
11291 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11292 if( msg
!= EQUIP_ERR_OK
)
11294 SendEquipError( msg
, pSrcItem
, NULL
);
11298 RemoveItem(srcbag
, srcslot
, true);
11299 EquipItem( dest
, pSrcItem
, true);
11300 AutoUnequipOffhandIfNeed();
11303 else // if (!pDstItem)
11305 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11307 //best error message found for attempting to swap while looting
11308 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11312 // check unequip potability for equipped items and bank bags
11313 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11315 // bags can be swapped with empty bag slots
11316 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
11317 if(msg
!= EQUIP_ERR_OK
)
11319 SendEquipError( msg
, pSrcItem
, pDstItem
);
11324 // attempt merge to / fill target item
11327 ItemPosCountVec sDest
;
11329 if( IsInventoryPos( dst
) )
11330 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11331 else if( IsBankPos ( dst
) )
11332 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11333 else if( IsEquipmentPos ( dst
) )
11334 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11338 // can be merge/fill
11339 if(msg
== EQUIP_ERR_OK
)
11341 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11343 RemoveItem(srcbag
, srcslot
, true);
11345 if( IsInventoryPos( dst
) )
11346 StoreItem( sDest
, pSrcItem
, true);
11347 else if( IsBankPos ( dst
) )
11348 BankItem( sDest
, pSrcItem
, true);
11349 else if( IsEquipmentPos ( dst
) )
11351 EquipItem( eDest
, pSrcItem
, true);
11352 AutoUnequipOffhandIfNeed();
11357 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11358 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11359 pSrcItem
->SetState(ITEM_CHANGED
, this);
11360 pDstItem
->SetState(ITEM_CHANGED
, this);
11363 pSrcItem
->SendUpdateToPlayer( this );
11364 pDstItem
->SendUpdateToPlayer( this );
11371 // impossible merge/fill, do real swap
11374 // check src->dest move possibility
11375 ItemPosCountVec sDest
;
11377 if( IsInventoryPos( dst
) )
11378 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11379 else if( IsBankPos( dst
) )
11380 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11381 else if( IsEquipmentPos( dst
) )
11383 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11384 if( msg
== EQUIP_ERR_OK
)
11385 msg
= CanUnequipItem( eDest
, true );
11388 if( msg
!= EQUIP_ERR_OK
)
11390 SendEquipError( msg
, pSrcItem
, pDstItem
);
11394 // check dest->src move possibility
11395 ItemPosCountVec sDest2
;
11397 if( IsInventoryPos( src
) )
11398 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11399 else if( IsBankPos( src
) )
11400 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11401 else if( IsEquipmentPos( src
) )
11403 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11404 if( msg
== EQUIP_ERR_OK
)
11405 msg
= CanUnequipItem( eDest2
, true);
11408 if( msg
!= EQUIP_ERR_OK
)
11410 SendEquipError( msg
, pDstItem
, pSrcItem
);
11414 // now do moves, remove...
11415 RemoveItem(dstbag
, dstslot
, false);
11416 RemoveItem(srcbag
, srcslot
, false);
11419 if( IsInventoryPos( dst
) )
11420 StoreItem(sDest
, pSrcItem
, true);
11421 else if( IsBankPos( dst
) )
11422 BankItem(sDest
, pSrcItem
, true);
11423 else if( IsEquipmentPos( dst
) )
11424 EquipItem(eDest
, pSrcItem
, true);
11427 if( IsInventoryPos( src
) )
11428 StoreItem(sDest2
, pDstItem
, true);
11429 else if( IsBankPos( src
) )
11430 BankItem(sDest2
, pDstItem
, true);
11431 else if( IsEquipmentPos( src
) )
11432 EquipItem(eDest2
, pDstItem
, true);
11434 AutoUnequipOffhandIfNeed();
11438 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11442 uint32 slot
= m_currentBuybackSlot
;
11443 // if current back slot non-empty search oldest or free
11446 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11447 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11449 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11458 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11460 if(oldest_time
> i_time
)
11462 oldest_time
= i_time
;
11468 slot
= oldest_slot
;
11471 RemoveItemFromBuyBackSlot( slot
, true );
11472 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11474 m_items
[slot
] = pItem
;
11475 time_t base
= time(NULL
);
11476 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11477 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11479 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11480 ItemPrototype
const *pProto
= pItem
->GetProto();
11482 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11484 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11485 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11487 // move to next (for non filled list is move most optimized choice)
11488 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11489 ++m_currentBuybackSlot
;
11493 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11495 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11496 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11497 return m_items
[slot
];
11501 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11503 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11504 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11506 Item
*pItem
= m_items
[slot
];
11509 pItem
->RemoveFromWorld();
11510 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11513 m_items
[slot
] = NULL
;
11515 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11516 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11517 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11518 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11520 // if current backslot is filled set to now free slot
11521 if(m_items
[m_currentBuybackSlot
])
11522 m_currentBuybackSlot
= slot
;
11526 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11528 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11529 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11530 data
<< uint8(msg
);
11534 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11535 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11536 data
<< uint8(0); // not 0 there...
11538 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11543 if(ItemPrototype
const* proto
= pItem
->GetProto())
11544 level
= proto
->RequiredLevel
;
11546 data
<< uint32(level
); // new 2.4.0
11549 GetSession()->SendPacket(&data
);
11552 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11554 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11555 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11556 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11557 data
<< uint32(item
);
11559 data
<< uint32(param
);
11560 data
<< uint8(msg
);
11561 GetSession()->SendPacket(&data
);
11564 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11566 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11567 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11568 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11569 data
<< uint64(guid
);
11571 data
<< uint32(param
);
11572 data
<< uint8(msg
);
11573 GetSession()->SendPacket(&data
);
11576 void Player::ClearTrade()
11579 acceptTrade
= false;
11580 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11581 tradeItems
[i
] = NULL_SLOT
;
11584 void Player::TradeCancel(bool sendback
)
11588 // send yellow "Trade canceled" message to both traders
11592 ws
->SendCancelTrade();
11593 ws
= pTrader
->GetSession();
11594 if(!ws
->PlayerLogout())
11595 ws
->SendCancelTrade();
11599 pTrader
->ClearTrade();
11600 // prevent loss of reference
11601 pTrader
->pTrader
= NULL
;
11606 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11608 if(m_itemDuration
.empty())
11611 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11613 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11616 ++itr
; // current element can be erased in UpdateDuration
11618 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11619 item
->UpdateDuration(this,time
);
11623 void Player::UpdateEnchantTime(uint32 time
)
11625 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11629 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11631 next
= m_enchantDuration
.erase(itr
);
11633 else if(itr
->leftduration
<= time
)
11635 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11636 itr
->item
->ClearEnchantment(itr
->slot
);
11637 next
= m_enchantDuration
.erase(itr
);
11639 else if(itr
->leftduration
> time
)
11641 itr
->leftduration
-= time
;
11647 void Player::AddEnchantmentDurations(Item
*item
)
11649 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11651 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11654 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11656 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11660 void Player::RemoveEnchantmentDurations(Item
*item
)
11662 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11664 if(itr
->item
== item
)
11666 // save duration in item
11667 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11668 itr
= m_enchantDuration
.erase(itr
);
11675 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11677 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11678 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11681 if(itr
->slot
==slot
)
11683 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11685 // remove from stats
11686 ApplyEnchantment(itr
->item
,slot
,false,false);
11688 itr
->item
->ClearEnchantment(slot
);
11690 // remove from update list
11691 next
= m_enchantDuration
.erase(itr
);
11697 // remove enchants from inventory items
11698 // NOTE: no need to remove these from stats, since these aren't equipped
11700 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11702 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11703 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11704 pItem
->ClearEnchantment(slot
);
11707 // in inventory bags
11708 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11710 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11713 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11715 Item
* pItem
= pBag
->GetItemByPos(j
);
11716 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11717 pItem
->ClearEnchantment(slot
);
11723 // duration == 0 will remove item enchant
11724 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11729 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11732 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11734 if(itr
->item
== item
&& itr
->slot
== slot
)
11736 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11737 m_enchantDuration
.erase(itr
);
11741 if(item
&& duration
> 0 )
11743 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11744 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11748 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11750 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11751 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11754 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11759 if(!item
->IsEquipped())
11762 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11765 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11769 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11773 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11776 for (int s
=0; s
<3; s
++)
11778 uint32 enchant_display_type
= pEnchant
->type
[s
];
11779 uint32 enchant_amount
= pEnchant
->amount
[s
];
11780 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11782 switch(enchant_display_type
)
11784 case ITEM_ENCHANTMENT_TYPE_NONE
:
11786 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11787 // processed in Player::CastItemCombatSpell
11789 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11790 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11791 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11792 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11793 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11794 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11795 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11797 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11798 if(enchant_spell_id
)
11802 int32 basepoints
= 0;
11803 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11804 if (item
->GetItemRandomPropertyId())
11806 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11809 // Search enchant_amount
11810 for (int k
=0; k
<3; k
++)
11812 if(item_rand
->enchant_id
[k
] == enchant_id
)
11814 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11820 // Cast custom spell vs all equal basepoints getted from enchant_amount
11822 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11824 CastSpell(this,enchant_spell_id
,true,item
);
11827 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11830 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11831 if (!enchant_amount
)
11833 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11836 for (int k
=0; k
<3; k
++)
11838 if(item_rand
->enchant_id
[k
] == enchant_id
)
11840 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11847 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11849 case ITEM_ENCHANTMENT_TYPE_STAT
:
11851 if (!enchant_amount
)
11853 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11854 if(item_rand_suffix
)
11856 for (int k
=0; k
<3; k
++)
11858 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11860 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11867 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11868 switch (enchant_spell_id
)
11870 case ITEM_MOD_AGILITY
:
11871 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11872 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11873 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11875 case ITEM_MOD_STRENGTH
:
11876 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11877 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11878 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11880 case ITEM_MOD_INTELLECT
:
11881 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11882 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11883 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11885 case ITEM_MOD_SPIRIT
:
11886 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11887 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11888 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11890 case ITEM_MOD_STAMINA
:
11891 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11892 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11893 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11895 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11896 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11897 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11899 case ITEM_MOD_DODGE_RATING
:
11900 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11901 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11903 case ITEM_MOD_PARRY_RATING
:
11904 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11905 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11907 case ITEM_MOD_BLOCK_RATING
:
11908 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11909 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11911 case ITEM_MOD_HIT_MELEE_RATING
:
11912 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11913 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11915 case ITEM_MOD_HIT_RANGED_RATING
:
11916 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11917 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11919 case ITEM_MOD_HIT_SPELL_RATING
:
11920 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11921 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11923 case ITEM_MOD_CRIT_MELEE_RATING
:
11924 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11925 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11927 case ITEM_MOD_CRIT_RANGED_RATING
:
11928 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11929 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11931 case ITEM_MOD_CRIT_SPELL_RATING
:
11932 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11933 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11935 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11937 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11938 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11940 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11941 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11943 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11944 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11946 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11947 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11949 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11950 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11952 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11953 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11955 // case ITEM_MOD_HASTE_MELEE_RATING:
11956 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11958 // case ITEM_MOD_HASTE_RANGED_RATING:
11959 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11961 case ITEM_MOD_HASTE_SPELL_RATING
:
11962 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11964 case ITEM_MOD_HIT_RATING
:
11965 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11966 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11967 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11968 sLog
.outDebug("+ %u HIT", enchant_amount
);
11970 case ITEM_MOD_CRIT_RATING
:
11971 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11972 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11973 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11974 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11976 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11977 // case ITEM_MOD_HIT_TAKEN_RATING:
11978 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11979 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11980 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11982 // case ITEM_MOD_CRIT_TAKEN_RATING:
11983 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11984 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11985 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11987 case ITEM_MOD_RESILIENCE_RATING
:
11988 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11989 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11990 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11991 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11993 case ITEM_MOD_HASTE_RATING
:
11994 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11995 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11996 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11997 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11999 case ITEM_MOD_EXPERTISE_RATING
:
12000 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12001 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12003 case ITEM_MOD_ATTACK_POWER
:
12004 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12005 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12007 case ITEM_MOD_RANGED_ATTACK_POWER
:
12008 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12009 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12011 case ITEM_MOD_FERAL_ATTACK_POWER
:
12012 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
12013 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12015 case ITEM_MOD_SPELL_HEALING_DONE
:
12016 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12017 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
12019 case ITEM_MOD_SPELL_DAMAGE_DONE
:
12020 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12021 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
12023 case ITEM_MOD_MANA_REGENERATION
:
12024 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12025 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12027 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12028 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12029 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12031 case ITEM_MOD_SPELL_POWER
:
12032 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12033 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12034 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12041 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12043 if(getClass() == CLASS_SHAMAN
)
12045 float addValue
= 0.0f
;
12046 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12048 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12049 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12051 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12053 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12054 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12059 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12060 // processed in Player::CastItemUseSpell
12063 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
12065 } /*switch(enchant_display_type)*/
12068 // visualize enchantment at player and equipped items
12069 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
12071 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
12072 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
12080 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12082 AddEnchantmentDuration(item
,slot
,duration
);
12086 // duration == 0 will remove EnchantDuration
12087 AddEnchantmentDuration(item
,slot
,0);
12092 void Player::SendEnchantmentDurations()
12094 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
12096 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
12100 void Player::SendItemDurations()
12102 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
12104 (*itr
)->SendTimeUpdate(this);
12108 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12110 if(!item
) // prevent crash
12113 // last check 2.0.10
12114 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12115 data
<< GetGUID(); // player GUID
12116 data
<< uint32(received
); // 0=looted, 1=from npc
12117 data
<< uint32(created
); // 0=received, 1=created
12118 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12119 data
<< (uint8
)item
->GetBagSlot(); // bagslot
12120 // item slot, but when added to stack: 0xFFFFFFFF
12121 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
12122 data
<< uint32(item
->GetEntry()); // item id
12123 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12124 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12125 data
<< uint32(count
); // count of items
12126 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
12128 if (broadcast
&& GetGroup())
12129 GetGroup()->BroadcastPacket(&data
);
12131 GetSession()->SendPacket(&data
);
12134 /*********************************************************/
12135 /*** QUEST SYSTEM ***/
12136 /*********************************************************/
12138 void Player::PrepareQuestMenu( uint64 guid
)
12141 QuestRelations
* pObjectQR
;
12142 QuestRelations
* pObjectQIR
;
12143 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12146 pObject
= (Object
*)pCreature
;
12147 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12148 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12152 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12155 pObject
= (Object
*)pGameObject
;
12156 pObjectQR
= &objmgr
.mGOQuestRelations
;
12157 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12163 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12166 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12168 uint32 quest_id
= i
->second
;
12169 QuestStatus status
= GetQuestStatus( quest_id
);
12170 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12171 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12172 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12173 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
12174 else if (status
== QUEST_STATUS_AVAILABLE
)
12175 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12178 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12180 uint32 quest_id
= i
->second
;
12181 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12182 if(!pQuest
) continue;
12184 QuestStatus status
= GetQuestStatus( quest_id
);
12186 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12187 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12188 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12189 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12193 void Player::SendPreparedQuest( uint64 guid
)
12195 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12196 if( questMenu
.Empty() )
12199 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12201 uint32 status
= qmi0
.m_qIcon
;
12203 // single element case
12204 if ( questMenu
.MenuItemCount() == 1 )
12206 // Auto open -- maybe also should verify there is no greeting
12207 uint32 quest_id
= qmi0
.m_qId
;
12208 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12211 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12212 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12213 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12214 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12215 // Send completable on repeatable quest if player don't have quest
12216 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12217 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12219 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12222 // multiply entries
12228 std::string title
= "";
12229 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12232 uint32 textid
= pCreature
->GetNpcTextId();
12233 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
12236 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12237 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12242 qe
= gossiptext
->Options
[0].Emotes
[0];
12244 if(!gossiptext
->Options
[0].Text_0
.empty())
12246 title
= gossiptext
->Options
[0].Text_0
;
12248 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12251 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12254 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12255 title
= nl
->Text_0
[0][loc_idx
];
12261 title
= gossiptext
->Options
[0].Text_1
;
12263 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12266 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12269 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12270 title
= nl
->Text_1
[0][loc_idx
];
12276 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12280 bool Player::IsActiveQuest( uint32 quest_id
) const
12282 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12284 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12287 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12290 QuestRelations
* pObjectQR
;
12291 QuestRelations
* pObjectQIR
;
12293 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12296 pObject
= (Object
*)pCreature
;
12297 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12298 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12302 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12305 pObject
= (Object
*)pGameObject
;
12306 pObjectQR
= &objmgr
.mGOQuestRelations
;
12307 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12313 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12314 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12316 if (itr
->second
== nextQuestID
)
12317 return objmgr
.GetQuestTemplate(nextQuestID
);
12323 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12325 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12326 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12327 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12328 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12330 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12336 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12338 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12339 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12340 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12341 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12342 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12343 && SatisfyQuestDay( pQuest
, msg
);
12346 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12348 if( !SatisfyQuestLog( msg
) )
12351 uint32 srcitem
= pQuest
->GetSrcItemId();
12354 uint32 count
= pQuest
->GetSrcItemCount();
12355 ItemPosCountVec dest
;
12356 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12358 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12359 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12361 else if( msg
!= EQUIP_ERR_OK
)
12363 SendEquipError( msg
, NULL
, NULL
);
12370 bool Player::CanCompleteQuest( uint32 quest_id
)
12374 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12375 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12376 return false; // not allow re-complete quest
12378 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12383 // auto complete quest
12384 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12387 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12390 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12392 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12394 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12399 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12401 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12403 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12406 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12411 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12414 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12417 if ( qInfo
->GetRewOrReqMoney() < 0 )
12419 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12423 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12424 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12433 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12435 // Solve problem that player don't have the quest and try complete it.
12436 // if repeatable she must be able to complete event if player don't have it.
12437 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12438 if( !CanTakeQuest(pQuest
, false) )
12441 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12442 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12443 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12446 if( !CanRewardQuest(pQuest
, false) )
12452 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12454 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12455 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12458 // daily quest can't be rewarded (25 daily quest already completed)
12459 if(!SatisfyQuestDay(pQuest
,true))
12462 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12463 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12466 // prevent receive reward with quest items in bank
12467 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12469 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12471 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12472 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12475 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12481 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12482 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12488 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12490 // prevent receive reward with quest items in bank or for not completed quest
12491 if(!CanRewardQuest(pQuest
,msg
))
12494 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12496 if( pQuest
->RewChoiceItemId
[reward
] )
12498 ItemPosCountVec dest
;
12499 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12500 if( res
!= EQUIP_ERR_OK
)
12502 SendEquipError( res
, NULL
, NULL
);
12508 if ( pQuest
->GetRewItemsCount() > 0 )
12510 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12512 if( pQuest
->RewItemId
[i
] )
12514 ItemPosCountVec dest
;
12515 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12516 if( res
!= EQUIP_ERR_OK
)
12518 SendEquipError( res
, NULL
, NULL
);
12528 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12530 uint16 log_slot
= FindQuestSlot( 0 );
12531 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12533 uint32 quest_id
= pQuest
->GetQuestId();
12535 // if not exist then created with set uState==NEW and rewarded=false
12536 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12537 if (questStatusData
.uState
!= QUEST_NEW
)
12538 questStatusData
.uState
= QUEST_CHANGED
;
12540 // check for repeatable quests status reset
12541 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12542 questStatusData
.m_explored
= false;
12544 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12546 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12547 questStatusData
.m_itemcount
[i
] = 0;
12550 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12552 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12553 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12556 GiveQuestSourceItem( pQuest
);
12557 AdjustQuestReqItemCount( pQuest
);
12559 if( pQuest
->GetRepObjectiveFaction() )
12560 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12563 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12565 uint32 limittime
= pQuest
->GetLimitTime();
12567 // shared timed quest
12568 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12569 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12571 AddTimedQuest( quest_id
);
12572 questStatusData
.m_timer
= limittime
* 1000;
12573 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12576 questStatusData
.m_timer
= 0;
12578 SetQuestSlot(log_slot
, quest_id
, qtime
);
12580 //starting initial quest script
12581 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12582 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12584 UpdateForQuestsGO();
12587 void Player::CompleteQuest( uint32 quest_id
)
12591 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12593 uint16 log_slot
= FindQuestSlot( quest_id
);
12594 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12595 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12597 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12599 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12600 RewardQuest(qInfo
,0,this,false);
12602 SendQuestComplete( quest_id
);
12607 void Player::IncompleteQuest( uint32 quest_id
)
12611 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12613 uint16 log_slot
= FindQuestSlot( quest_id
);
12614 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12615 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12619 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12621 uint32 quest_id
= pQuest
->GetQuestId();
12623 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12625 if ( pQuest
->ReqItemId
[i
] )
12626 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12629 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12630 // SetTimedQuest( 0 );
12631 m_timedquests
.erase(pQuest
->GetQuestId());
12633 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12635 if( pQuest
->RewChoiceItemId
[reward
] )
12637 ItemPosCountVec dest
;
12638 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12640 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12641 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12646 if ( pQuest
->GetRewItemsCount() > 0 )
12648 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12650 if( pQuest
->RewItemId
[i
] )
12652 ItemPosCountVec dest
;
12653 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12655 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12656 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12662 RewardReputation( pQuest
);
12664 if( pQuest
->GetRewSpellCast() > 0 )
12665 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12666 else if( pQuest
->GetRewSpell() > 0)
12667 CastSpell( this, pQuest
->GetRewSpell(), true);
12669 uint16 log_slot
= FindQuestSlot( quest_id
);
12670 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12671 SetQuestSlot(log_slot
,0);
12673 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12675 // Not give XP in case already completed once repeatable quest
12676 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12678 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12679 GiveXP( XP
, NULL
);
12681 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12683 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12684 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12687 if(pQuest
->GetRewHonorableKills())
12688 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12691 if(pQuest
->GetCharTitleId())
12693 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12694 SetTitle(titleEntry
);
12697 if(pQuest
->GetBonusTalents())
12699 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12700 InitTalentForLevel();
12703 // Send reward mail
12704 if(pQuest
->GetRewMailTemplateId())
12706 MailMessageType mailType
;
12707 uint32 senderGuidOrEntry
;
12708 switch(questGiver
->GetTypeId())
12711 mailType
= MAIL_CREATURE
;
12712 senderGuidOrEntry
= questGiver
->GetEntry();
12714 case TYPEID_GAMEOBJECT
:
12715 mailType
= MAIL_GAMEOBJECT
;
12716 senderGuidOrEntry
= questGiver
->GetEntry();
12719 mailType
= MAIL_ITEM
;
12720 senderGuidOrEntry
= questGiver
->GetEntry();
12722 case TYPEID_PLAYER
:
12723 mailType
= MAIL_NORMAL
;
12724 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12727 mailType
= MAIL_NORMAL
;
12728 senderGuidOrEntry
= GetGUIDLow();
12732 Loot questMailLoot
;
12734 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12737 MailItemsInfo mi
; // item list preparing
12739 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12741 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12743 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12745 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12746 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12751 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12753 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12755 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12757 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12758 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12763 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12766 if(pQuest
->IsDaily())
12768 SetDailyQuestStatus(quest_id
);
12769 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12772 if ( !pQuest
->IsRepeatable() )
12773 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12775 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12777 q_status
.m_rewarded
= true;
12780 SendQuestReward( pQuest
, XP
, questGiver
);
12782 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12783 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12784 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12787 void Player::FailQuest( uint32 quest_id
)
12791 IncompleteQuest( quest_id
);
12793 uint16 log_slot
= FindQuestSlot( quest_id
);
12794 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12796 SetQuestSlotTimer(log_slot
, 1 );
12797 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12799 SendQuestFailed( quest_id
);
12803 void Player::FailTimedQuest( uint32 quest_id
)
12807 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12809 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12810 q_status
.m_timer
= 0;
12812 IncompleteQuest( quest_id
);
12814 uint16 log_slot
= FindQuestSlot( quest_id
);
12815 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12817 SetQuestSlotTimer(log_slot
, 1 );
12818 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12820 SendQuestTimerFailed( quest_id
);
12824 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12826 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12827 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12829 // skip zone zoneOrSort and 0 case skillOrClass
12830 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12833 int32 questSort
= -zoneOrSort
;
12834 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12836 // check class sort cases in zoneOrSort
12837 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12840 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12845 if( skillOrClass
< 0 )
12847 uint8 reqClass
= -int32(skillOrClass
);
12848 if(getClass() != reqClass
)
12851 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12856 else if( skillOrClass
> 0 )
12858 uint32 reqSkill
= skillOrClass
;
12859 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12862 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12870 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12872 if( getLevel() < qInfo
->GetMinLevel() )
12875 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12881 bool Player::SatisfyQuestLog( bool msg
)
12884 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12889 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12890 GetSession()->SendPacket( &data
);
12891 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12896 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12898 // No previous quest (might be first quest in a series)
12899 if( qInfo
->prevQuests
.empty())
12902 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12904 uint32 prevId
= abs(*iter
);
12906 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12907 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12909 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12911 // If any of the positive previous quests completed, return true
12912 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12914 // skip one-from-all exclusive group
12915 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12918 // each-from-all exclusive group ( < 0)
12919 // can be start if only all quests in prev quest exclusive group completed and rewarded
12920 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12921 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12923 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12925 for(; iter
!= end
; ++iter
)
12927 uint32 exclude_Id
= iter
->second
;
12929 // skip checked quest id, only state of other quests in group is interesting
12930 if(exclude_Id
== prevId
)
12933 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12935 // alternative quest from group also must be completed and rewarded(reported)
12936 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12939 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12945 // If any of the negative previous quests active, return true
12946 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12947 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12949 // skip one-from-all exclusive group
12950 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12953 // each-from-all exclusive group ( < 0)
12954 // can be start if only all quests in prev quest exclusive group active
12955 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12956 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12958 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12960 for(; iter
!= end
; ++iter
)
12962 uint32 exclude_Id
= iter
->second
;
12964 // skip checked quest id, only state of other quests in group is interesting
12965 if(exclude_Id
== prevId
)
12968 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12970 // alternative quest from group also must be active
12971 if( i_exstatus
== mQuestStatus
.end() ||
12972 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12973 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12976 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12985 // Has only positive prev. quests in non-rewarded state
12986 // and negative prev. quests in non-active state
12988 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12993 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12995 uint32 reqraces
= qInfo
->GetRequiredRaces();
12996 if ( reqraces
== 0 )
12998 if( (reqraces
& getRaceMask()) == 0 )
13001 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13007 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13009 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13010 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13013 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13017 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13018 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13021 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13028 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13030 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13031 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13034 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13040 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
13042 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
13045 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13051 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13053 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13054 if(qInfo
->GetExclusiveGroup() <= 0)
13057 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13058 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13060 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13062 for(; iter
!= end
; ++iter
)
13064 uint32 exclude_Id
= iter
->second
;
13066 // skip checked quest id, only state of other quests in group is interesting
13067 if(exclude_Id
== qInfo
->GetQuestId())
13070 // not allow have daily quest if daily quest from exclusive group already recently completed
13071 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13072 if( !SatisfyQuestDay(Nquest
, false) )
13075 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13079 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13081 // alternative quest already started or completed
13082 if( i_exstatus
!= mQuestStatus
.end()
13083 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13086 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13093 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13095 if(!qInfo
->GetNextQuestInChain())
13098 // next quest in chain already started or completed
13099 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13100 if( itr
!= mQuestStatus
.end()
13101 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13104 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13108 // check for all quests further up the chain
13109 // only necessary if there are quest chains with more than one quest that can be skipped
13110 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13114 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13116 // No previous quest in chain
13117 if( qInfo
->prevChainQuests
.empty())
13120 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13122 uint32 prevId
= *iter
;
13124 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13126 if( i_prevstatus
!= mQuestStatus
.end() )
13128 // If any of the previous quests in chain active, return false
13129 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13130 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13133 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13138 // check for all quests further down the chain
13139 // only necessary if there are quest chains with more than one quest that can be skipped
13140 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13144 // No previous quest in chain active
13148 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13150 if(!qInfo
->IsDaily())
13153 bool have_slot
= false;
13154 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13156 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13157 if(qInfo
->GetQuestId()==id
)
13167 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13174 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13176 uint32 srcitem
= pQuest
->GetSrcItemId();
13179 uint32 count
= pQuest
->GetSrcItemCount();
13183 ItemPosCountVec dest
;
13184 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13185 if( msg
== EQUIP_ERR_OK
)
13187 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13188 SendNewItem(item
, count
, true, false);
13191 // player already have max amount required item, just report success
13192 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13195 SendEquipError( msg
, NULL
, NULL
);
13202 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13204 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13207 uint32 srcitem
= qInfo
->GetSrcItemId();
13210 uint32 count
= qInfo
->GetSrcItemCount();
13214 // exist one case when destroy source quest item not possible:
13215 // non un-equippable item (equipped non-empty bag, for example)
13216 uint8 res
= CanUnequipItems(srcitem
,count
);
13217 if(res
!= EQUIP_ERR_OK
)
13220 SendEquipError( res
, NULL
, NULL
);
13224 DestroyItemCount(srcitem
, count
, true, true);
13230 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13232 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13235 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13236 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13237 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13238 && !qInfo
->IsRepeatable() )
13239 return itr
->second
.m_rewarded
;
13246 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13250 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13251 if( itr
!= mQuestStatus
.end() )
13252 return itr
->second
.m_status
;
13254 return QUEST_STATUS_NONE
;
13257 bool Player::CanShareQuest(uint32 quest_id
) const
13259 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13260 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13262 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13263 if( itr
!= mQuestStatus
.end() )
13264 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13269 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13271 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13274 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13276 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13277 m_timedquests
.erase(qInfo
->GetQuestId());
13280 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13282 q_status
.m_status
= status
;
13283 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13286 UpdateForQuestsGO();
13289 // not used in MaNGOS, but used in scripting code
13290 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13292 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13296 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13297 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13298 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13303 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
13305 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13307 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
13309 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13310 if( reqitemcount
!= 0 )
13312 uint32 quest_id
= pQuest
->GetQuestId();
13313 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13315 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13316 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13317 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13323 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13325 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13326 if ( GetQuestSlotQuestId(i
) == quest_id
)
13329 return MAX_QUEST_LOG_SIZE
;
13332 void Player::AreaExploredOrEventHappens( uint32 questId
)
13336 uint16 log_slot
= FindQuestSlot( questId
);
13337 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13339 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13341 if(!q_status
.m_explored
)
13343 q_status
.m_explored
= true;
13344 if (q_status
.uState
!= QUEST_NEW
)
13345 q_status
.uState
= QUEST_CHANGED
;
13348 if( CanCompleteQuest( questId
) )
13349 CompleteQuest( questId
);
13353 //not used in mangosd, function for external script library
13354 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13356 if( Group
*pGroup
= GetGroup() )
13358 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13360 Player
*pGroupGuy
= itr
->getSource();
13362 // for any leave or dead (with not released body) group member at appropriate distance
13363 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13364 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13368 AreaExploredOrEventHappens(questId
);
13371 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13373 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13375 uint32 questid
= GetQuestSlotQuestId(i
);
13376 if ( questid
== 0 )
13379 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13381 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13384 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13385 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13388 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13390 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13391 if ( reqitem
== entry
)
13393 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13394 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13395 if ( curitemcount
< reqitemcount
)
13397 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13398 q_status
.m_itemcount
[j
] += additemcount
;
13399 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13401 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13403 if ( CanCompleteQuest( questid
) )
13404 CompleteQuest( questid
);
13409 UpdateForQuestsGO();
13410 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13413 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13415 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13417 uint32 questid
= GetQuestSlotQuestId(i
);
13420 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13423 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13426 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13428 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13429 if ( reqitem
== entry
)
13431 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13433 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13434 uint32 curitemcount
;
13435 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13436 curitemcount
= q_status
.m_itemcount
[j
];
13438 curitemcount
= GetItemCount(entry
,true);
13439 if ( curitemcount
< reqitemcount
+ count
)
13441 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13442 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13443 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13445 IncompleteQuest( questid
);
13451 UpdateForQuestsGO();
13454 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13456 uint32 addkillcount
= 1;
13457 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13458 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13460 uint32 questid
= GetQuestSlotQuestId(i
);
13464 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13467 // just if !ingroup || !noraidgroup || raidgroup
13468 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13469 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13471 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13473 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13475 // skip GO activate objective or none
13476 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13479 // skip Cast at creature objective
13480 if(qInfo
->ReqSpell
[j
] !=0 )
13483 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13485 if ( reqkill
== entry
)
13487 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13488 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13489 if ( curkillcount
< reqkillcount
)
13491 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13492 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13494 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13496 if ( CanCompleteQuest( questid
) )
13497 CompleteQuest( questid
);
13499 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13508 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13510 bool isCreature
= IS_CREATURE_GUID(guid
);
13512 uint32 addCastCount
= 1;
13513 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13515 uint32 questid
= GetQuestSlotQuestId(i
);
13519 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13523 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13525 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13527 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13529 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13531 // skip kill creature objective (0) or wrong spell casts
13532 if(qInfo
->ReqSpell
[j
] != spell_id
)
13535 uint32 reqTarget
= 0;
13539 // creature activate objectives
13540 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13541 // checked at quest_template loading
13542 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13546 // GO activate objective
13547 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13548 // checked at quest_template loading
13549 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13552 // other not this creature/GO related objectives
13553 if( reqTarget
!= entry
)
13556 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13557 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13558 if ( curCastCount
< reqCastCount
)
13560 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13561 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13563 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13566 if ( CanCompleteQuest( questid
) )
13567 CompleteQuest( questid
);
13569 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13577 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13579 uint32 addTalkCount
= 1;
13580 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13582 uint32 questid
= GetQuestSlotQuestId(i
);
13586 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13590 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13592 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13594 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13596 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13598 // skip spell casts and Gameobject objectives
13599 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13602 uint32 reqTarget
= 0;
13604 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13605 // checked at quest_template loading
13606 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13610 if ( reqTarget
== entry
)
13612 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13613 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13614 if ( curTalkCount
< reqTalkCount
)
13616 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13617 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13619 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13621 if ( CanCompleteQuest( questid
) )
13622 CompleteQuest( questid
);
13624 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13633 void Player::MoneyChanged( uint32 count
)
13635 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13637 uint32 questid
= GetQuestSlotQuestId(i
);
13641 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13642 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13644 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13646 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13648 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13650 if ( CanCompleteQuest( questid
) )
13651 CompleteQuest( questid
);
13654 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13656 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13657 IncompleteQuest( questid
);
13663 bool Player::HasQuestForItem( uint32 itemid
) const
13665 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13667 QuestStatusData
const& q_status
= i
->second
;
13669 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13671 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13675 // hide quest if player is in raid-group and quest is no raid quest
13676 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13679 // There should be no mixed ReqItem/ReqSource drop
13680 // This part for ReqItem drop
13681 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13683 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13686 // This part - for ReqSource
13687 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13689 // examined item is a source item
13690 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13692 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13694 // total count of created ReqItems and SourceItems is less than ReqItemCount
13695 if(qinfo
->ReqItemId
[idx
] != 0 &&
13696 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13699 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13700 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13702 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13705 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13706 else if(qinfo
->ReqSpell
[idx
] != 0)
13708 // not casted and need more reagents/item for use.
13709 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13719 void Player::SendQuestComplete( uint32 quest_id
)
13723 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13724 data
<< uint32(quest_id
);
13725 GetSession()->SendPacket( &data
);
13726 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13730 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13732 uint32 questid
= pQuest
->GetQuestId();
13733 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13734 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13735 data
<< uint32(questid
);
13737 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13739 data
<< uint32(XP
);
13740 data
<< uint32(pQuest
->GetRewOrReqMoney());
13745 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13748 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13749 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13750 GetSession()->SendPacket( &data
);
13752 if (pQuest
->GetQuestCompleteScript() != 0)
13753 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13756 void Player::SendQuestFailed( uint32 quest_id
)
13760 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13762 data
<< uint32(0); // failed reason (4 for inventory is full)
13763 GetSession()->SendPacket( &data
);
13764 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13768 void Player::SendQuestTimerFailed( uint32 quest_id
)
13772 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13774 GetSession()->SendPacket( &data
);
13775 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13779 void Player::SendCanTakeQuestResponse( uint32 msg
)
13781 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13782 data
<< uint32(msg
);
13783 GetSession()->SendPacket( &data
);
13784 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13787 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13791 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13792 data
<< uint64(pPlayer
->GetGUID());
13793 data
<< uint8(msg
); // valid values: 0-8
13794 GetSession()->SendPacket( &data
);
13795 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13799 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13801 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13802 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13803 //data << pQuest->ReqItemId[item_idx];
13805 GetSession()->SendPacket( &data
);
13808 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13810 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13812 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13814 // client expected gameobject template id in form (id|0x80000000)
13815 entry
= (-entry
) | 0x80000000;
13817 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13818 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13819 data
<< uint32(pQuest
->GetQuestId());
13820 data
<< uint32(entry
);
13821 data
<< uint32(old_count
+ add_count
);
13822 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13823 data
<< uint64(guid
);
13824 GetSession()->SendPacket(&data
);
13826 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13827 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13828 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13831 /*********************************************************/
13832 /*** LOAD SYSTEM ***/
13833 /*********************************************************/
13835 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13837 bool delete_result
= true;
13840 // 0 1 2 3 4 5 6 7 8 9
13841 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13842 if(!result
) return false;
13844 else delete_result
= false;
13846 Field
*fields
= result
->Fetch();
13848 if(!LoadValues( fields
[1].GetString()))
13850 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13851 if(delete_result
) delete result
;
13855 // overwrite possible wrong/corrupted guid
13856 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13858 m_name
= fields
[2].GetCppString();
13860 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13861 SetMapId(fields
[6].GetUInt32());
13862 // the instance id is not needed at character enum
13864 m_Played_time
[0] = fields
[7].GetUInt32();
13865 m_Played_time
[1] = fields
[8].GetUInt32();
13867 m_atLoginFlags
= fields
[9].GetUInt32();
13869 // I don't see these used anywhere ..
13872 _LoadBoundInstances();*/
13874 if (delete_result
) delete result
;
13876 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13879 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13880 m_deathState
= DEAD
;
13885 void Player::_LoadDeclinedNames(QueryResult
* result
)
13891 delete m_declinedname
;
13893 m_declinedname
= new DeclinedName
;
13894 Field
*fields
= result
->Fetch();
13895 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13896 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13901 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13903 // arenateamid, played_week, played_season, personal_rating
13904 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13910 Field
*fields
= result
->Fetch();
13912 uint32 arenateamid
= fields
[0].GetUInt32();
13913 uint32 played_week
= fields
[1].GetUInt32();
13914 uint32 played_season
= fields
[2].GetUInt32();
13915 uint32 personal_rating
= fields
[3].GetUInt32();
13917 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13920 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13923 uint8 arenaSlot
= aTeam
->GetSlot();
13925 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13926 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13927 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13928 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13929 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13930 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13932 }while (result
->NextRow());
13936 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13938 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13942 Field
*fields
= result
->Fetch();
13944 x
= fields
[0].GetFloat();
13945 y
= fields
[1].GetFloat();
13946 z
= fields
[2].GetFloat();
13947 o
= fields
[3].GetFloat();
13948 mapid
= fields
[4].GetUInt32();
13949 in_flight
= !fields
[5].GetCppString().empty();
13955 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13957 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13961 Field
*fields
= result
->Fetch();
13963 data
= StrSplit(fields
[0].GetCppString(), " ");
13970 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13972 if(index
>= data
.size())
13975 return (uint32
)atoi(data
[index
].c_str());
13978 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13981 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13982 memcpy(&result
, &temp
, sizeof(result
));
13987 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13990 if(!LoadValuesArrayFromDB(data
,guid
))
13993 return GetUInt32ValueFromArray(data
,index
);
13996 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13999 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
14000 memcpy(&result
, &temp
, sizeof(result
));
14005 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14007 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33
14008 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, 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, arena_pending_points FROM characters WHERE guid = '%u'", guid);
14009 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14013 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14017 Field
*fields
= result
->Fetch();
14019 uint32 dbAccountId
= fields
[1].GetUInt32();
14021 // check if the character's account in the db and the logged in account match.
14022 // player should be able to load/delete character only with correct account!
14023 if( dbAccountId
!= GetSession()->GetAccountId() )
14025 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14030 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14032 m_name
= fields
[3].GetCppString();
14034 // check name limitations
14035 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
14038 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14042 if(!LoadValues( fields
[2].GetString()))
14044 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
14049 // overwrite possible wrong/corrupted guid
14050 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14052 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14053 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14055 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
14056 SetVisibleItemSlot(slot
,NULL
);
14060 delete m_items
[slot
];
14061 m_items
[slot
] = NULL
;
14065 // update money limits
14066 if(GetMoney() > MAX_MONEY_AMOUNT
)
14067 SetMoney(MAX_MONEY_AMOUNT
);
14069 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14072 m_race
= fields
[4].GetUInt8();
14073 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14074 //Other way is to saves m_team into characters table.
14075 setFactionForRace(m_race
);
14078 m_class
= fields
[5].GetUInt8();
14080 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
14083 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
14088 InitPrimaryProffesions(); // to max set before any spell loaded
14090 uint32 transGUID
= fields
[24].GetUInt32();
14091 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
14092 SetMapId(fields
[9].GetUInt32());
14093 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
14095 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14097 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14099 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
14100 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
14101 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
14103 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14105 // check arena teams integrity
14106 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14108 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14112 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
14113 if(at
->HaveMember(GetGUID()))
14116 // arena team not exist or not member, cleanup fields
14117 for(int j
=0; j
< 6; ++j
)
14118 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
14121 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14123 if(!IsPositionValid())
14125 sLog
.outError("ERROR: 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());
14127 SetMapId(info
->mapId
);
14128 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14132 m_movementInfo
.t_x
= 0.0f
;
14133 m_movementInfo
.t_y
= 0.0f
;
14134 m_movementInfo
.t_z
= 0.0f
;
14135 m_movementInfo
.t_o
= 0.0f
;
14138 // load the player's map here if it's not already loaded
14139 Map
*map
= GetMap();
14140 // since the player may not be bound to the map yet, make sure subsequent
14141 // getmap calls won't create new maps
14142 SetInstanceId(map
->GetInstanceId());
14144 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14145 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14147 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14149 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14151 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14154 SaveRecallPosition();
14156 if (transGUID
!= 0)
14158 m_movementInfo
.t_x
= fields
[20].GetFloat();
14159 m_movementInfo
.t_y
= fields
[21].GetFloat();
14160 m_movementInfo
.t_z
= fields
[22].GetFloat();
14161 m_movementInfo
.t_o
= fields
[23].GetFloat();
14163 if( !MaNGOS::IsValidMapCoord(
14164 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14165 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
14166 // transport size limited
14167 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
14169 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14170 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14171 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
14173 SetMapId(info
->mapId
);
14174 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14176 m_movementInfo
.t_x
= 0.0f
;
14177 m_movementInfo
.t_y
= 0.0f
;
14178 m_movementInfo
.t_z
= 0.0f
;
14179 m_movementInfo
.t_o
= 0.0f
;
14185 if (transGUID
!= 0)
14187 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
14189 if( (*iter
)->GetGUIDLow() == transGUID
)
14191 m_transport
= *iter
;
14192 m_transport
->AddPassenger(this);
14193 SetMapId(m_transport
->GetMapId());
14200 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14203 SetMapId(info
->mapId
);
14204 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14206 m_movementInfo
.t_x
= 0.0f
;
14207 m_movementInfo
.t_y
= 0.0f
;
14208 m_movementInfo
.t_z
= 0.0f
;
14209 m_movementInfo
.t_o
= 0.0f
;
14215 time_t now
= time(NULL
);
14216 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14218 // since last logout (in seconds)
14219 uint64 time_diff
= uint64(now
- logoutTime
);
14221 // set value, including drunk invisibility detection
14222 // calculate sobering. after 15 minutes logged out, the player will be sober again
14224 if(time_diff
> 15*MINUTE
)
14227 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14228 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14229 SetDrunkValue(newDrunkenValue
);
14231 m_rest_bonus
= fields
[15].GetFloat();
14232 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14233 float bubble0
= 0.031;
14234 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14235 float bubble1
= 0.125;
14237 if((int32
)fields
[16].GetUInt32() > 0)
14239 float bubble
= fields
[17].GetUInt32() > 0
14240 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14241 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14243 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14246 m_cinematic
= fields
[12].GetUInt32();
14247 m_Played_time
[0]= fields
[13].GetUInt32();
14248 m_Played_time
[1]= fields
[14].GetUInt32();
14250 m_resetTalentsCost
= fields
[18].GetUInt32();
14251 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14253 // reserve some flags
14254 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14256 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14257 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14259 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14261 uint32 extraflags
= fields
[25].GetUInt32();
14263 m_stableSlots
= fields
[26].GetUInt32();
14264 if(m_stableSlots
> 4)
14266 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14270 m_atLoginFlags
= fields
[27].GetUInt32();
14273 // Update Honor kills data
14274 m_lastHonorUpdateTime
= logoutTime
;
14275 UpdateHonorFields();
14277 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14278 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14279 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14281 std::string taxi_nodes
= fields
[31].GetCppString();
14285 // clear channel spell data (if saved at channel spell casting)
14286 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14287 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14289 // clear charm/summon related fields
14296 // reset some aura modifiers before aura apply
14297 SetFarSightGUID(0);
14298 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14299 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14303 // make sure the unit is considered out of combat for proper loading
14306 // make sure the unit is considered not in duel for proper loading
14307 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14308 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14310 // remember loaded power/health values to restore after stats initialization and modifier applying
14311 uint32 savedHealth
= GetHealth();
14312 uint32 savedPower
[MAX_POWERS
];
14313 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14314 savedPower
[i
] = GetPower(Powers(i
));
14316 // reset stats before loading any modifiers
14317 InitStatsForLevel();
14318 InitTaxiNodesForLevel();
14319 InitGlyphsForLevel();
14322 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14324 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14327 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14330 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14331 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14332 m_deathState
= DEAD
;
14334 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14336 // after spell load, learn rewarded spell if need also
14337 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14338 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14340 // after spell and quest load
14341 InitTalentForLevel();
14342 learnDefaultSpells();
14344 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14346 // must be before inventory (some items required reputation check)
14347 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14349 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14351 // update items with duration and realtime
14352 UpdateItemDuration(time_diff
, true);
14354 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14356 // unread mails and next delivery time, actual mails not loaded
14357 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14359 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14361 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14364 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14365 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14366 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14368 if(!HasTitle(curTitle
))
14369 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14372 // Not finish taxi flight path
14373 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14375 // problems with taxi path loading
14376 TaxiNodesEntry
const* nodeEntry
= NULL
;
14377 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14378 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14380 if(!nodeEntry
) // don't know taxi start node, to homebind
14382 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14383 SetMapId(m_homebindMapId
);
14384 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
14385 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14387 else // have start node, to it
14389 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14390 SetMapId(nodeEntry
->map_id
);
14391 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14392 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14394 m_taxi
.ClearTaxiDestinations();
14396 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14398 // save source node as recall coord to prevent recall and fall from sky
14399 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14400 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14401 m_recallMap
= nodeEntry
->map_id
;
14402 m_recallX
= nodeEntry
->x
;
14403 m_recallY
= nodeEntry
->y
;
14404 m_recallZ
= nodeEntry
->z
;
14406 // flight will started later
14409 // has to be called after last Relocate() in Player::LoadFromDB
14410 SetFallInformation(0, GetPositionZ());
14412 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14414 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14415 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14417 RemoveAllAurasOnDeath();
14419 //apply all stat bonuses from items and auras
14420 SetCanModifyStats(true);
14423 // restore remembered power/health values (but not more max values)
14424 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14425 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14426 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14428 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14432 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14434 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14437 case 0: break; // disable
14438 case 1: SetGameMaster(true); break; // enable
14439 case 2: // save state
14440 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14441 SetGameMaster(true);
14445 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14448 case 0: SetGMVisible(false); break; // invisible
14449 case 1: break; // visible
14450 case 2: // save state
14451 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14452 SetGMVisible(false);
14456 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14459 case 0: break; // disable
14460 case 1: SetAcceptTicket(true); break; // enable
14461 case 2: // save state
14462 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14463 SetAcceptTicket(true);
14467 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14470 case 0: break; // disable
14471 case 1: SetGMChat(true); break; // enable
14472 case 2: // save state
14473 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14478 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14481 case 0: break; // disable
14482 case 1: SetAcceptWhispers(true); break; // enable
14483 case 2: // save state
14484 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14485 SetAcceptWhispers(true);
14490 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14492 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14493 m_achievementMgr
.CheckAllAchievementCriteria();
14497 bool Player::isAllowedToLoot(Creature
* creature
)
14499 if(Player
* recipient
= creature
->GetLootRecipient())
14501 if (recipient
== this)
14503 if( Group
* otherGroup
= recipient
->GetGroup())
14505 Group
* thisGroup
= GetGroup();
14508 return thisGroup
== otherGroup
;
14513 // prevent other players from looting if the recipient got disconnected
14514 return !creature
->hasLootRecipient();
14517 void Player::_LoadActions(QueryResult
*result
)
14519 m_actionButtons
.clear();
14521 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14527 Field
*fields
= result
->Fetch();
14529 uint8 button
= fields
[0].GetUInt8();
14531 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
14533 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14535 while( result
->NextRow() );
14541 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14544 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14545 m_modAuras
[i
].clear();
14547 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14553 Field
*fields
= result
->Fetch();
14554 uint64 caster_guid
= fields
[0].GetUInt64();
14555 uint32 spellid
= fields
[1].GetUInt32();
14556 uint32 effindex
= fields
[2].GetUInt32();
14557 uint32 stackcount
= fields
[3].GetUInt32();
14558 int32 damage
= (int32
)fields
[4].GetUInt32();
14559 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14560 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14561 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14563 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14566 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14572 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14576 // negative effects should continue counting down after logout
14577 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14579 if(remaintime
<= int32(timediff
))
14582 remaintime
-= timediff
;
14585 // prevent wrong values of remaincharges
14586 if(spellproto
->procCharges
)
14588 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14589 remaincharges
= spellproto
->procCharges
;
14594 //do not load single target auras (unless they were cast by the player)
14595 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14598 for(uint32 i
=0; i
<stackcount
; i
++)
14600 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14602 damage
= aura
->GetModifier()->m_amount
;
14603 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14605 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14608 while( result
->NextRow() );
14613 if(m_class
== CLASS_WARRIOR
)
14614 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14617 void Player::_LoadGlyphAuras()
14619 for (uint8 i
= 0; i
<= MAX_GLYPH_SLOT_INDEX
; ++i
)
14621 if (uint32 glyph
= GetGlyph(i
))
14623 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14625 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14627 if(gp
->TypeFlags
== gs
->TypeFlags
)
14629 CastSpell(this, gp
->SpellId
, true);
14633 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14636 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14639 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14641 // On any error remove glyph
14647 void Player::LoadCorpse()
14651 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14655 if(Corpse
*corpse
= GetCorpse())
14657 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14661 //Prevent Dead Player login without corpse
14662 ResurrectPlayer(0.5f
);
14667 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14669 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
14670 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14671 //NOTE: the "order by `bag`" is important because it makes sure
14672 //the bagMap is filled before items in the bags are loaded
14673 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14674 //expected to be equipped before offhand items (TODO: fixme)
14676 uint32 zone
= GetZoneId();
14680 std::list
<Item
*> problematicItems
;
14682 // prevent items from being added to the queue when stored
14683 m_itemUpdateQueueBlocked
= true;
14686 Field
*fields
= result
->Fetch();
14687 uint32 bag_guid
= fields
[1].GetUInt32();
14688 uint8 slot
= fields
[2].GetUInt8();
14689 uint32 item_guid
= fields
[3].GetUInt32();
14690 uint32 item_id
= fields
[4].GetUInt32();
14692 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14696 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14697 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14698 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14702 Item
*item
= NewItemOrBag(proto
);
14704 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14706 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14707 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14708 item
->FSetState(ITEM_REMOVED
);
14709 item
->SaveToDB(); // it also deletes item object !
14713 // not allow have in alive state item limited to another map/zone
14714 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14716 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14717 item
->FSetState(ITEM_REMOVED
);
14718 item
->SaveToDB(); // it also deletes item object !
14722 // "Conjured items disappear if you are logged out for more than 15 minutes"
14723 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14725 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14726 item
->FSetState(ITEM_REMOVED
);
14727 item
->SaveToDB(); // it also deletes item object !
14731 bool success
= true;
14735 // the item is not in a bag
14736 item
->SetContainer( NULL
);
14737 item
->SetSlot(slot
);
14739 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14741 ItemPosCountVec dest
;
14742 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14743 item
= StoreItem(dest
, item
, true);
14747 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14750 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14751 QuickEquipItem(dest
, item
);
14755 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14757 ItemPosCountVec dest
;
14758 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14759 item
= BankItem(dest
, item
, true);
14766 // store bags that may contain items in them
14767 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14768 bagMap
[item_guid
] = (Bag
*)item
;
14773 item
->SetSlot(NULL_SLOT
);
14774 // the item is in a bag, find the bag
14775 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14776 if(itr
!= bagMap
.end())
14777 itr
->second
->StoreItem(slot
, item
, true );
14782 // item's state may have changed after stored
14784 item
->SetState(ITEM_UNCHANGED
, this);
14787 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
);
14788 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14789 problematicItems
.push_back(item
);
14791 } while (result
->NextRow());
14794 m_itemUpdateQueueBlocked
= false;
14796 // send by mail problematic items
14797 while(!problematicItems
.empty())
14800 MailItemsInfo mi
; // item list preparing
14802 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14804 Item
* item
= problematicItems
.front();
14805 problematicItems
.pop_front();
14807 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14810 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14812 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14816 _ApplyAllItemMods();
14819 // load mailed item which should receive current player
14820 void Player::_LoadMailedItems(Mail
*mail
)
14822 // data needs to be at first place for Item::LoadFromDB
14823 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail
->messageID
);
14829 Field
*fields
= result
->Fetch();
14830 uint32 item_guid_low
= fields
[1].GetUInt32();
14831 uint32 item_template
= fields
[2].GetUInt32();
14833 mail
->AddItem(item_guid_low
, item_template
);
14835 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14839 sLog
.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low
, item_template
,mail
->messageID
);
14840 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14841 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14845 Item
*item
= NewItemOrBag(proto
);
14847 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14849 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14850 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14851 item
->FSetState(ITEM_REMOVED
);
14852 item
->SaveToDB(); // it also deletes item object !
14857 } while (result
->NextRow());
14862 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14864 //set a count of unread mails
14865 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14868 Field
*fieldMail
= resultUnread
->Fetch();
14869 unReadMails
= fieldMail
[0].GetUInt8();
14870 delete resultUnread
;
14873 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14874 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14875 if (resultDelivery
)
14877 Field
*fieldMail
= resultDelivery
->Fetch();
14878 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14879 delete resultDelivery
;
14883 void Player::_LoadMail()
14886 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14887 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
14892 Field
*fields
= result
->Fetch();
14893 Mail
*m
= new Mail
;
14894 m
->messageID
= fields
[0].GetUInt32();
14895 m
->messageType
= fields
[1].GetUInt8();
14896 m
->sender
= fields
[2].GetUInt32();
14897 m
->receiver
= fields
[3].GetUInt32();
14898 m
->subject
= fields
[4].GetCppString();
14899 m
->itemTextId
= fields
[5].GetUInt32();
14900 bool has_items
= fields
[6].GetBool();
14901 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14902 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14903 m
->money
= fields
[9].GetUInt32();
14904 m
->COD
= fields
[10].GetUInt32();
14905 m
->checked
= fields
[11].GetUInt32();
14906 m
->stationery
= fields
[12].GetUInt8();
14907 m
->mailTemplateId
= fields
[13].GetInt16();
14909 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14911 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14912 m
->mailTemplateId
= 0;
14915 m
->state
= MAIL_STATE_UNCHANGED
;
14918 _LoadMailedItems(m
);
14920 m_mail
.push_back(m
);
14921 } while( result
->NextRow() );
14924 m_mailsLoaded
= true;
14927 void Player::LoadPet()
14929 //fixme: the pet should still be loaded if the player is not in world
14930 // just not added to the map
14933 Pet
*pet
= new Pet
;
14934 if(!pet
->LoadPetFromDB(this,0,0,true))
14939 void Player::_LoadQuestStatus(QueryResult
*result
)
14941 mQuestStatus
.clear();
14945 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14946 //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());
14952 Field
*fields
= result
->Fetch();
14954 uint32 quest_id
= fields
[0].GetUInt32();
14955 // used to be new, no delete?
14956 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14960 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14962 uint32 qstatus
= fields
[1].GetUInt32();
14963 if(qstatus
< MAX_QUEST_STATUS
)
14964 questStatusData
.m_status
= QuestStatus(qstatus
);
14967 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14968 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14971 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14972 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14974 time_t quest_time
= time_t(fields
[4].GetUInt64());
14976 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14978 AddTimedQuest( quest_id
);
14980 if (quest_time
<= sWorld
.GetGameTime())
14981 questStatusData
.m_timer
= 1;
14983 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14988 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14989 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14990 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14991 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14992 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14993 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14994 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14995 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14997 questStatusData
.uState
= QUEST_UNCHANGED
;
14999 // add to quest log
15000 if( slot
< MAX_QUEST_LOG_SIZE
&&
15001 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
15002 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
15003 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
15005 SetQuestSlot(slot
,quest_id
,quest_time
);
15007 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15008 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
15010 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15011 if(questStatusData
.m_creatureOrGOcount
[idx
])
15012 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
15017 if(questStatusData
.m_rewarded
)
15019 // learn rewarded spell if unknown
15020 learnQuestRewardedSpells(pQuest
);
15022 // set rewarded title if any
15023 if(pQuest
->GetCharTitleId())
15025 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15026 SetTitle(titleEntry
);
15029 if(pQuest
->GetBonusTalents())
15030 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
15033 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15036 while( result
->NextRow() );
15041 // clear quest log tail
15042 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15046 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15048 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15049 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15051 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15055 uint32 quest_daily_idx
= 0;
15059 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15061 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15065 Field
*fields
= result
->Fetch();
15067 uint32 quest_id
= fields
[0].GetUInt32();
15069 // save _any_ from daily quest times (it must be after last reset anyway)
15070 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15072 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15076 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15079 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15081 while( result
->NextRow() );
15086 m_DailyQuestChanged
= false;
15089 void Player::_LoadReputation(QueryResult
*result
)
15091 m_factions
.clear();
15093 // Set initial reputations (so everything is nifty before DB data load)
15094 SetInitialFactions();
15096 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15102 Field
*fields
= result
->Fetch();
15104 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
15105 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
15107 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
15109 // update standing to current
15110 faction
->Standing
= int32(fields
[1].GetUInt32());
15112 uint32 dbFactionFlags
= fields
[2].GetUInt32();
15114 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
15115 SetFactionVisible(faction
); // have internal checks for forced invisibility
15117 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
15118 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
15120 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
15121 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15122 else // DB not at war
15124 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15125 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
15126 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15129 // set atWar for hostile
15130 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
15131 SetFactionAtWar(faction
,true);
15133 // reset changed flag if values similar to saved in DB
15134 if(faction
->Flags
==dbFactionFlags
)
15135 faction
->Changed
= false;
15138 while( result
->NextRow() );
15144 void Player::_LoadSpells(QueryResult
*result
)
15146 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
15147 delete itr
->second
;
15150 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15156 Field
*fields
= result
->Fetch();
15158 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
15160 while( result
->NextRow() );
15166 void Player::_LoadTutorials(QueryResult
*result
)
15168 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15174 Field
*fields
= result
->Fetch();
15176 for (int iI
=0; iI
<8; iI
++)
15177 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
15179 while( result
->NextRow() );
15184 m_TutorialsChanged
= false;
15187 void Player::_LoadGroup(QueryResult
*result
)
15189 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15192 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
15194 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
15197 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15198 SetGroup(group
, subgroup
);
15199 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
15201 // the group leader may change the instance difficulty while the player is offline
15202 SetDifficulty(group
->GetDifficulty());
15208 void Player::_LoadBoundInstances(QueryResult
*result
)
15210 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15211 m_boundInstances
[i
].clear();
15213 Group
*group
= GetGroup();
15215 //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));
15220 Field
*fields
= result
->Fetch();
15221 bool perm
= fields
[1].GetBool();
15222 uint32 mapId
= fields
[2].GetUInt32();
15223 uint32 instanceId
= fields
[0].GetUInt32();
15224 uint8 difficulty
= fields
[3].GetUInt8();
15225 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15226 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15227 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15228 // and in that case it is not used
15232 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
);
15233 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15237 // since non permanent binds are always solo bind, they can always be reset
15238 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15239 if(save
) BindToInstance(save
, perm
, true);
15240 } while(result
->NextRow());
15245 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15247 // some instances only have one difficulty
15248 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15249 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15251 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15252 if(itr
!= m_boundInstances
[difficulty
].end())
15253 return &itr
->second
;
15258 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15260 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15261 UnbindInstance(itr
, difficulty
, unload
);
15264 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15266 if(itr
!= m_boundInstances
[difficulty
].end())
15268 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15269 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15270 m_boundInstances
[difficulty
].erase(itr
++);
15274 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15278 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15281 // update the save when the group kills a boss
15282 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15283 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());
15286 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15288 if(bind
.save
!= save
)
15290 if(bind
.save
) bind
.save
->RemovePlayer(this);
15291 save
->AddPlayer(this);
15294 if(permanent
) save
->SetCanReset(false);
15297 bind
.perm
= permanent
;
15298 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());
15305 void Player::SendRaidInfo()
15307 uint32 counter
= 0;
15309 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15311 size_t p_counter
= data
.wpos();
15312 data
<< uint32(counter
); // placeholder
15314 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15316 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15318 if(itr
->second
.perm
)
15320 InstanceSave
*save
= itr
->second
.save
;
15321 data
<< uint32(save
->GetMapId());
15322 data
<< uint32(save
->GetResetTime() - time(NULL
));
15323 data
<< uint32(save
->GetInstanceId());
15324 data
<< uint32(save
->GetDifficulty());
15329 data
.put
<uint32
>(p_counter
,counter
);
15330 GetSession()->SendPacket(&data
);
15334 - called on every successful teleportation to a map
15336 void Player::SendSavedInstances()
15338 bool hasBeenSaved
= false;
15341 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15343 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15345 if(itr
->second
.perm
) // only permanent binds are sent
15347 hasBeenSaved
= true;
15353 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15354 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15355 data
<< uint32(hasBeenSaved
);
15356 GetSession()->SendPacket(&data
);
15361 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15363 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15365 if(itr
->second
.perm
)
15367 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15368 data
<< uint32(itr
->second
.save
->GetMapId());
15369 GetSession()->SendPacket(&data
);
15375 /// convert the player's binds to the group
15376 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15378 bool has_binds
= false;
15379 bool has_solo
= false;
15381 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15382 assert(player_guid
);
15384 // copy all binds to the group, when changing leader it's assumed the character
15385 // will not have any solo binds
15389 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15391 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15394 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15395 // permanent binds are not removed
15396 if(!itr
->second
.perm
)
15398 player
->UnbindInstance(itr
, i
, true); // increments itr
15407 // if the player's not online we don't know what binds it has
15408 if(!player
|| !group
|| has_binds
) CharacterDatabase
.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid
));
15409 // the following should not get executed when changing leaders
15410 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15413 bool Player::_LoadHomeBind(QueryResult
*result
)
15416 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15419 Field
*fields
= result
->Fetch();
15420 m_homebindMapId
= fields
[0].GetUInt32();
15421 m_homebindZoneId
= fields
[1].GetUInt16();
15422 m_homebindX
= fields
[2].GetFloat();
15423 m_homebindY
= fields
[3].GetFloat();
15424 m_homebindZ
= fields
[4].GetFloat();
15427 // accept saved data only for valid position (and non instanceable)
15428 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15429 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
15434 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15439 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15440 if(!info
) return false;
15442 m_homebindMapId
= info
->mapId
;
15443 m_homebindZoneId
= info
->zoneId
;
15444 m_homebindX
= info
->positionX
;
15445 m_homebindY
= info
->positionY
;
15446 m_homebindZ
= info
->positionZ
;
15448 CharacterDatabase
.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId
, (uint32
)m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15451 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15452 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15457 /*********************************************************/
15458 /*** SAVE SYSTEM ***/
15459 /*********************************************************/
15461 void Player::SaveToDB()
15463 // delay auto save at any saves (manual, in code, or autosave)
15464 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15466 // first save/honor gain after midnight will also update the player's honor fields
15467 UpdateHonorFields();
15469 // players aren't saved on battleground maps
15470 uint32 mapid
= IsBeingTeleported() ? GetTeleportDest().mapid
: GetMapId();
15471 const MapEntry
* me
= sMapStore
.LookupEntry(mapid
);
15472 if(!me
|| me
->IsBattleGroundOrArena())
15475 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15476 //save, far from tavern/city
15477 //save, but in tavern/city
15478 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15481 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15482 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15483 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15484 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15485 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15486 uint32 tmp_displayid
= GetDisplayId();
15488 // Set player sit state to standing on save, also stealth and shifted form
15489 SetStandState(UNIT_STAND_STATE_STAND
); // stand state
15490 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // stand flags?
15491 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15492 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15493 SetDisplayId(GetNativeDisplayId());
15495 bool inworld
= IsInWorld();
15497 CharacterDatabase
.BeginTransaction();
15499 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15501 std::string sql_name
= m_name
;
15502 CharacterDatabase
.escape_string(sql_name
);
15504 std::ostringstream ss
;
15505 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15506 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15507 "taximask, online, cinematic, "
15508 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15509 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15510 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15511 << GetGUIDLow() << ", "
15512 << GetSession()->GetAccountId() << ", '"
15513 << sql_name
<< "', "
15515 << m_class
<< ", ";
15517 bool save_to_dest
= false;
15518 if(IsBeingTeleported())
15520 // don't save to battlegrounds or arenas
15521 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
15522 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
15523 save_to_dest
= true;
15528 ss
<< GetMapId() << ", "
15529 << (uint32
)GetDifficulty() << ", "
15530 << finiteAlways(GetPositionX()) << ", "
15531 << finiteAlways(GetPositionY()) << ", "
15532 << finiteAlways(GetPositionZ()) << ", "
15533 << finiteAlways(GetOrientation()) << ", '";
15537 ss
<< GetTeleportDest().mapid
<< ", "
15538 << (uint32
)GetDifficulty() << ", "
15539 << finiteAlways(GetTeleportDest().x
) << ", "
15540 << finiteAlways(GetTeleportDest().y
) << ", "
15541 << finiteAlways(GetTeleportDest().z
) << ", "
15542 << finiteAlways(GetTeleportDest().o
) << ", '";
15546 for( i
= 0; i
< m_valuesCount
; i
++ )
15548 ss
<< GetUInt32Value(i
) << " ";
15553 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15556 ss
<< (inworld
? 1 : 0);
15562 ss
<< m_Played_time
[0];
15564 ss
<< m_Played_time
[1];
15567 ss
<< finiteAlways(m_rest_bonus
);
15569 ss
<< (uint64
)time(NULL
);
15571 ss
<< is_save_resting
;
15573 ss
<< m_resetTalentsCost
;
15575 ss
<< (uint64
)m_resetTalentsTime
;
15578 ss
<< finiteAlways(m_movementInfo
.t_x
);
15580 ss
<< finiteAlways(m_movementInfo
.t_y
);
15582 ss
<< finiteAlways(m_movementInfo
.t_z
);
15584 ss
<< finiteAlways(m_movementInfo
.t_o
);
15587 ss
<< m_transport
->GetGUIDLow();
15592 ss
<< m_ExtraFlags
;
15595 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15598 ss
<< uint32(m_atLoginFlags
);
15604 ss
<< (uint64
)m_deathExpireTime
;
15607 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15610 CharacterDatabase
.Execute( ss
.str().c_str() );
15612 if(m_mailsUpdated
) //save mails only when needed
15616 _SaveQuestStatus();
15617 _SaveDailyQuestStatus();
15620 _SaveSpellCooldowns();
15625 CharacterDatabase
.CommitTransaction();
15627 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15628 SetDisplayId(tmp_displayid
);
15629 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15630 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15631 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15632 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15634 // save pet (hunter pet level and experience and all type pets health/mana).
15635 if(Pet
* pet
= GetPet())
15636 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15637 m_achievementMgr
.SaveToDB();
15640 // fast save function for item/money cheating preventing - save only inventory and money state
15641 void Player::SaveInventoryAndGoldToDB()
15644 //money is in data field
15645 SaveDataFieldToDB();
15648 void Player::_SaveActions()
15650 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15652 switch (itr
->second
.uState
)
15654 case ACTIONBUTTON_NEW
:
15655 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15656 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15657 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15660 case ACTIONBUTTON_CHANGED
:
15661 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15662 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15663 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15666 case ACTIONBUTTON_DELETED
:
15667 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15668 m_actionButtons
.erase(itr
++);
15677 void Player::_SaveAuras()
15679 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15681 AuraMap
const& auras
= GetAuras();
15686 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15687 uint32 stackCounter
= 1;
15689 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15691 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15693 AuraMap::const_iterator itr2
= itr
;
15694 // save previous spellEffectPair to db
15696 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15698 //skip all auras from spells that are passive or need a shapeshift
15699 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15701 //do not save single target auras (unless they were cast by the player)
15702 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15705 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15706 for (i
= 0; i
< 3; i
++)
15707 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15708 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15713 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15714 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15715 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->GetAuraCharges()));
15720 if(itr
== auras
.end())
15724 if (lastEffectPair
== itr
->first
)
15728 lastEffectPair
= itr
->first
;
15734 void Player::_SaveInventory()
15736 // force items in buyback slots to new state
15737 // and remove those that aren't already
15738 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15740 Item
*item
= m_items
[i
];
15741 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15742 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15743 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15744 m_items
[i
]->FSetState(ITEM_NEW
);
15747 // update enchantment durations
15748 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15750 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15754 if (m_itemUpdateQueue
.empty()) return;
15756 // do not save if the update queue is corrupt
15757 bool error
= false;
15758 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15760 Item
*item
= m_itemUpdateQueue
[i
];
15761 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15762 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15766 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());
15769 else if (test
!= item
)
15771 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());
15778 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15779 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15783 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15785 Item
*item
= m_itemUpdateQueue
[i
];
15786 if(!item
) continue;
15788 Bag
*container
= item
->GetContainer();
15789 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15791 switch(item
->GetState())
15794 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());
15797 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());
15800 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15802 case ITEM_UNCHANGED
:
15806 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15808 m_itemUpdateQueue
.clear();
15811 void Player::_SaveMail()
15813 if (!m_mailsLoaded
)
15816 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15819 if (m
->state
== MAIL_STATE_CHANGED
)
15821 CharacterDatabase
.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD
"', deliver_time = '" I64FMTD
"',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15822 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15823 if(m
->removedItems
.size())
15825 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15826 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15827 m
->removedItems
.clear();
15829 m
->state
= MAIL_STATE_UNCHANGED
;
15831 else if (m
->state
== MAIL_STATE_DELETED
)
15834 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15835 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15837 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15838 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15839 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15843 //deallocate deleted mails...
15844 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15846 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15851 itr
= m_mail
.begin();
15857 m_mailsUpdated
= false;
15860 void Player::_SaveQuestStatus()
15862 // we don't need transactions here.
15863 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15865 switch (i
->second
.uState
)
15868 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15869 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15870 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ 1000 + 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]);
15872 case QUEST_CHANGED
:
15873 CharacterDatabase
.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD
"',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15874 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ 1000 + 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
);
15876 case QUEST_UNCHANGED
:
15879 i
->second
.uState
= QUEST_UNCHANGED
;
15883 void Player::_SaveDailyQuestStatus()
15885 if(!m_DailyQuestChanged
)
15888 m_DailyQuestChanged
= false;
15890 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15892 // we don't need transactions here.
15893 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15894 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15895 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15896 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15897 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15900 void Player::_SaveReputation()
15902 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15904 if (itr
->second
.Changed
)
15906 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15907 CharacterDatabase
.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr
->second
.ID
, itr
->second
.Standing
, itr
->second
.Flags
);
15908 itr
->second
.Changed
= false;
15913 void Player::_SaveSpells()
15915 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15917 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15918 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15920 // add only changed/new not dependent spells
15921 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15922 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);
15924 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15926 delete itr
->second
;
15927 m_spells
.erase(itr
++);
15931 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15938 void Player::_SaveTutorials()
15940 if(!m_TutorialsChanged
)
15944 // it's better than rebuilding indexes multiple times
15945 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15948 Rows
= result
->Fetch()[0].GetUInt32();
15954 CharacterDatabase
.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15955 m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7], GetSession()->GetAccountId(), realmID
);
15959 CharacterDatabase
.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID
, m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7]);
15962 m_TutorialsChanged
= false;
15965 void Player::outDebugValues() const
15967 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15970 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15971 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15972 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15973 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15974 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15975 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15976 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15977 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15978 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15979 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15980 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15981 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15984 /*********************************************************/
15985 /*** FLOOD FILTER SYSTEM ***/
15986 /*********************************************************/
15988 void Player::UpdateSpeakTime()
15990 // ignore chat spam protection for GMs in any mode
15991 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15994 time_t current
= time (NULL
);
15995 if(m_speakTime
> current
)
15997 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
16002 if(m_speakCount
>= max_count
)
16004 // prevent overwrite mute time, if message send just before mutes set, for example.
16005 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
16006 if(GetSession()->m_muteTime
< new_mute
)
16007 GetSession()->m_muteTime
= new_mute
;
16015 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
16018 bool Player::CanSpeak() const
16020 return GetSession()->m_muteTime
<= time (NULL
);
16023 /*********************************************************/
16024 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16025 /*********************************************************/
16027 void Player::SendAttackSwingNotInRange()
16029 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16030 GetSession()->SendPacket( &data
);
16033 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16035 std::ostringstream ss
;
16036 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16037 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16038 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16039 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16040 sLog
.outDebug(ss
.str().c_str());
16041 CharacterDatabase
.Execute(ss
.str().c_str());
16044 void Player::SaveDataFieldToDB()
16046 std::ostringstream ss
;
16047 ss
<<"UPDATE characters SET data='";
16049 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
16051 ss
<< GetUInt32Value(i
) << " ";
16053 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16055 CharacterDatabase
.Execute(ss
.str().c_str());
16058 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16060 std::ostringstream ss2
;
16061 ss2
<<"UPDATE characters SET data='";
16063 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16065 ss2
<<tokens
[i
]<<" ";
16067 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16069 return CharacterDatabase
.Execute(ss2
.str().c_str());
16072 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16075 snprintf(buf
,11,"%u",value
);
16077 if(index
>= tokens
.size())
16080 tokens
[index
] = buf
;
16083 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16086 if(!LoadValuesArrayFromDB(tokens
,guid
))
16089 if(index
>= tokens
.size())
16093 snprintf(buf
,11,"%u",value
);
16094 tokens
[index
] = buf
;
16096 SaveValuesArrayInDB(tokens
,guid
);
16099 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16102 memcpy(&temp
, &value
, sizeof(value
));
16103 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16106 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16109 if(!LoadValuesArrayFromDB(tokens
, guid
))
16112 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
16113 uint8 race
= unit_bytes0
& 0xFF;
16114 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
16116 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
16120 unit_bytes0
&= ~(0xFF << 16);
16121 unit_bytes0
|= (gender
<< 16);
16122 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
16124 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16125 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16127 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
16129 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
16130 player_bytes2
&= ~0xFF;
16131 player_bytes2
|= facialHair
;
16132 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
16134 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
16135 player_bytes3
&= ~0xFF;
16136 player_bytes3
|= gender
;
16137 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
16139 SaveValuesArrayInDB(tokens
, guid
);
16142 void Player::SendAttackSwingNotStanding()
16144 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
16145 GetSession()->SendPacket( &data
);
16148 void Player::SendAttackSwingDeadTarget()
16150 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16151 GetSession()->SendPacket( &data
);
16154 void Player::SendAttackSwingCantAttack()
16156 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16157 GetSession()->SendPacket( &data
);
16160 void Player::SendAttackSwingCancelAttack()
16162 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16163 GetSession()->SendPacket( &data
);
16166 void Player::SendAttackSwingBadFacingAttack()
16168 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16169 GetSession()->SendPacket( &data
);
16172 void Player::SendAutoRepeatCancel()
16174 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
16175 data
.append(GetPackGUID()); // may be it's target guid
16176 GetSession()->SendPacket( &data
);
16179 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
16181 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
16184 GetSession()->SendPacket( &data
);
16186 SendMessageToSet( &data
, true );
16189 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16191 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16193 data
<< Experience
;
16194 GetSession()->SendPacket(&data
);
16197 void Player::SendDungeonDifficulty(bool IsInGroup
)
16199 uint8 val
= 0x00000001;
16200 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16201 data
<< (uint32
)GetDifficulty();
16202 data
<< uint32(val
);
16203 data
<< uint32(IsInGroup
);
16204 GetSession()->SendPacket(&data
);
16207 void Player::SendResetFailedNotify(uint32 mapid
)
16209 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16210 data
<< uint32(mapid
);
16211 GetSession()->SendPacket(&data
);
16214 /// Reset all solo instances and optionally send a message on success for each
16215 void Player::ResetInstances(uint8 method
)
16217 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16219 // we assume that when the difficulty changes, all instances that can be reset will be
16220 uint8 dif
= GetDifficulty();
16222 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
16224 InstanceSave
*p
= itr
->second
.save
;
16225 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16226 if(!entry
|| !p
->CanReset())
16232 if(method
== INSTANCE_RESET_ALL
)
16234 // the "reset all instances" method can only reset normal maps
16235 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16242 // if the map is loaded, reset it
16243 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16244 if(map
&& map
->IsDungeon())
16245 ((InstanceMap
*)map
)->Reset(method
);
16247 // since this is a solo instance there should not be any players inside
16248 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16249 SendResetInstanceSuccess(p
->GetMapId());
16252 m_boundInstances
[dif
].erase(itr
++);
16254 // the following should remove the instance save from the manager and delete it as well
16255 p
->RemovePlayer(this);
16259 void Player::SendResetInstanceSuccess(uint32 MapId
)
16261 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16263 GetSession()->SendPacket(&data
);
16266 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16268 // TODO: find what other fail reasons there are besides players in the instance
16269 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16272 GetSession()->SendPacket(&data
);
16275 /*********************************************************/
16276 /*** Update timers ***/
16277 /*********************************************************/
16279 ///checks the 15 afk reports per 5 minutes limit
16280 void Player::UpdateAfkReport(time_t currTime
)
16282 if(m_bgAfkReportedTimer
<= currTime
)
16284 m_bgAfkReportedCount
= 0;
16285 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16289 void Player::UpdateContestedPvP(uint32 diff
)
16291 if(!m_contestedPvPTimer
||isInCombat())
16293 if(m_contestedPvPTimer
<= diff
)
16295 ResetContestedPvP();
16298 m_contestedPvPTimer
-= diff
;
16301 void Player::UpdatePvPFlag(time_t currTime
)
16305 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16311 void Player::UpdateDuelFlag(time_t currTime
)
16313 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16316 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16317 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16319 duel
->startTimer
= 0;
16320 duel
->startTime
= currTime
;
16321 duel
->opponent
->duel
->startTimer
= 0;
16322 duel
->opponent
->duel
->startTime
= currTime
;
16325 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16330 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16332 //returning of reagents only for players, so best done here
16333 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16334 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16338 for(uint32 i
= 0; i
< 7; ++i
)
16340 if(spellInfo
->Reagent
[i
] > 0)
16342 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16343 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16344 if( msg
== EQUIP_ERR_OK
)
16346 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16348 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16353 m_temporaryUnsummonedPetNumber
= 0;
16356 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16359 // only if current pet in slot
16360 switch(pet
->getPetType())
16366 m_guardianPets
.erase(pet
->GetGUID());
16369 if(GetPetGUID() == pet
->GetGUID())
16378 switch(pet
->GetEntry())
16380 //warlock pets except imp are removed(?) when logging out
16385 mode
= PET_SAVE_NOT_IN_SLOT
;
16390 pet
->SavePetToDB(mode
);
16392 pet
->CleanupsBeforeDelete();
16393 pet
->AddObjectToRemoveList();
16394 pet
->m_removed
= true;
16396 if(pet
->isControlled())
16398 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16401 GetSession()->SendPacket(&data
);
16404 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16408 void Player::RemoveMiniPet()
16410 if(Pet
* pet
= GetMiniPet())
16412 pet
->Remove(PET_SAVE_AS_DELETED
);
16417 Pet
* Player::GetMiniPet()
16421 return ObjectAccessor::GetPet(m_miniPet
);
16424 void Player::RemoveGuardians()
16426 while(!m_guardianPets
.empty())
16428 uint64 guid
= *m_guardianPets
.begin();
16429 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16430 pet
->Remove(PET_SAVE_AS_DELETED
);
16432 m_guardianPets
.erase(guid
);
16436 bool Player::HasGuardianWithEntry(uint32 entry
)
16438 // pet guid middle part is entry (and creature also)
16439 // and in guardian list must be guardians with same entry _always_
16440 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16441 if(GUID_ENPART(*itr
)==entry
)
16447 void Player::Uncharm()
16449 Unit
* charm
= GetCharm();
16453 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16454 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16457 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16459 *data
<< (uint8
)msgtype
;
16460 *data
<< (uint32
)language
;
16461 *data
<< (uint64
)GetGUID();
16462 *data
<< (uint32
)language
; //language 2.1.0 ?
16463 *data
<< (uint64
)GetGUID();
16464 *data
<< (uint32
)(text
.length()+1);
16466 *data
<< (uint8
)chatTag();
16469 void Player::Say(const std::string
& text
, const uint32 language
)
16471 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16472 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16473 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16476 void Player::Yell(const std::string
& text
, const uint32 language
)
16478 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16479 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16480 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16483 void Player::TextEmote(const std::string
& text
)
16485 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16486 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16487 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16490 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16492 if (language
!= LANG_ADDON
) // if not addon data
16493 language
= LANG_UNIVERSAL
; // whispers should always be readable
16495 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16497 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16498 if(!rPlayer
->isDND() || isGameMaster())
16500 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16501 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16502 rPlayer
->GetSession()->SendPacket(&data
);
16504 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16505 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16506 GetSession()->SendPacket(&data
);
16510 // announce to player that player he is whispering to is dnd and cannot receive his message
16511 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16514 if(!isAcceptWhispers())
16516 SetAcceptWhispers(true);
16517 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16520 // announce to player that player he is whispering to is afk
16521 if(rPlayer
->isAFK())
16522 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16524 // if player whisper someone, auto turn of dnd to be able to receive an answer
16525 if(isDND() && !rPlayer
->isGameMaster())
16529 void Player::PetSpellInitialize()
16531 Pet
* pet
= GetPet();
16536 sLog
.outDebug("Pet Spells Groups");
16538 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16540 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16541 data
<< uint64(pet
->GetGUID());
16542 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16544 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16547 for(uint32 i
= 0; i
< 10; i
++)
16549 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16552 size_t spellsCountPos
= data
.wpos();
16556 data
<< uint8(addlist
); // placeholder
16558 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16561 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16563 if(itr
->second
->state
== PETSPELL_REMOVED
)
16566 data
<< uint16(itr
->first
);
16567 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16572 data
.put
<uint8
>(spellsCountPos
, addlist
);
16574 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16575 data
<< uint8(cooldownsCount
);
16577 time_t curTime
= time(NULL
);
16579 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16581 time_t cooldown
= 0;
16583 if(itr
->second
> curTime
)
16584 cooldown
= (itr
->second
- curTime
) * 1000;
16586 data
<< uint16(itr
->first
); // spellid
16587 data
<< uint16(0); // spell category?
16588 data
<< uint32(itr
->second
); // cooldown
16589 data
<< uint32(0); // category cooldown
16592 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16594 time_t cooldown
= 0;
16596 if(itr
->second
> curTime
)
16597 cooldown
= (itr
->second
- curTime
) * 1000;
16599 data
<< uint16(itr
->first
); // spellid
16600 data
<< uint16(0); // spell category?
16601 data
<< uint32(0); // cooldown
16602 data
<< uint32(itr
->second
); // category cooldown
16605 GetSession()->SendPacket(&data
);
16608 void Player::PossessSpellInitialize()
16610 Unit
* charm
= GetCharm();
16615 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16619 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16624 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16627 data
<< uint64(charm
->GetGUID());
16628 data
<< uint32(0x00000000);
16630 data
<< uint8(0) << uint8(0) << uint16(0);
16632 for(uint32 i
= 0; i
< 10; i
++) //40
16634 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16637 data
<< uint8(addlist
); //1
16640 data
<< uint8(count
); // cooldowns count
16642 GetSession()->SendPacket(&data
);
16645 void Player::CharmSpellInitialize()
16647 Unit
* charm
= GetCharm();
16652 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16655 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16661 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16663 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16665 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16667 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16669 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16675 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16677 data
<< uint64(charm
->GetGUID());
16678 data
<< uint32(0x00000000);
16680 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16681 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16683 data
<< uint8(0) << uint8(0);
16686 for(uint32 i
= 0; i
< 10; i
++) //40
16688 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16691 data
<< uint8(addlist
); //1
16695 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16697 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16698 if(cspell
->spellId
)
16700 data
<< uint16(cspell
->spellId
);
16701 data
<< uint16(cspell
->active
);
16707 data
<< uint8(count
); // cooldowns count
16709 GetSession()->SendPacket(&data
);
16712 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16714 if (!mod
|| !spellInfo
)
16717 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16719 // prevent apply to any spell except spell that trigger expire
16722 if(mod
->lastAffected
!= spell
)
16725 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16729 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16732 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16734 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16736 for(int eff
=0;eff
<96;++eff
)
16740 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16741 else _mask2
= uint64(1) << (eff
-64);
16742 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16745 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16747 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16748 val
+= (*itr
)->value
;
16750 val
+= apply
? mod
->value
: -(mod
->value
);
16751 WorldPacket
data(Opcode
, (1+1+4));
16752 data
<< uint8(eff
);
16753 data
<< uint8(mod
->op
);
16754 data
<< int32(val
);
16755 SendDirectMessage(&data
);
16760 m_spellMods
[mod
->op
].push_back(mod
);
16763 if (mod
->charges
== -1)
16764 --m_SpellModRemoveCount
;
16765 m_spellMods
[mod
->op
].remove(mod
);
16770 void Player::RemoveSpellMods(Spell
const* spell
)
16772 if(!spell
|| (m_SpellModRemoveCount
== 0))
16775 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16777 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16779 SpellModifier
*mod
= *itr
;
16782 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16784 RemoveAurasDueToSpell(mod
->spellId
);
16785 if (m_spellMods
[i
].empty())
16788 itr
= m_spellMods
[i
].begin();
16794 // send Proficiency
16795 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16797 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16798 data
<< pr1
<< pr2
;
16799 GetSession()->SendPacket (&data
);
16802 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16804 QueryResult
*result
= NULL
;
16806 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16808 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16811 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.
16812 { // and SendPetitionQueryOpcode reads data from the DB
16813 Field
*fields
= result
->Fetch();
16814 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16815 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16817 // send update if charter owner in game
16818 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16820 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16822 } while ( result
->NextRow() );
16827 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16829 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16832 CharacterDatabase
.BeginTransaction();
16835 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16836 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16840 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16841 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16843 CharacterDatabase
.CommitTransaction();
16846 void Player::LeaveAllArenaTeams(uint64 guid
)
16848 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
));
16854 Field
*fields
= result
->Fetch();
16855 uint32 at_id
= fields
[0].GetUInt32();
16858 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16860 at
->DelMember(guid
);
16862 } while (result
->NextRow());
16867 void Player::SetRestBonus (float rest_bonus_new
)
16869 // Prevent resting on max level
16870 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16871 rest_bonus_new
= 0;
16873 if(rest_bonus_new
< 0)
16874 rest_bonus_new
= 0;
16876 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16878 if(rest_bonus_new
> rest_bonus_max
)
16879 m_rest_bonus
= rest_bonus_max
;
16881 m_rest_bonus
= rest_bonus_new
;
16883 // update data for client
16884 if(m_rest_bonus
>10)
16885 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16886 else if(m_rest_bonus
<=1)
16887 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16890 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16893 void Player::HandleStealthedUnitsDetection()
16895 std::list
<Unit
*> stealthedUnits
;
16897 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16899 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16900 cell
.SetNoCreate();
16902 MaNGOS::AnyStealthedCheck u_check
;
16903 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16905 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16906 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16908 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16909 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16910 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16912 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16916 i
= stealthedUnits
.erase(i
);
16920 if ((*i
)->isVisibleForOrDetect(this,true))
16923 (*i
)->SendUpdateToPlayer(this);
16924 m_clientGUIDs
.insert((*i
)->GetGUID());
16926 #ifdef MANGOS_DEBUG
16927 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16928 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16931 // target aura duration for caster show only if target exist at caster client
16932 // send data at target visibility change (adding to client)
16933 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16934 SendAurasForTarget(*i
);
16936 i
= stealthedUnits
.erase(i
);
16944 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16946 if(nodes
.size() < 2)
16949 // not let cheating with start flight mounted
16952 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16953 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16954 GetSession()->SendPacket(&data
);
16958 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16960 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16961 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16962 GetSession()->SendPacket(&data
);
16966 // 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
16967 if(GetSession()->isLogingOut() ||
16968 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16969 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16970 IsNonMeleeSpellCasted(false) ||
16973 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16974 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16975 GetSession()->SendPacket(&data
);
16979 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16982 uint32 sourcenode
= nodes
[0];
16984 // starting node too far away (cheat?)
16985 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16986 if( !node
|| node
->map_id
!= GetMapId() ||
16987 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16988 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16989 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16990 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16992 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16993 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16994 GetSession()->SendPacket(&data
);
16998 // Prepare to flight start now
17000 // stop combat at start taxi flight if any
17003 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17006 // clean not finished taxi path if any
17007 m_taxi
.ClearTaxiDestinations();
17009 // 0 element current node
17010 m_taxi
.AddTaxiDestination(sourcenode
);
17012 // fill destinations path tail
17013 uint32 sourcepath
= 0;
17014 uint32 totalcost
= 0;
17016 uint32 prevnode
= sourcenode
;
17017 uint32 lastnode
= 0;
17019 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17023 lastnode
= nodes
[i
];
17024 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17028 m_taxi
.ClearTaxiDestinations();
17034 if(prevnode
== sourcenode
)
17037 m_taxi
.AddTaxiDestination(lastnode
);
17039 prevnode
= lastnode
;
17042 if(!mount_id
) // if not provide then attempt use default.
17043 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
17045 if (mount_id
== 0 || sourcepath
== 0)
17047 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17048 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17049 GetSession()->SendPacket(&data
);
17050 m_taxi
.ClearTaxiDestinations();
17054 uint32 money
= GetMoney();
17058 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17061 if(money
< totalcost
)
17063 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17064 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17065 GetSession()->SendPacket(&data
);
17066 m_taxi
.ClearTaxiDestinations();
17070 //Checks and preparations done, DO FLIGHT
17071 ModifyMoney(-(int32
)totalcost
);
17073 // prevent stealth flight
17074 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17076 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17077 data
<< uint32(ERR_TAXIOK
);
17078 GetSession()->SendPacket(&data
);
17080 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17082 GetSession()->SendDoFlight(mount_id
, sourcepath
);
17087 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17089 // last check 2.0.10
17090 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17092 data
<< uint8(0x0); // flags (0x1, 0x2)
17093 time_t curTime
= time(NULL
);
17094 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17096 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
17098 uint32 unSpellId
= itr
->first
;
17099 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17106 // Not send cooldown for this spells
17107 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17110 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17113 data
<< unTimeMs
; // in m.secs
17114 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
17117 GetSession()->SendPacket(&data
);
17120 void Player::InitDataForForm(bool reapplyMods
)
17122 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17123 if(ssEntry
&& ssEntry
->attackSpeed
)
17125 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17126 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17127 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17130 SetRegularAttackTime();
17136 if(getPowerType()!=POWER_ENERGY
)
17137 setPowerType(POWER_ENERGY
);
17141 case FORM_DIREBEAR
:
17143 if(getPowerType()!=POWER_RAGE
)
17144 setPowerType(POWER_RAGE
);
17147 default: // 0, for example
17149 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17150 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17151 setPowerType(Powers(cEntry
->powerType
));
17156 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17158 UpdateEquipSpellsAtFormChange();
17160 UpdateAttackPowerAndDamage();
17161 UpdateAttackPowerAndDamage(true);
17164 // Return true is the bought item has a max count to force refresh of window by caller
17165 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
17167 // cheating attempt
17168 if(count
< 1) count
= 1;
17173 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17176 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17180 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17183 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17184 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17188 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17189 if(!vItems
|| vItems
->Empty())
17191 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17195 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17196 if(vendor_slot
>= vItems
->GetItemCount())
17198 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17202 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17204 // check current item amount if it limited
17205 if( crItem
->maxcount
!= 0 )
17207 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17209 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17214 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17216 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17220 if(crItem
->ExtendedCost
)
17222 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17225 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17229 // honor points price
17230 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17232 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17236 // arena points price
17237 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17239 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17244 for (uint8 i
= 0; i
< 5; ++i
)
17246 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17248 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17253 // check for personal arena rating requirement
17254 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17256 // probably not the proper equip err
17257 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17262 uint32 price
= pProto
->BuyPrice
* count
;
17264 // reputation discount
17265 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17267 if( GetMoney() < price
)
17269 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17273 uint8 bag
= 0; // init for case invalid bagGUID
17275 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17278 if( bagguid
== GetGUID() )
17280 bag
= INVENTORY_SLOT_BAG_0
;
17284 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17286 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17289 if( bagguid
== pBag
->GetGUID() )
17299 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17301 ItemPosCountVec dest
;
17302 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17303 if( msg
!= EQUIP_ERR_OK
)
17305 SendEquipError( msg
, NULL
, NULL
);
17309 ModifyMoney( -(int32
)price
);
17310 if(crItem
->ExtendedCost
) // case for new honor system
17312 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17313 if(iece
->reqhonorpoints
)
17314 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17315 if(iece
->reqarenapoints
)
17316 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17317 for (uint8 i
= 0; i
< 5; ++i
)
17319 if(iece
->reqitem
[i
])
17320 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17324 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17326 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17328 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17329 data
<< pCreature
->GetGUID();
17330 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17331 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17332 data
<< (uint32
)count
;
17333 GetSession()->SendPacket(&data
);
17335 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17338 else if( IsEquipmentPos( bag
, slot
) )
17340 if(pProto
->BuyCount
* count
!= 1)
17342 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17347 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17348 if( msg
!= EQUIP_ERR_OK
)
17350 SendEquipError( msg
, NULL
, NULL
);
17354 ModifyMoney( -(int32
)price
);
17355 if(crItem
->ExtendedCost
) // case for new honor system
17357 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17358 if(iece
->reqhonorpoints
)
17359 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17360 if(iece
->reqarenapoints
)
17361 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17362 for (uint8 i
= 0; i
< 5; ++i
)
17364 if(iece
->reqitem
[i
])
17365 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17369 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17371 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17373 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17374 data
<< pCreature
->GetGUID();
17375 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17376 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17377 data
<< (uint32
)count
;
17378 GetSession()->SendPacket(&data
);
17380 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17382 AutoUnequipOffhandIfNeed();
17387 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17391 return crItem
->maxcount
!=0;
17394 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17396 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17397 // the personal rating of the arena team must match the required limit as well
17398 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17399 uint32 max_personal_rating
= 0;
17400 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17402 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17404 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17405 uint32 t_rating
= at
->GetRating();
17406 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17407 if(max_personal_rating
< p_rating
)
17408 max_personal_rating
= p_rating
;
17411 return max_personal_rating
;
17414 void Player::UpdateHomebindTime(uint32 time
)
17416 // GMs never get homebind timer online
17417 if (m_InstanceValid
|| isGameMaster())
17419 if(m_HomebindTimer
) // instance valid, but timer not reset
17422 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17425 GetSession()->SendPacket(&data
);
17427 // instance is valid, reset homebind timer
17428 m_HomebindTimer
= 0;
17430 else if (m_HomebindTimer
> 0)
17432 if (time
>= m_HomebindTimer
)
17434 // teleport to homebind location
17435 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17438 m_HomebindTimer
-= time
;
17442 // instance is invalid, start homebind timer
17443 m_HomebindTimer
= 60000;
17444 // send message to player
17445 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17446 data
<< m_HomebindTimer
;
17448 GetSession()->SendPacket(&data
);
17449 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17453 void Player::UpdatePvP(bool state
, bool ovrride
)
17455 if(!state
|| ovrride
)
17458 if(Pet
* pet
= GetPet())
17459 pet
->SetPvP(state
);
17460 if(Unit
* charmed
= GetCharm())
17461 charmed
->SetPvP(state
);
17463 pvpInfo
.endTimer
= 0;
17467 if(pvpInfo
.endTimer
!= 0)
17468 pvpInfo
.endTimer
= time(NULL
);
17473 if(Pet
* pet
= GetPet())
17474 pet
->SetPvP(state
);
17475 if(Unit
* charmed
= GetCharm())
17476 charmed
->SetPvP(state
);
17481 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17485 sc
.itemid
= itemid
;
17486 m_spellCooldowns
[spellid
] = sc
;
17489 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
17491 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
17494 // Get spell cooldown
17495 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
17497 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
17501 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
17503 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17504 data
<< spellInfo
->Id
;
17506 SendDirectMessage(&data
);
17508 //slot to be excluded while counting
17509 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17511 if(!enchantmentcondition
)
17514 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17519 uint8 curcount
[4] = {0, 0, 0, 0};
17521 //counting current equipped gem colors
17522 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17526 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17527 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17529 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17531 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17535 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17539 uint32 gemid
= enchantEntry
->GemID
;
17543 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17547 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17551 uint8 GemColor
= gemProperty
->color
;
17553 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17555 if(tmpcolormask
& GemColor
)
17562 bool activate
= true;
17564 for(int i
= 0; i
< 5; i
++)
17566 if(!Condition
->Color
[i
])
17569 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17571 // if have <CompareColor> use them as count, else use <value> from Condition
17572 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17574 switch(Condition
->Comparator
[i
])
17576 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17577 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17579 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17580 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17582 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17583 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17588 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");
17593 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17595 //cycle all equipped items
17596 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17598 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17599 if(slot
== exceptslot
)
17602 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17604 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17607 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17609 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17613 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17617 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17620 //was enchant active with/without item?
17621 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17622 //should it now be?
17623 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17625 // ignore item gem conditions
17626 //if state changed, (dis)apply enchant
17627 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17634 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17635 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17637 //cycle all equipped items
17638 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17640 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17641 if(slot
== exceptslot
)
17644 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17646 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17649 //cycle all (gem)enchants
17650 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17652 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17653 if(!enchant_id
) //if no enchant go to next enchant(slot)
17656 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17660 //only metagems to be (de)activated, so only enchants with condition
17661 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17663 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17668 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17670 if(BattleGround
*bg
= GetBattleGround())
17672 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
17674 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17676 // call after remove to be sure that player resurrected for correct cast
17678 CastSpell(this, 26013, true); // Deserter
17682 bool Player::CanJoinToBattleground() const
17684 // check Deserter debuff
17685 if(GetDummyAura(26013))
17691 bool Player::CanReportAfkDueToLimit()
17693 // a player can complain about 15 people per 5 minutes
17694 if(m_bgAfkReportedCount
>= 15)
17696 ++m_bgAfkReportedCount
;
17700 ///This player has been blamed to be inactive in a battleground
17701 void Player::ReportedAfkBy(Player
* reporter
)
17703 BattleGround
*bg
= GetBattleGround();
17704 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17707 // check if player has 'Idle' or 'Inactive' debuff
17708 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17710 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17711 // 3 players have to complain to apply debuff
17712 if(m_bgAfkReporter
.size() >= 3)
17714 // cast 'Idle' spell
17715 CastSpell(this, 43680, true);
17716 m_bgAfkReporter
.clear();
17721 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17723 // gamemaster in GM mode see all, including ghosts
17724 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17727 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17728 if (InBattleGround())
17730 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17735 // Live player see live player or dead player with not realized corpse
17736 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17738 return isAlive() || m_deathTimer
> 0;
17741 // Ghost see other friendly ghosts, that's for sure
17742 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17745 // Dead player see live players near own corpse
17748 Corpse
*corpse
= pl
->GetCorpse();
17751 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17752 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17757 // and not see any other
17761 bool Player::IsVisibleGloballyFor( Player
* u
) const
17766 // Always can see self
17770 // Visible units, always are visible for all players
17771 if (GetVisibility() == VISIBILITY_ON
)
17774 // GMs are visible for higher gms (or players are visible for gms)
17775 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17776 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17778 // non faction visibility non-breakable for non-GMs
17779 if (GetVisibility() == VISIBILITY_OFF
)
17782 // non-gm stealth/invisibility not hide from global player lists
17786 void Player::UpdateVisibilityOf(WorldObject
* target
)
17788 if(HaveAtClient(target
))
17790 if(!target
->isVisibleForInState(this,true))
17792 target
->DestroyForPlayer(this);
17793 m_clientGUIDs
.erase(target
->GetGUID());
17795 #ifdef MANGOS_DEBUG
17796 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17797 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17803 if(target
->isVisibleForInState(this,false))
17805 target
->SendUpdateToPlayer(this);
17806 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17807 m_clientGUIDs
.insert(target
->GetGUID());
17809 #ifdef MANGOS_DEBUG
17810 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17811 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17814 // target aura duration for caster show only if target exist at caster client
17815 // send data at target visibility change (adding to client)
17816 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17817 SendAurasForTarget((Unit
*)target
);
17819 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17820 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17826 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17828 s64
.insert(target
->GetGUID());
17832 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17834 if(!target
->IsTransport())
17835 s64
.insert(target
->GetGUID());
17839 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17841 if(HaveAtClient(target
))
17843 if(!target
->isVisibleForInState(this,true))
17845 target
->BuildOutOfRangeUpdateBlock(&data
);
17846 m_clientGUIDs
.erase(target
->GetGUID());
17848 #ifdef MANGOS_DEBUG
17849 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17850 sLog
.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),target
->GetEntry(),GetGUIDLow(),GetDistance(target
));
17856 if(target
->isVisibleForInState(this,false))
17858 visibleNow
.insert(target
);
17859 target
->BuildUpdate(data_updates
);
17860 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17861 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17863 #ifdef MANGOS_DEBUG
17864 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17865 sLog
.outDebug("Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),target
->GetEntry(),GetGUIDLow(),GetDistance(target
));
17871 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17872 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17873 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17874 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17875 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17877 void Player::InitPrimaryProffesions()
17879 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17882 void Player::SendComboPoints()
17884 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17887 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17888 data
.append(combotarget
->GetPackGUID());
17889 data
<< uint8(m_comboPoints
);
17890 GetSession()->SendPacket(&data
);
17894 void Player::AddComboPoints(Unit
* target
, int8 count
)
17899 // without combo points lost (duration checked in aura)
17900 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17902 if(target
->GetGUID() == m_comboTarget
)
17904 m_comboPoints
+= count
;
17909 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17910 target
->RemoveComboPointHolder(GetGUIDLow());
17912 m_comboTarget
= target
->GetGUID();
17913 m_comboPoints
= count
;
17915 target
->AddComboPointHolder(GetGUIDLow());
17918 if (m_comboPoints
> 5) m_comboPoints
= 5;
17919 if (m_comboPoints
< 0) m_comboPoints
= 0;
17924 void Player::ClearComboPoints()
17929 // without combopoints lost (duration checked in aura)
17930 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17936 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17937 target
->RemoveComboPointHolder(GetGUIDLow());
17942 void Player::SetGroup(Group
*group
, int8 subgroup
)
17944 if(group
== NULL
) m_group
.unlink();
17947 // never use SetGroup without a subgroup unless you specify NULL for group
17948 assert(subgroup
>= 0);
17949 m_group
.link(group
, this);
17950 m_group
.setSubGroup((uint8
)subgroup
);
17954 void Player::SendInitialPacketsBeforeAddToMap()
17956 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17957 data
<< uint32(0); // unknown, may be rest state time or experience
17958 GetSession()->SendPacket(&data
);
17961 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17962 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17963 data
<< (uint32
) m_homebindMapId
;
17964 data
<< (uint32
) m_homebindZoneId
;
17965 GetSession()->SendPacket(&data
);
17967 // SMSG_SET_PROFICIENCY
17968 // SMSG_UPDATE_AURA_DURATION
17971 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17972 for (int i
= 0; i
< 8; ++i
)
17973 data
<< uint32( GetTutorialInt(i
) );
17974 GetSession()->SendPacket(&data
);
17976 SendInitialSpells();
17978 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17979 data
<< uint32(0); // count, for(count) uint32;
17980 GetSession()->SendPacket(&data
);
17982 SendInitialActionButtons();
17983 SendInitialReputations();
17984 m_achievementMgr
.SendAllAchievementData();
17985 UpdateZone(GetZoneId());
17986 SendInitWorldStates();
17988 // SMSG_SET_AURA_SINGLE
17990 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17991 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17992 data
<< (float)0.01666667f
; // game speed
17993 GetSession()->SendPacket( &data
);
17995 data
.Initialize(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17996 data
<< uint32(0x00000000); // on blizz it increments periodically
17997 GetSession()->SendPacket(&data
);
17999 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18000 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
18001 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
18006 void Player::SendInitialPacketsAfterAddToMap()
18008 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18009 data
<< uint32(0x00000000); // on blizz it increments periodically
18010 GetSession()->SendPacket(&data
);
18012 CastSpell(this, 836, true); // LOGINEFFECT
18014 // set some aura effects that send packet to player client after add player to map
18015 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18016 // same auras state lost at far teleport, send it one more time in this case also
18017 static const AuraType auratypes
[] =
18019 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
18020 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
18021 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
18023 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
18025 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
18026 if(!auraList
.empty())
18027 auraList
.front()->ApplyModifier(true,true);
18030 if(HasAuraType(SPELL_AURA_MOD_STUN
))
18031 SetMovement(MOVE_ROOT
);
18033 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18034 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
18036 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
18037 data
.append(GetPackGUID());
18039 SendMessageToSet(&data
,true);
18042 SendAurasForTarget(this);
18043 SendEnchantmentDurations(); // must be after add to map
18044 SendItemDurations(); // must be after add to map
18047 void Player::SendUpdateToOutOfRangeGroupMembers()
18049 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
18051 if(Group
* group
= GetGroup())
18052 group
->UpdatePlayerOutOfRange(this);
18054 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18055 m_auraUpdateMask
= 0;
18056 if(Pet
*pet
= GetPet())
18057 pet
->ResetAuraUpdateMask();
18060 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18062 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18063 data
<< uint32(mapid
);
18064 data
<< uint8(reason
); // transfer abort reason
18067 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18068 case TRANSFER_ABORT_DIFFICULTY
:
18069 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18070 data
<< uint8(arg
);
18073 GetSession()->SendPacket(&data
);
18076 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
18078 // type of warning, based on the time remaining until reset
18081 type
= RAID_INSTANCE_WELCOME
;
18082 else if(time
> 900 && time
<= 3600)
18083 type
= RAID_INSTANCE_WARNING_HOURS
;
18084 else if(time
> 300 && time
<= 900)
18085 type
= RAID_INSTANCE_WARNING_MIN
;
18087 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18088 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
18089 data
<< uint32(type
);
18090 data
<< uint32(mapid
);
18091 data
<< uint32(time
);
18092 GetSession()->SendPacket(&data
);
18095 void Player::ApplyEquipCooldown( Item
* pItem
)
18097 for(int i
= 0; i
<5; ++i
)
18099 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18102 if( !spellData
.SpellId
)
18105 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18106 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18109 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18111 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18112 data
<< pItem
->GetGUID();
18113 data
<< uint32(spellData
.SpellId
);
18114 GetSession()->SendPacket(&data
);
18118 void Player::resetSpells()
18120 // not need after this call
18121 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18123 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
18124 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18127 // make full copy of map (spells removed and marked as deleted at another spell remove
18128 // and we can't use original map for safe iterative with visit each spell at loop end
18129 PlayerSpellMap smap
= GetSpellMap();
18131 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18132 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18134 learnDefaultSpells();
18135 learnQuestRewardedSpells();
18138 void Player::learnDefaultSpells()
18140 // learn default race/class spells
18141 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18142 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18144 uint32 tspell
= *itr
;
18145 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18146 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18147 addSpell(tspell
,true,true,true,false);
18148 else // but send in normal spell in game learn case
18149 learnSpell(tspell
,true);
18153 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18155 uint32 spell_id
= quest
->GetRewSpellCast();
18157 // skip quests without rewarded spell
18161 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18165 // check learned spells state
18166 bool found
= false;
18167 for(int i
=0; i
< 3; ++i
)
18169 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18176 // skip quests with not teaching spell or already known spell
18180 // prevent learn non first rank unknown profession and second specialization for same profession)
18181 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18182 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18184 // not have first rank learned (unlearned prof?)
18185 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18186 if( !HasSpell(first_spell
) )
18189 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18194 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18196 // search other specialization for same prof
18197 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18199 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18202 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18206 // compare only specializations
18207 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18210 // compare same chain spells
18211 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18214 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18215 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18221 CastSpell( this, spell_id
, true);
18224 void Player::learnQuestRewardedSpells()
18226 // learn spells received from quest completing
18227 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18229 // skip no rewarded quests
18230 if(!itr
->second
.m_rewarded
)
18233 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18237 learnQuestRewardedSpells(quest
);
18241 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18243 uint32 raceMask
= getRaceMask();
18244 uint32 classMask
= getClassMask();
18245 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18247 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18248 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18250 // Check race if set
18251 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18253 // Check class if set
18254 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18257 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18259 // need unlearn spell
18260 if (skill_value
< pAbility
->req_skill_value
)
18261 removeSpell(pAbility
->spellId
);
18263 else if (!IsInWorld())
18264 addSpell(pAbility
->spellId
,true,true,true,false);
18266 learnSpell(pAbility
->spellId
,true);
18271 void Player::SendAurasForTarget(Unit
*target
)
18273 if(target
->GetVisibleAuras()->empty()) // speedup things
18276 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18277 data
.append(target
->GetPackGUID());
18279 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18280 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18282 for(uint32 j
= 0; j
< 3; ++j
)
18284 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18286 data
<< uint8(aura
->GetAuraSlot());
18287 data
<< uint32(aura
->GetId());
18291 uint8 auraFlags
= aura
->GetAuraFlags();
18293 data
<< uint8(auraFlags
);
18295 data
<< uint8(aura
->GetAuraLevel());
18297 data
<< uint8(aura
->GetAuraCharges());
18299 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18301 data
<< uint8(0); // packed GUID of someone (caster?)
18304 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18306 data
<< uint32(aura
->GetAuraMaxDuration());
18307 data
<< uint32(aura
->GetAuraDuration());
18315 GetSession()->SendPacket(&data
);
18318 void Player::SetDailyQuestStatus( uint32 quest_id
)
18320 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18322 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18324 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18325 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18326 m_DailyQuestChanged
= true;
18332 void Player::ResetDailyQuestStatus()
18334 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18335 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18337 // DB data deleted in caller
18338 m_DailyQuestChanged
= false;
18339 m_lastDailyQuestTime
= 0;
18342 BattleGround
* Player::GetBattleGround() const
18344 if(GetBattleGroundId()==0)
18347 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
18350 bool Player::InArena() const
18352 BattleGround
*bg
= GetBattleGround();
18353 if(!bg
|| !bg
->isArena())
18359 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
18361 // get a template bg instead of running one
18362 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18366 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18372 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
18380 return 10*(queue_id
+1);
18383 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
18386 return 255; // hardcoded max level
18388 return 10*(queue_id
+2)-1;
18391 uint32
Player::GetBattleGroundQueueIdFromLevel() const
18393 uint32 level
= getLevel();
18396 else if (level
> 79)
18399 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18401 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18402 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18404 return (getLevel() - bg->GetMinLevel()) / 10;*/
18407 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18409 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18410 if(!vendor_faction
)
18413 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18414 if(rank
<= REP_NEUTRAL
)
18417 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18420 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18422 uint32 racemask
= getRaceMask();
18423 uint32 classmask
= getClassMask();
18425 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18426 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18430 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18432 // skip wrong race skills
18433 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18436 // skip wrong class skills
18437 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18446 bool Player::HasQuestForGO(int32 GOId
)
18448 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
18450 QuestStatusData qs
=i
->second
;
18451 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18453 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
18457 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18460 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18462 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18465 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18473 void Player::UpdateForQuestsGO()
18475 if(m_clientGUIDs
.empty())
18479 WorldPacket packet
;
18480 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18482 if(IS_GAMEOBJECT_GUID(*itr
))
18484 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18486 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18489 udata
.BuildPacket(&packet
);
18490 GetSession()->SendPacket(&packet
);
18493 void Player::SummonIfPossible(bool agree
)
18497 m_summon_expire
= 0;
18501 // expire and auto declined
18502 if(m_summon_expire
< time(NULL
))
18505 // stop taxi flight at summon
18508 GetMotionMaster()->MovementExpired();
18509 m_taxi
.ClearTaxiDestinations();
18512 // drop flag at summon
18513 if(BattleGround
*bg
= GetBattleGround())
18514 bg
->EventPlayerDroppedFlag(this);
18516 m_summon_expire
= 0;
18518 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18521 void Player::RemoveItemDurations( Item
*item
)
18523 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18527 m_itemDuration
.erase(itr
);
18533 void Player::AddItemDurations( Item
*item
)
18535 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18537 m_itemDuration
.push_back(item
);
18538 item
->SendTimeUpdate(this);
18542 void Player::AutoUnequipOffhandIfNeed()
18544 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18548 // need unequip for 2h-weapon without TitanGrip
18549 if (!IsTwoHandUsed())
18552 ItemPosCountVec off_dest
;
18553 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18554 if( off_msg
== EQUIP_ERR_OK
)
18556 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18557 StoreItem( off_dest
, offItem
, true );
18561 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18565 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18567 if(spellInfo
->EquippedItemClass
< 0)
18570 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18571 // for optimize check 2 used cases only
18572 switch(spellInfo
->EquippedItemClass
)
18574 case ITEM_CLASS_WEAPON
:
18576 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18577 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18578 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18582 case ITEM_CLASS_ARMOR
:
18584 // tabard not have dependent spells
18585 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18586 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18587 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18590 // shields can be equipped to offhand slot
18591 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18592 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18595 // ranged slot can have some armor subclasses
18596 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18597 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18603 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18610 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18612 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18613 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18614 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18617 // Check no reagent use mask
18618 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18619 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18620 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18621 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18627 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18629 AuraMap
& auras
= GetAuras();
18630 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18632 Aura
* aura
= itr
->second
;
18634 // skip passive (passive item dependent spells work in another way) and not self applied auras
18635 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18636 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18642 // skip if not item dependent or have alternative item
18643 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18649 // no alt item, remove aura, restart check
18650 RemoveAurasDueToSpell(aura
->GetId());
18651 itr
= auras
.begin();
18654 // currently casted spells can be dependent from item
18655 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18657 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18658 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18663 uint32
Player::GetResurrectionSpellId()
18665 // search priceless resurrection possibilities
18667 uint32 spell_id
= 0;
18668 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18669 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18671 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18672 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18674 switch((*itr
)->GetId())
18676 case 20707: spell_id
= 3026; break; // rank 1
18677 case 20762: spell_id
= 20758; break; // rank 2
18678 case 20763: spell_id
= 20759; break; // rank 3
18679 case 20764: spell_id
= 20760; break; // rank 4
18680 case 20765: spell_id
= 20761; break; // rank 5
18681 case 27239: spell_id
= 27240; break; // rank 6
18683 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18689 // Twisting Nether // prio: 2 (max)
18690 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18697 // Reincarnation (passive spell) // prio: 1
18698 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18704 // Used in triggers for check "Only to targets that grant experience or honor" req
18705 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18707 uint32 v_level
= pVictim
->getLevel();
18708 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18710 // Victim level less gray level
18711 if(v_level
<=k_grey
)
18714 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18716 if (((Creature
*)pVictim
)->isTotem() ||
18717 ((Creature
*)pVictim
)->isPet() ||
18718 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18724 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18726 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18728 // prepare data for near group iteration (PvP and !PvP cases)
18730 bool honored_kill
= false;
18732 if(Group
*pGroup
= GetGroup())
18735 uint32 sum_level
= 0;
18736 Player
* member_with_max_level
= NULL
;
18737 Player
* not_gray_member_with_max_level
= NULL
;
18739 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18741 if(member_with_max_level
)
18743 /// not get Xp in PvP or no not gray players in group
18744 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18746 /// skip in check PvP case (for speed, not used)
18747 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18748 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18749 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18751 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18753 Player
* pGroupGuy
= itr
->getSource();
18757 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18758 continue; // member (alive or dead) or his corpse at req. distance
18760 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18761 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18762 honored_kill
= true;
18764 // xp and reputation only in !PvP case
18767 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18769 // if is in dungeon then all receive full reputation at kill
18770 // rewarded any alive/dead/near_corpse group member
18771 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18773 // XP updated only for alive group member
18774 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18775 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18777 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18779 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18780 if(Pet
* pet
= pGroupGuy
->GetPet())
18781 pet
->GivePetXP(itr_xp
/2);
18784 // quest objectives updated only for alive group member or dead but with not released body
18785 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18787 // normal creature (not pet/etc) can be only in !PvP case
18788 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18789 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18795 else // if (!pGroup)
18797 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18799 // honor can be in PvP and !PvP (racial leader) cases
18800 if(RewardHonor(pVictim
,1))
18801 honored_kill
= true;
18803 // xp and reputation only in !PvP case
18806 RewardReputation(pVictim
,1);
18807 GiveXP(xp
, pVictim
);
18809 if(Pet
* pet
= GetPet())
18810 pet
->GivePetXP(xp
);
18812 // normal creature (not pet/etc) can be only in !PvP case
18813 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18814 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18817 return xp
|| honored_kill
;
18820 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18822 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18828 Corpse
* corpse
= GetCorpse();
18832 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18835 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18837 Item
* item
= GetWeaponForAttack(attType
,true);
18839 // unarmed only with base attack
18840 if(attType
!= BASE_ATTACK
&& !item
)
18843 // weapon skill or (unarmed for base attack)
18844 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18845 return GetBaseSkillValue(skill
);
18848 void Player::ResurectUsingRequestData()
18850 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18851 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18853 ResurrectPlayer(0.0f
,false);
18855 if(GetMaxHealth() > m_resurrectHealth
)
18856 SetHealth( m_resurrectHealth
);
18858 SetHealth( GetMaxHealth() );
18860 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18861 SetPower(POWER_MANA
, m_resurrectMana
);
18863 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18865 SetPower(POWER_RAGE
, 0 );
18867 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18869 SpawnCorpseBones();
18872 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18874 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18875 data
.append(target
->GetPackGUID());
18876 data
<< uint8(allowMove
);
18877 GetSession()->SendPacket(&data
);
18880 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18882 // remove new continent flight forms
18883 if( !IsAllowUseFlyMountsHere() )
18885 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18886 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18889 // Some spells applied at enter into zone (with subzones)
18892 case 2367: // Old Hillsbrad Foothills
18895 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18896 uint32 spellid
= 0;
18898 if( GetTeam() == HORDE
)
18899 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18900 // and some alliance races
18901 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18902 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
18904 if(spellid
&& !HasAura(spellid
,0) )
18905 CastSpell(this,spellid
,true);
18911 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18913 // remove auras from spells with area limitations
18914 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18916 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18917 if(GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
)!=0)
18923 // some auras applied at subzone enter
18926 // Dragonmaw Illusion
18927 case 3759: // Netherwing Ledge
18928 case 3939: // Dragonmaw Fortress
18929 case 3966: // Dragonmaw Base Camp
18930 if( GetDummyAura(40214) )
18932 if( !HasAura(40216,0) )
18933 CastSpell(this,40216,true);
18934 if( !HasAura(42016,0) )
18935 CastSpell(this,42016,true);
18938 // Dominion Over Acherus
18939 case 4281: // Acherus: The Ebon Hold
18940 case 4342: // Acherus: The Ebon Hold
18941 if( HasSpell(51721) )
18942 if( !HasAura(51721,0) )
18943 CastSpell(this,51721,true);
18945 // Mist of the Kvaldir
18946 case 4028: //Riplash Strand
18947 case 4029: //Riplash Ruins
18948 case 4106: //Garrosh's Landing
18949 case 4031: //Pal'ea
18950 CastSpell(this,54119,true);
18955 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18957 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18958 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18960 return copseReclaimDelay
[0];
18963 time_t now
= time(NULL
);
18964 // 0..2 full period
18965 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18966 return copseReclaimDelay
[count
];
18969 void Player::UpdateCorpseReclaimDelay()
18971 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18973 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18974 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18977 time_t now
= time(NULL
);
18978 if(now
< m_deathExpireTime
)
18980 // full and partly periods 1..3
18981 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18982 if(count
< MAX_DEATH_COUNT
)
18983 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18985 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18988 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18991 void Player::SendCorpseReclaimDelay(bool load
)
18993 Corpse
* corpse
= GetCorpse();
19000 if(corpse
->GetGhostTime() > m_deathExpireTime
)
19003 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
19006 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19007 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19009 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
19010 if(count
>=MAX_DEATH_COUNT
)
19011 count
= MAX_DEATH_COUNT
-1;
19016 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
19018 time_t now
= time(NULL
);
19019 if(now
>= expected_time
)
19022 delay
= expected_time
-now
;
19025 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
19027 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19028 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
19029 data
<< uint32(delay
*1000);
19030 GetSession()->SendPacket( &data
);
19033 Player
* Player::GetNextRandomRaidMember(float radius
)
19035 Group
*pGroup
= GetGroup();
19039 std::vector
<Player
*> nearMembers
;
19040 nearMembers
.reserve(pGroup
->GetMembersCount());
19042 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19044 Player
* Target
= itr
->getSource();
19046 // IsHostileTo check duel and controlled by enemy
19047 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19048 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19049 nearMembers
.push_back(Target
);
19052 if (nearMembers
.empty())
19055 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19056 return nearMembers
[randTarget
];
19059 PartyResult
Player::CanUninviteFromGroup() const
19061 const Group
* grp
= GetGroup();
19063 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19065 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19066 return PARTY_RESULT_YOU_NOT_LEADER
;
19068 if(InBattleGround())
19069 return PARTY_RESULT_INVITE_RESTRICTED
;
19071 return PARTY_RESULT_OK
;
19074 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19076 float water_z
= m
->GetWaterLevel(x
,y
);
19077 float terrain_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
19078 uint8 flag1
= m
->GetTerrainType(x
,y
);
19080 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19081 if (terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
-2) || z
> (water_z
- 2) )
19082 m_isunderwater
&= ~UNDERWATER_INWATER
;
19083 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
19084 m_isunderwater
|= UNDERWATER_INWATER
;
19086 //!in lava check, anywhere under lava level
19087 if ((terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
- 0)) && (flag1
== 0x00) && IsInWater())
19088 m_isunderwater
|= UNDERWATER_INLAVA
;
19090 m_isunderwater
&= ~UNDERWATER_INLAVA
;
19093 void Player::SetCanParry( bool value
)
19095 if(m_canParry
==value
)
19098 m_canParry
= value
;
19099 UpdateParryPercentage();
19102 void Player::SetCanBlock( bool value
)
19104 if(m_canBlock
==value
)
19107 m_canBlock
= value
;
19108 UpdateBlockPercentage();
19111 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19113 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19114 if(itr
->pos
== pos
)
19120 bool Player::isAllowUseBattleGroundObject()
19122 return ( //InBattleGround() && // in battleground - not need, check in other cases
19123 !IsMounted() && // not mounted
19124 !HasStealthAura() && // not stealthed
19125 !HasInvisibilityAura() && // not invisible
19126 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19127 isAlive() // live player
19131 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19133 uint32 level
= getLevel();
19135 if(level
> GT_MAX_LEVEL
)
19136 level
= GT_MAX_LEVEL
; // max level in this dbc
19138 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19139 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19140 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19142 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19145 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19147 if(!bsc
) // shouldn't happen
19152 if(hairstyle
!= newhairstyle
)
19153 cost
+= bsc
->cost
; // full price
19155 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19156 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19158 if(facialhair
!= newfacialhair
)
19159 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19161 return uint32(cost
);
19164 void Player::InitGlyphsForLevel()
19166 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19167 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19169 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19171 uint32 level
= getLevel();
19174 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19176 value
|= (0x01 | 0x02);
19186 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19189 void Player::EnterVehicle(Vehicle
*vehicle
)
19191 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19195 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19199 vehicle
->SetCharmerGUID(GetGUID());
19200 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19201 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19202 vehicle
->setFaction(getFaction());
19204 SetCharm(vehicle
); // charm
19205 SetFarSightGUID(vehicle
->GetGUID()); // set view
19207 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19209 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19210 GetSession()->SendPacket(&data
);
19212 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19213 data
.append(GetPackGUID());
19214 data
<< uint32(0); // counter?
19215 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19216 data
<< uint16(0); // special flags
19217 data
<< uint32(getMSTime()); // time
19218 data
<< vehicle
->GetPositionX(); // x
19219 data
<< vehicle
->GetPositionY(); // y
19220 data
<< vehicle
->GetPositionZ(); // z
19221 data
<< vehicle
->GetOrientation(); // o
19222 // transport part, TODO: load/calculate seat offsets
19223 data
<< uint64(vehicle
->GetGUID()); // transport guid
19224 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19225 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19226 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19227 data
<< float(0); // transport orientation
19228 data
<< uint32(getMSTime()); // transport time
19229 data
<< uint8(0); // seat
19230 // end of transport part
19231 data
<< uint32(0); // fall time
19232 GetSession()->SendPacket(&data
);
19234 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19235 data
<< uint64(vehicle
->GetGUID());
19236 data
<< uint32(0x00000000);
19237 data
<< uint32(0x00000000);
19238 data
<< uint32(0x00000101);
19240 for(uint32 i
= 0; i
< 10; ++i
)
19241 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19245 GetSession()->SendPacket(&data
);
19248 void Player::ExitVehicle(Vehicle
*vehicle
)
19250 vehicle
->SetCharmerGUID(0);
19251 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19252 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19253 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19256 SetFarSightGUID(0);
19258 SetClientControl(vehicle
, 0);
19260 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19261 data
.append(GetPackGUID());
19262 data
<< uint32(0); // counter?
19263 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19264 data
<< uint16(0x40); // special flags
19265 data
<< uint32(getMSTime()); // time
19266 data
<< vehicle
->GetPositionX(); // x
19267 data
<< vehicle
->GetPositionY(); // y
19268 data
<< vehicle
->GetPositionZ(); // z
19269 data
<< vehicle
->GetOrientation(); // o
19270 data
<< uint32(0); // fall time
19271 GetSession()->SendPacket(&data
);
19273 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19276 GetSession()->SendPacket(&data
);
19278 // only for flyable vehicles?
19279 CastSpell(this, 45472, true); // Parachute
19282 bool Player::HasTitle(uint32 bitIndex
)
19284 if (bitIndex
> 128)
19287 uint32 fieldIndexOffset
= bitIndex
/32;
19288 uint32 flag
= 1 << (bitIndex
%32);
19289 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19292 void Player::SetTitle(CharTitlesEntry
const* title
)
19294 uint32 fieldIndexOffset
= title
->bit_index
/32;
19295 uint32 flag
= 1 << (title
->bit_index
%32);
19296 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19299 void Player::ConvertRune(uint8 index
, uint8 newType
)
19301 SetCurrentRune(index
, newType
);
19303 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19304 data
<< uint8(index
);
19305 data
<< uint8(newType
);
19306 GetSession()->SendPacket(&data
);
19309 void Player::ResyncRunes(uint8 count
)
19311 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19312 for(uint32 i
= 0; i
< count
; ++i
)
19314 data
<< uint8(GetCurrentRune(i
)); // rune type
19315 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19317 GetSession()->SendPacket(&data
);
19320 void Player::AddRunePower(uint8 index
)
19322 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19323 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19324 GetSession()->SendPacket(&data
);
19327 void Player::InitRunes()
19329 if(getClass() != CLASS_DEATH_KNIGHT
)
19332 m_runes
= new Runes
;
19334 m_runes
->runeState
= 0;
19336 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19338 SetBaseRune(i
, i
/ 2); // init base types
19339 SetCurrentRune(i
, i
/ 2); // init current types
19340 SetRuneCooldown(i
, 0); // reset cooldowns
19341 m_runes
->SetRuneState(i
);
19344 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19345 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19348 void Player::AutoStoreLootItem(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
)
19351 loot
.FillLoot (loot_id
,store
,this);
19352 if(loot
.items
.empty ())
19354 LootItem
const* lootItem
= &loot
.items
[0];
19356 ItemPosCountVec dest
;
19357 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19358 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19359 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19360 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19361 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19362 if(msg
!= EQUIP_ERR_OK
)
19365 StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19368 uint32
Player::CalculateTalentsPoints() const
19370 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19372 if(getClass() != CLASS_DEATH_KNIGHT
)
19373 return base_talent
;
19375 uint32 talentPointsForLevel
=
19376 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19377 + m_questRewardTalentCount
;
19379 if(talentPointsForLevel
> base_talent
)
19380 talentPointsForLevel
= base_talent
;
19382 return talentPointsForLevel
;
19385 bool Player::IsAllowUseFlyMountsHere() const
19387 if (isGameMaster())
19390 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19391 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19394 void Player::learnSpellHighRank(uint32 spellid
)
19396 learnSpell(spellid
,false);
19398 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19399 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19400 learnSpellHighRank(itr
->second
);
19403 void Player::_LoadSkills()
19405 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19407 // reset skill modifiers and set correct unlearn flags
19408 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
19410 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19412 // set correct unlearn bit
19413 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19416 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19417 if(!pSkill
) continue;
19419 // enable unlearn button for primary professions only
19420 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19421 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19423 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19425 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19427 learnSkillRewardedSpells(id
, vskill
);
19430 // special settings
19431 if(getClass()==CLASS_DEATH_KNIGHT
)
19433 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19436 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19438 base_skill
= 1; // skill mast be known and then > 0 in any case
19440 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19441 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19442 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19443 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19444 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19445 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19446 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19447 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19448 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19449 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19450 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19451 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19452 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19453 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19454 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19455 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);