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
,false); // see and visible in all phases
1993 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
1994 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
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))
3945 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3946 _pb
= GetUInt32Value(PLAYER_BYTES
);
3947 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3949 uint8 race
= (uint8
)(_uf
);
3950 uint8 skin
= (uint8
)(_pb
);
3951 uint8 face
= (uint8
)(_pb
>> 8);
3952 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3953 uint8 haircolor
= (uint8
)(_pb
>> 24);
3954 uint8 facialhair
= (uint8
)(_pb2
);
3956 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3957 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3959 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3960 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3962 uint32 flags
= CORPSE_FLAG_UNK2
;
3963 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3964 flags
|= CORPSE_FLAG_HIDE_HELM
;
3965 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3966 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3967 if(InBattleGround())
3968 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3969 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3971 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3973 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3976 uint16 iIventoryType
;
3978 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3982 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3983 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3985 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3986 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3990 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3991 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3993 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3996 // register for player, but not show
3997 ObjectAccessor::Instance().AddCorpse(corpse
);
4000 void Player::SpawnCorpseBones()
4002 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4003 SaveToDB(); // prevent loading as ghost without corpse
4006 Corpse
* Player::GetCorpse() const
4008 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4011 void Player::DurabilityLossAll(double percent
, bool inventory
)
4013 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4014 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4015 DurabilityLoss(pItem
,percent
);
4019 // bags not have durability
4020 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4022 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4023 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4024 DurabilityLoss(pItem
,percent
);
4026 // keys not have durability
4027 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4029 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4030 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4031 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4032 if(Item
* pItem
= GetItemByPos( i
, j
))
4033 DurabilityLoss(pItem
,percent
);
4037 void Player::DurabilityLoss(Item
* item
, double percent
)
4042 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4047 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4049 if(pDurabilityLoss
< 1 )
4050 pDurabilityLoss
= 1;
4052 DurabilityPointsLoss(item
,pDurabilityLoss
);
4055 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4057 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4058 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4059 DurabilityPointsLoss(pItem
,points
);
4063 // bags not have durability
4064 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4066 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4067 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4068 DurabilityPointsLoss(pItem
,points
);
4070 // keys not have durability
4071 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4073 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4074 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4075 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4076 if(Item
* pItem
= GetItemByPos( i
, j
))
4077 DurabilityPointsLoss(pItem
,points
);
4081 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4083 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4084 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4085 int32 pNewDurability
= pOldDurability
- points
;
4087 if (pNewDurability
< 0)
4089 else if (pNewDurability
> pMaxDurability
)
4090 pNewDurability
= pMaxDurability
;
4092 if (pOldDurability
!= pNewDurability
)
4094 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4095 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4096 _ApplyItemMods(item
,item
->GetSlot(), false);
4098 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4100 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4101 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4102 _ApplyItemMods(item
,item
->GetSlot(), true);
4104 item
->SetState(ITEM_CHANGED
, this);
4108 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4110 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4111 DurabilityPointsLoss(pItem
,1);
4114 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4116 uint32 TotalCost
= 0;
4117 // equipped, backpack, bags itself
4118 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4119 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4121 // bank, buyback and keys not repaired
4123 // items in inventory bags
4124 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4125 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4126 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4130 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4132 Item
* item
= GetItemByPos(pos
);
4134 uint32 TotalCost
= 0;
4138 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4142 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4146 uint32 LostDurability
= maxDurability
- curDurability
;
4147 if(LostDurability
>0)
4149 ItemPrototype
const *ditemProto
= item
->GetProto();
4151 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4154 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4158 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4159 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4160 if(!dQualitymodEntry
)
4162 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4166 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4167 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4169 costs
= uint32(costs
* discountMod
);
4171 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4176 if (GetGuildId()==0)
4178 DEBUG_LOG("You are not member of a guild");
4182 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4186 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4188 DEBUG_LOG("You do not have rights to withdraw for repairs");
4192 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4194 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4198 if (pGuild
->GetGuildBankMoney() < costs
)
4200 DEBUG_LOG("There is not enough money in bank");
4204 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4207 else if (GetMoney() < costs
)
4209 DEBUG_LOG("You do not have enough money");
4213 ModifyMoney( -int32(costs
) );
4217 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4218 item
->SetState(ITEM_CHANGED
, this);
4220 // reapply mods for total broken and repaired item if equipped
4221 if(IsEquipmentPos(pos
) && !curDurability
)
4222 _ApplyItemMods(item
,pos
& 255, true);
4226 void Player::RepopAtGraveyard()
4228 // note: this can be called also when the player is alive
4229 // for example from WorldSession::HandleMovementOpcodes
4231 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4233 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4234 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4236 ResurrectPlayer(0.5f
);
4240 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4242 // Special handle for battleground maps
4243 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4245 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4246 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4248 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4250 // stop countdown until repop
4253 // if no grave found, stay at the current location
4254 // and don't show spirit healer location
4257 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4258 if(isDead()) // not send if alive, because it used in TeleportTo()
4260 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4261 data
<< ClosestGrave
->map_id
;
4262 data
<< ClosestGrave
->x
;
4263 data
<< ClosestGrave
->y
;
4264 data
<< ClosestGrave
->z
;
4265 GetSession()->SendPacket(&data
);
4270 void Player::JoinedChannel(Channel
*c
)
4272 m_channels
.push_back(c
);
4275 void Player::LeftChannel(Channel
*c
)
4277 m_channels
.remove(c
);
4280 void Player::CleanupChannels()
4282 while(!m_channels
.empty())
4284 Channel
* ch
= *m_channels
.begin();
4285 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4286 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4287 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4288 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4291 sLog
.outDebug("Player: channels cleaned up!");
4294 void Player::UpdateLocalChannels(uint32 newZone
)
4296 if(m_channels
.empty())
4299 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4303 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4307 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4309 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4313 // skip non built-in channels
4314 if(!(*i
)->IsConstant())
4317 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4321 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4325 char new_channel_name_buf
[100];
4326 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4327 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4329 if((*i
)!=new_channel
)
4331 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4333 // leave old channel
4334 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4335 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4336 LeftChannel(*i
); // remove from player's channel list
4337 cMgr
->LeftChannel(name
); // delete if empty
4340 sLog
.outDebug("Player: channels cleaned up!");
4343 void Player::LeaveLFGChannel()
4345 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4349 (*i
)->Leave(GetGUID());
4355 void Player::UpdateDefense()
4357 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4359 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4361 // update dependent from defense skill part
4362 UpdateDefenseBonusesMod();
4366 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4368 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4370 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4379 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4382 if(amount
<= -100.0f
)
4385 val
= (100.0f
+ amount
) / 100.0f
;
4386 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4390 if(!CanModifyStats())
4395 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4396 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4397 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4398 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4403 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4405 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4407 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4411 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4414 return m_auraBaseMod
[modGroup
][modType
];
4417 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4419 if(modGroup
>= BASEMOD_END
)
4421 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4425 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4428 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4431 uint32
Player::GetShieldBlockValue() const
4433 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4435 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
) * 0.5f
- 10;
4437 value
= (value
< 0) ? 0 : value
;
4439 return uint32(value
);
4442 float Player::GetMeleeCritFromAgility()
4444 uint32 level
= getLevel();
4445 uint32 pclass
= getClass();
4447 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4449 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4450 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4451 if (critBase
==NULL
|| critRatio
==NULL
)
4454 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4458 float Player::GetDodgeFromAgility()
4460 // Table for base dodge values
4461 float dodge_base
[MAX_CLASSES
] = {
4463 0.00652f
, // Paladin
4470 0.02011f
, // Warlock
4474 // Crit/agility to dodge/agility coefficient multipliers
4475 float crit_to_dodge
[MAX_CLASSES
] = {
4489 uint32 level
= getLevel();
4490 uint32 pclass
= getClass();
4492 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4494 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4495 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4496 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4499 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4500 return dodge
*100.0f
;
4503 float Player::GetSpellCritFromIntellect()
4505 uint32 level
= getLevel();
4506 uint32 pclass
= getClass();
4508 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4510 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4511 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4512 if (critBase
==NULL
|| critRatio
==NULL
)
4515 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4519 float Player::GetRatingCoefficient(CombatRating cr
) const
4521 uint32 level
= getLevel();
4523 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4525 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4527 return 1.0f
; // By default use minimum coefficient (not must be called)
4529 return Rating
->ratio
;
4532 float Player::GetRatingBonusValue(CombatRating cr
) const
4534 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4537 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4539 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4540 if (melee
>25.0f
) melee
= 25.0f
;
4541 return uint32 (melee
* damage
/100.0f
);
4544 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4546 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4547 if (ranged
>25.0f
) ranged
=25.0f
;
4548 return uint32 (ranged
* damage
/100.0f
);
4551 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4553 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4554 // In wow script resilience limited to 25%
4557 return uint32 (spell
* damage
/ 100.0f
);
4560 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4562 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4563 // Dot resilience not limited (limit it by 100%)
4564 if (spellDot
> 100.0f
)
4566 return uint32 (spellDot
* damage
/ 100.0f
);
4569 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4574 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4576 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4583 float Player::OCTRegenHPPerSpirit()
4585 uint32 level
= getLevel();
4586 uint32 pclass
= getClass();
4588 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4590 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4591 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4592 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4595 // Formula from PaperDollFrame script
4596 float spirit
= GetStat(STAT_SPIRIT
);
4597 float baseSpirit
= spirit
;
4598 if (baseSpirit
>50) baseSpirit
= 50;
4599 float moreSpirit
= spirit
- baseSpirit
;
4600 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4604 float Player::OCTRegenMPPerSpirit()
4606 uint32 level
= getLevel();
4607 uint32 pclass
= getClass();
4609 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4611 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4613 if (moreRatio
==NULL
)
4616 // Formula get from PaperDollFrame script
4617 float spirit
= GetStat(STAT_SPIRIT
);
4618 float regen
= spirit
* moreRatio
->ratio
;
4622 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4624 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4626 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4627 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4628 // stat used stored in miscValueB for this aura
4629 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4630 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4631 if ((*i
)->GetMiscValue() & (1<<cr
))
4632 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4635 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4637 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4638 float RatingChange
= 0.0f
;
4640 bool affectStats
= CanModifyStats();
4644 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4645 case CR_DEFENSE_SKILL
:
4646 UpdateDefenseBonusesMod();
4649 UpdateDodgePercentage();
4652 UpdateParryPercentage();
4655 UpdateBlockPercentage();
4658 UpdateMeleeHitChances();
4661 UpdateRangedHitChances();
4664 UpdateSpellHitChances();
4669 UpdateCritPercentage(BASE_ATTACK
);
4670 UpdateCritPercentage(OFF_ATTACK
);
4673 case CR_CRIT_RANGED
:
4675 UpdateCritPercentage(RANGED_ATTACK
);
4679 UpdateAllSpellCritChances();
4681 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4682 case CR_HIT_TAKEN_RANGED
:
4684 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4686 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4687 case CR_CRIT_TAKEN_RANGED
:
4689 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4691 case CR_HASTE_MELEE
:
4692 RatingChange
= value
/ RatingCoeffecient
;
4693 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4694 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4696 case CR_HASTE_RANGED
:
4697 RatingChange
= value
/ RatingCoeffecient
;
4698 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4700 case CR_HASTE_SPELL
:
4701 RatingChange
= value
/ RatingCoeffecient
;
4702 ApplyCastTimePercentMod(RatingChange
,apply
);
4704 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4705 case CR_WEAPON_SKILL_OFFHAND
:
4706 case CR_WEAPON_SKILL_RANGED
:
4711 UpdateExpertise(BASE_ATTACK
);
4712 UpdateExpertise(OFF_ATTACK
);
4718 void Player::SetRegularAttackTime()
4720 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4722 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4723 if(tmpitem
&& !tmpitem
->IsBroken())
4725 ItemPrototype
const *proto
= tmpitem
->GetProto();
4727 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4729 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4734 //skill+step, checking for max value
4735 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4741 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4742 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4745 if(i
>=PLAYER_MAX_SKILLS
)
4748 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4749 uint32 value
= SKILL_VALUE(data
);
4750 uint32 max
= SKILL_MAX(data
);
4752 if ((!max
) || (!value
) || (value
>= max
))
4755 if (value
*512 < max
*urand(0,512))
4757 uint32 new_value
= value
+step
;
4761 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4762 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4769 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4771 if ( SkillValue
>= GrayLevel
)
4772 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4773 if ( SkillValue
>= GreenLevel
)
4774 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4775 if ( SkillValue
>= YellowLevel
)
4776 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4777 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4780 bool Player::UpdateCraftSkill(uint32 spellid
)
4782 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4784 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4785 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4787 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4789 if(_spell_idx
->second
->skillId
)
4791 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4793 // Alchemy Discoveries here
4794 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4795 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4797 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4798 learnSpell(discoveredSpell
,false);
4801 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4803 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4804 _spell_idx
->second
->max_value
,
4805 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4806 _spell_idx
->second
->min_value
),
4813 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4815 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4817 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4819 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4822 case SKILL_HERBALISM
:
4823 case SKILL_LOCKPICKING
:
4824 case SKILL_JEWELCRAFTING
:
4825 case SKILL_INSCRIPTION
:
4826 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4827 case SKILL_SKINNING
:
4828 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4829 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4831 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4833 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4834 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4836 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4841 bool Player::UpdateFishingSkill()
4843 sLog
.outDebug("UpdateFishingSkill");
4845 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4847 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4849 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4851 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4854 // levels sync. with spell requirement for skill levels to learn
4855 // bonus abilities in sSkillLineAbilityStore
4856 // Used only to avoid scan DBC at each skill grow
4857 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4859 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4861 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4865 if(Chance
<= 0) // speedup in 0 chance case
4867 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4872 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4873 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4874 if ( i
>= PLAYER_MAX_SKILLS
)
4877 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4878 uint16 SkillValue
= SKILL_VALUE(data
);
4879 uint16 MaxValue
= SKILL_MAX(data
);
4881 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4884 int32 Roll
= irand(1,1000);
4886 if ( Roll
<= Chance
)
4888 uint32 new_value
= SkillValue
+step
;
4889 if(new_value
> MaxValue
)
4890 new_value
= MaxValue
;
4892 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4893 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
4895 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
4897 learnSkillRewardedSpells( SkillId
, new_value
);
4901 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4902 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4906 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4910 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4912 // no skill gain in pvp
4913 Unit
*pVictim
= getVictim();
4914 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4918 return; // always maximized SKILL_FERAL_COMBAT in fact
4920 if(m_form
== FORM_TREE
)
4921 return; // use weapon but not skill up
4923 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4929 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4932 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4933 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4934 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4940 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4942 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4946 UpdateAllCritPercentages();
4949 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
4951 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4952 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4953 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4954 if(moblevel
< greylevel
)
4957 if (moblevel
> plevel
+ 5)
4958 moblevel
= plevel
+ 5;
4960 uint32 lvldif
= moblevel
- greylevel
;
4964 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4968 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4971 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4972 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4975 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4977 if(roll_chance_f(chance
))
4982 UpdateWeaponSkill(attType
);
4988 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4990 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4991 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4993 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4994 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4995 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4997 if(talent
) // permanent bonus stored in high part
4998 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4999 else // temporary/item bonus stored in low part
5000 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5005 void Player::UpdateSkillsForLevel()
5007 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5008 uint32 maxSkill
= GetMaxSkillValueForLevel();
5010 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5012 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5013 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5015 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5017 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5021 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5024 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5025 uint32 max
= SKILL_MAX(data
);
5026 uint32 val
= SKILL_VALUE(data
);
5028 /// update only level dependent max skill values
5031 /// miximize skill always
5033 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5034 /// update max skill value if current max skill not maximized
5035 else if(max
!= maxconfskill
)
5036 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5041 void Player::UpdateSkillsToMaxSkillsForLevel()
5043 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5044 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5046 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5047 if( IsProfessionOrRidingSkill(pskill
))
5049 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5051 uint32 max
= SKILL_MAX(data
);
5054 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5056 if(pskill
== SKILL_DEFENSE
)
5057 UpdateDefenseBonusesMod();
5061 // This functions sets a skill line value (and adds if doesn't exist yet)
5062 // To "remove" a skill line, set it's values to zero
5063 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5069 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5070 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5072 if(i
<PLAYER_MAX_SKILLS
) //has skill
5076 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5077 learnSkillRewardedSpells(id
, currVal
);
5078 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5082 // clear skill fields
5083 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5084 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5085 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5087 // remove all spells that related to this skill
5088 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5089 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5090 if (pAbility
->skillId
==id
)
5091 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5094 else if(currVal
) //add
5096 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5097 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5099 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5102 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5105 // enable unlearn button for primary professions only
5106 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5107 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5109 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5110 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5111 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5113 // apply skill bonuses
5114 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5116 // temporary bonuses
5117 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5118 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5119 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5120 (*i
)->ApplyModifier(true);
5122 // permanent bonuses
5123 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5124 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5125 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5126 (*i
)->ApplyModifier(true);
5128 // Learn all spells for skill
5129 learnSkillRewardedSpells(id
, currVal
);
5135 bool Player::HasSkill(uint32 skill
) const
5137 if(!skill
)return false;
5138 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5140 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5148 uint16
Player::GetSkillValue(uint32 skill
) const
5153 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5155 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5157 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5159 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5160 result
+= SKILL_TEMP_BONUS(bonus
);
5161 result
+= SKILL_PERM_BONUS(bonus
);
5162 return result
< 0 ? 0 : result
;
5168 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5171 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5173 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5175 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5177 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5178 result
+= SKILL_TEMP_BONUS(bonus
);
5179 result
+= SKILL_PERM_BONUS(bonus
);
5180 return result
< 0 ? 0 : result
;
5186 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5189 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5191 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5193 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5199 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5202 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5204 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5206 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5207 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5208 return result
< 0 ? 0 : result
;
5214 uint16
Player::GetPureSkillValue(uint32 skill
) const
5217 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5219 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5221 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5227 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5232 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5234 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5236 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5243 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5248 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5250 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5252 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5259 void Player::SendInitialActionButtons()
5261 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5263 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5264 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5266 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5267 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5269 data
<< uint16(itr
->second
.action
);
5270 data
<< uint8(itr
->second
.misc
);
5271 data
<< uint8(itr
->second
.type
);
5279 GetSession()->SendPacket( &data
);
5280 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5283 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5285 if(button
>= MAX_ACTION_BUTTONS
)
5287 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5291 // check cheating with adding non-known spells to action bar
5292 if(type
==ACTION_BUTTON_SPELL
)
5294 if(!sSpellStore
.LookupEntry(action
))
5296 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5300 if(!HasSpell(action
))
5302 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5307 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5309 if (buttonItr
==m_actionButtons
.end())
5310 { // just add new button
5311 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5314 { // change state of current button
5315 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5316 buttonItr
->second
= ActionButton(action
,type
,misc
);
5317 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5320 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5323 void Player::removeActionButton(uint8 button
)
5325 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5326 if (buttonItr
==m_actionButtons
.end())
5329 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5330 m_actionButtons
.erase(buttonItr
); // new and not saved
5332 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5334 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5337 void Player::SetDontMove(bool dontMove
)
5339 m_dontMove
= dontMove
;
5342 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5344 // prevent crash when a bad coord is sent by the client
5345 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5347 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5353 const float old_x
= GetPositionX();
5354 const float old_y
= GetPositionY();
5355 const float old_z
= GetPositionZ();
5356 const float old_r
= GetOrientation();
5358 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5360 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5361 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5363 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5365 // move and update visible state if need
5366 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5368 // reread after Map::Relocation
5375 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5376 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5379 // code block for underwater state update
5380 UpdateUnderwaterState(m
, x
, y
, z
);
5382 CheckExploreSystem();
5387 void Player::SaveRecallPosition()
5389 m_recallMap
= GetMapId();
5390 m_recallX
= GetPositionX();
5391 m_recallY
= GetPositionY();
5392 m_recallZ
= GetPositionZ();
5393 m_recallO
= GetOrientation();
5396 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5398 GetMap()->MessageBroadcast(this, data
, self
);
5401 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5403 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5406 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5408 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5411 void Player::SendDirectMessage(WorldPacket
*data
)
5413 GetSession()->SendPacket(data
);
5416 void Player::CheckExploreSystem()
5424 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5425 if(areaFlag
==0xffff)
5427 int offset
= areaFlag
/ 32;
5431 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
);
5435 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5436 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5438 if( !(currFields
& val
) )
5440 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5442 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5444 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5447 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5449 else if(p
->area_level
> 0)
5451 uint32 area
= p
->ID
;
5452 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5454 SendExplorationExperience(area
,0);
5458 int32 diff
= int32(getLevel()) - p
->area_level
;
5462 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5466 int32 exploration_percent
= (100-((diff
-5)*5));
5467 if (exploration_percent
> 100)
5468 exploration_percent
= 100;
5469 else if (exploration_percent
< 0)
5470 exploration_percent
= 0;
5472 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5476 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5480 SendExplorationExperience(area
,XP
);
5482 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5487 uint32
Player::TeamForRace(uint8 race
)
5489 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5492 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5496 switch(rEntry
->TeamID
)
5498 case 7: return ALLIANCE
;
5499 case 1: return HORDE
;
5502 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5506 uint32
Player::getFactionForRace(uint8 race
)
5508 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5511 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5515 return rEntry
->FactionID
;
5518 void Player::setFactionForRace(uint8 race
)
5520 m_team
= TeamForRace(race
);
5521 setFaction( getFactionForRace(race
) );
5524 void Player::UpdateReputation() const
5526 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5528 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5530 SendFactionState(&(itr
->second
));
5534 void Player::SendFactionState(FactionState
const* faction
) const
5536 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5538 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5539 data
<< (float) 0; // unk 2.4.0
5540 data
<< (uint8
) 0; // wotlk 8634
5541 data
<< (uint32
) 1; // count
5543 data
<< (uint32
) faction
->ReputationListID
;
5544 data
<< (uint32
) faction
->Standing
;
5546 GetSession()->SendPacket(&data
);
5550 void Player::SendInitialReputations()
5552 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5553 data
<< uint32 (0x00000080);
5557 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5559 // fill in absent fields
5560 for (; a
!= itr
->first
; a
++)
5562 data
<< uint8 (0x00);
5563 data
<< uint32 (0x00000000);
5566 // fill in encountered data
5567 data
<< uint8 (itr
->second
.Flags
);
5568 data
<< uint32 (itr
->second
.Standing
);
5573 // fill in absent fields
5574 for (; a
!= 128; a
++)
5576 data
<< uint8 (0x00);
5577 data
<< uint32 (0x00000000);
5580 GetSession()->SendPacket(&data
);
5583 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5585 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5586 if (itr
!= m_factions
.end())
5587 return &itr
->second
;
5592 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5594 // not allow declare war to own faction
5595 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5599 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5603 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5605 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5607 faction
->Changed
= true;
5610 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5612 // always invisible or hidden faction can't be inactive
5613 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5617 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5621 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5623 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5625 faction
->Changed
= true;
5628 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5630 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5632 if(!factionTemplateEntry
)
5635 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5638 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5640 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5644 if(factionEntry
->reputationListID
< 0)
5647 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5648 if (itr
== m_factions
.end())
5651 SetFactionVisible(&itr
->second
);
5654 void Player::SetFactionVisible(FactionState
* faction
)
5656 // always invisible or hidden faction can't be make visible
5657 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5661 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5664 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5665 faction
->Changed
= true;
5667 if(!m_session
->PlayerLoading())
5669 // make faction visible in reputation list at client
5670 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5671 data
<< faction
->ReputationListID
;
5672 GetSession()->SendPacket(&data
);
5676 void Player::SetInitialFactions()
5678 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5680 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5682 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5684 FactionState newFaction
;
5685 newFaction
.ID
= factionEntry
->ID
;
5686 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5687 newFaction
.Standing
= 0;
5688 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5689 newFaction
.Changed
= true;
5691 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5696 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5701 uint32 raceMask
= getRaceMask();
5702 uint32 classMask
= getClassMask();
5703 for (int i
=0; i
< 4; i
++)
5705 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5706 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5707 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5708 return factionEntry
->ReputationFlags
[i
];
5713 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5718 uint32 raceMask
= getRaceMask();
5719 uint32 classMask
= getClassMask();
5720 for (int i
=0; i
< 4; i
++)
5722 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5723 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5724 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5725 return factionEntry
->BaseRepValue
[i
];
5728 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5732 int32
Player::GetReputation(uint32 faction_id
) const
5734 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5738 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5742 return GetReputation(factionEntry
);
5745 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5747 // Faction without recorded reputation. Just ignore.
5751 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5752 if (itr
!= m_factions
.end())
5753 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5758 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5760 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5762 return MIN_REPUTATION_RANK
;
5764 return GetReputationRank(factionEntry
);
5767 ReputationRank
Player::ReputationToRank(int32 standing
) const
5769 int32 Limit
= Reputation_Cap
+ 1;
5770 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5772 Limit
-= ReputationRank_Length
[i
];
5773 if (standing
>= Limit
)
5774 return ReputationRank(i
);
5776 return MIN_REPUTATION_RANK
;
5779 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5781 int32 Reputation
= GetReputation(factionEntry
);
5782 return ReputationToRank(Reputation
);
5785 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5787 int32 Reputation
= GetBaseReputation(factionEntry
);
5788 return ReputationToRank(Reputation
);
5791 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5793 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5795 if(!factionTemplateEntry
)
5797 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5801 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5803 // Faction without recorded reputation. Just ignore.
5807 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5810 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5812 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5816 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5818 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5819 if(factionEntryCalc
)
5820 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5825 return ModifyOneFactionReputation(factionEntry
, standing
);
5828 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5830 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5831 if (itr
!= m_factions
.end())
5833 int32 BaseRep
= GetBaseReputation(factionEntry
);
5834 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5836 if (new_rep
> Reputation_Cap
)
5837 new_rep
= Reputation_Cap
;
5839 if (new_rep
< Reputation_Bottom
)
5840 new_rep
= Reputation_Bottom
;
5842 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5843 SetFactionAtWar(&itr
->second
,true);
5845 itr
->second
.Standing
= new_rep
- BaseRep
;
5846 itr
->second
.Changed
= true;
5848 SetFactionVisible(&itr
->second
);
5850 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5852 if(uint32 questid
= GetQuestSlotQuestId(i
))
5854 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5855 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5857 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5858 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5860 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5861 if ( CanCompleteQuest( questid
) )
5862 CompleteQuest( questid
);
5864 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5866 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5867 IncompleteQuest( questid
);
5872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5873 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5874 SendFactionState(&(itr
->second
));
5881 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5883 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5885 if(!factionTemplateEntry
)
5887 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5891 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5893 // Faction without recorded reputation. Just ignore.
5897 return SetFactionReputation(factionEntry
, standing
);
5900 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5902 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5906 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5908 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5909 if(factionEntryCalc
)
5910 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5915 return SetOneFactionReputation(factionEntry
, standing
);
5918 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5920 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5921 if (itr
!= m_factions
.end())
5923 if (standing
> Reputation_Cap
)
5924 standing
= Reputation_Cap
;
5926 if (standing
< Reputation_Bottom
)
5927 standing
= Reputation_Bottom
;
5929 int32 BaseRep
= GetBaseReputation(factionEntry
);
5930 itr
->second
.Standing
= standing
- BaseRep
;
5931 itr
->second
.Changed
= true;
5933 SetFactionVisible(&itr
->second
);
5935 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5936 SetFactionAtWar(&itr
->second
,true);
5938 SendFactionState(&(itr
->second
));
5939 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5940 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5946 //Calculate total reputation percent player gain with quest/creature level
5947 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5949 // for grey creature kill received 20%, in other case 100.
5950 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5952 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5954 percent
+= rep
> 0 ? repMod
: -repMod
;
5959 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5962 //Calculates how many reputation points player gains in victim's enemy factions
5963 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5965 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5968 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5973 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5975 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5976 donerep1
= int32(donerep1
*rate
);
5977 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5978 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5979 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5980 ModifyFactionReputation(factionEntry1
, donerep1
);
5982 // Wiki: Team factions value divided by 2
5983 if(Rep
->is_teamaward1
)
5985 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5986 if(team1_factionEntry
)
5987 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5991 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5993 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5994 donerep2
= int32(donerep2
*rate
);
5995 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5996 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5997 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5998 ModifyFactionReputation(factionEntry2
, donerep2
);
6000 // Wiki: Team factions value divided by 2
6001 if(Rep
->is_teamaward2
)
6003 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6004 if(team2_factionEntry
)
6005 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
6010 //Calculate how many reputation points player gain with the quest
6011 void Player::RewardReputation(Quest
const *pQuest
)
6013 // quest reputation reward/loss
6014 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6016 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
6018 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
6019 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
6021 ModifyFactionReputation(factionEntry
, rep
);
6025 // TODO: implement reputation spillover
6028 void Player::UpdateArenaFields(void)
6030 /* arena calcs go here */
6033 void Player::UpdateHonorFields()
6035 /// called when rewarding honor and at each save
6036 uint64 now
= time(NULL
);
6037 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
6039 if(m_lastHonorUpdateTime
< today
)
6041 uint64 yesterday
= today
- DAY
;
6043 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6045 // update yesterday's contribution
6046 if(m_lastHonorUpdateTime
>= yesterday
)
6048 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6050 // this is the first update today, reset today's contribution
6051 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6052 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6056 // no honor/kills yesterday or today, reset
6057 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6058 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6062 m_lastHonorUpdateTime
= now
;
6065 ///Calculate the amount of honor gained based on the victim
6066 ///and the size of the group for which the honor is divided
6067 ///An exact honor value can also be given (overriding the calcs)
6068 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6070 // do not reward honor in arenas, but enable onkill spellproc
6073 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6076 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6082 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6083 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6086 uint64 victim_guid
= 0;
6087 uint32 victim_rank
= 0;
6089 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6090 UpdateHonorFields();
6094 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6097 victim_guid
= uVictim
->GetGUID();
6099 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6101 Player
*pVictim
= (Player
*)uVictim
;
6103 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6106 float f
= 1; //need for total kills (?? need more info)
6108 uint32 k_level
= getLevel();
6109 uint32 v_level
= pVictim
->getLevel();
6112 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6114 // [1..14] Alliance honor titles and player name
6115 // [15..28] Horde honor titles and player name
6116 // [29..38] Other title and player name
6118 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6119 // Get Killer titles, CharTitlesEntry::bit_index
6121 // title[1..14] -> rank[5..18]
6122 // title[15..28] -> rank[5..18]
6123 // title[other] -> 0
6124 if (victim_title
== 0)
6125 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6126 else if (victim_title
< 15)
6127 victim_rank
= victim_title
+ 4;
6128 else if (victim_title
< 29)
6129 victim_rank
= victim_title
- 14 + 4;
6131 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6134 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6139 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6141 int32 v_rank
=1; //need more info
6143 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6144 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6146 // count the number of playerkills in one day
6147 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6148 // and those in a lifetime
6149 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6153 Creature
*cVictim
= (Creature
*)uVictim
;
6155 if (!cVictim
->isRacialLeader())
6158 honor
= 100; // ??? need more info
6159 victim_rank
= 19; // HK: Leader
6163 if (uVictim
!= NULL
)
6165 honor
*= sWorld
.getRate(RATE_HONOR
);
6170 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6173 // honor - for show honor points in log
6174 // victim_guid - for show victim name in log
6175 // victim_rank [1..4] HK: <dishonored rank>
6176 // victim_rank [5..19] HK: <alliance\horde rank>
6177 // victim_rank [0,20+] HK: <>
6178 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6179 data
<< (uint32
) honor
;
6180 data
<< (uint64
) victim_guid
;
6181 data
<< (uint32
) victim_rank
;
6183 GetSession()->SendPacket(&data
);
6186 ModifyHonorPoints(int32(honor
));
6188 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6192 void Player::ModifyHonorPoints( int32 value
)
6196 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6197 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6199 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6202 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6205 void Player::ModifyArenaPoints( int32 value
)
6209 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6210 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6212 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6215 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6218 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6220 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6224 uint32 id
= result
->Fetch()[0].GetUInt32();
6229 uint32
Player::GetRankFromDB(uint64 guid
)
6231 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6234 uint32 v
= result
->Fetch()[0].GetUInt32();
6242 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6244 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
);
6248 uint32 id
= (*result
)[0].GetUInt32();
6253 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6255 uint32 guidLow
= GUID_LOPART(guid
);
6256 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6259 Field
* fields
= result
->Fetch();
6260 uint32 zone
= fields
[0].GetUInt32();
6265 // stored zone is zero, use generic and slow zone detection
6266 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6269 fields
= result
->Fetch();
6270 uint32 map
= fields
[0].GetUInt32();
6271 float posx
= fields
[1].GetFloat();
6272 float posy
= fields
[2].GetFloat();
6273 float posz
= fields
[3].GetFloat();
6276 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6278 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6284 void Player::UpdateArea(uint32 newArea
)
6286 // FFA_PVP flags are area and not zone id dependent
6287 // so apply them accordingly
6288 m_areaUpdateId
= newArea
;
6290 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6292 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6295 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6299 // remove ffa flag only if not ffapvp realm
6300 // removal in sanctuaries and capitals is handled in zone update
6301 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6302 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6305 UpdateAreaDependentAuras(newArea
);
6308 void Player::UpdateZone(uint32 newZone
)
6310 m_zoneUpdateId
= newZone
;
6311 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6313 // zone changed, so area changed as well, update it
6314 UpdateArea(GetAreaId());
6316 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6320 if (sWorld
.getConfig(CONFIG_WEATHER
))
6322 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6325 wth
->SendWeatherUpdateToPlayer(this);
6329 if(!sWorld
.AddWeather(zone
->ID
))
6331 // send fine weather packet to remove old zone's weather
6332 Weather::SendFineWeatherUpdateToPlayer(this);
6337 pvpInfo
.inHostileArea
=
6338 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6339 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6340 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6341 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6343 if(pvpInfo
.inHostileArea
) // in hostile area
6345 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6346 UpdatePvP(true, true);
6348 else // in friendly area
6350 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6351 pvpInfo
.endTimer
= time(0); // start toggle-off
6354 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6356 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6357 if(sWorld
.IsFFAPvPRealm())
6358 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6362 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6365 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6367 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6368 SetRestType(REST_TYPE_IN_CITY
);
6369 InnEnter(time(0),GetMapId(),0,0,0);
6371 if(sWorld
.IsFFAPvPRealm())
6372 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6374 else // anywhere else
6376 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6378 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6380 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6382 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6383 SetRestType(REST_TYPE_NO
);
6385 if(sWorld
.IsFFAPvPRealm())
6386 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6389 else // not in tavern (leave city then)
6391 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6392 SetRestType(REST_TYPE_NO
);
6394 // Set player to FFA PVP when not in rested environment.
6395 if(sWorld
.IsFFAPvPRealm())
6396 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6401 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6402 // if player resurrected at teleport this will be applied in resurrect code
6404 DestroyZoneLimitedItem( true, newZone
);
6406 // recent client version not send leave/join channel packets for built-in local channels
6407 UpdateLocalChannels( newZone
);
6411 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6413 UpdateZoneDependentAuras(newZone
);
6416 //If players are too far way of duel flag... then player loose the duel
6417 void Player::CheckDuelDistance(time_t currTime
)
6422 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6423 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6427 if(duel
->outOfBound
== 0)
6429 if(!IsWithinDistInMap(obj
, 50))
6431 duel
->outOfBound
= currTime
;
6433 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6434 GetSession()->SendPacket(&data
);
6439 if(IsWithinDistInMap(obj
, 40))
6441 duel
->outOfBound
= 0;
6443 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6444 GetSession()->SendPacket(&data
);
6446 else if(currTime
>= (duel
->outOfBound
+10))
6448 DuelComplete(DUEL_FLED
);
6453 void Player::DuelComplete(DuelCompleteType type
)
6455 // duel not requested
6459 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6460 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6461 GetSession()->SendPacket(&data
);
6462 duel
->opponent
->GetSession()->SendPacket(&data
);
6464 if(type
!= DUEL_INTERUPTED
)
6466 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6467 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6468 data
<< duel
->opponent
->GetName();
6470 SendMessageToSet(&data
,true);
6473 // cool-down duel spell
6474 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6481 GetSession()->SendPacket(&data);
6482 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6483 data<<duel->opponent->GetGUID();
6487 duel->opponent->GetSession()->SendPacket(&data);*/
6489 //Remove Duel Flag object
6490 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6492 duel
->initiator
->RemoveGameObject(obj
,true);
6495 std::vector
<uint32
> auras2remove
;
6496 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6497 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6499 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6500 auras2remove
.push_back(i
->second
->GetId());
6503 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6504 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6506 auras2remove
.clear();
6507 AuraMap
const& auras
= GetAuras();
6508 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6510 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6511 auras2remove
.push_back(i
->second
->GetId());
6513 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6514 RemoveAurasDueToSpell(auras2remove
[i
]);
6516 // cleanup combo points
6517 if(GetComboTarget()==duel
->opponent
->GetGUID())
6519 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6522 if(duel
->opponent
->GetComboTarget()==GetGUID())
6523 duel
->opponent
->ClearComboPoints();
6524 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6525 duel
->opponent
->ClearComboPoints();
6528 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6529 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6530 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6531 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6533 delete duel
->opponent
->duel
;
6534 duel
->opponent
->duel
= NULL
;
6539 //---------------------------------------------------------//
6541 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6543 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6546 // not apply/remove mods for broken item
6547 if(item
->IsBroken())
6550 ItemPrototype
const *proto
= item
->GetProto();
6555 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6557 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6558 if(attacktype
< MAX_ATTACK
)
6559 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6561 _ApplyItemBonuses(proto
,slot
,apply
);
6563 if( slot
==EQUIPMENT_SLOT_RANGED
)
6564 _ApplyAmmoBonuses();
6566 ApplyItemEquipSpell(item
,apply
);
6567 ApplyEnchantment(item
, apply
);
6569 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6570 CorrectMetaGemEnchants(slot
, apply
);
6572 sLog
.outDebug("_ApplyItemMods complete.");
6575 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6577 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6580 for (int i
= 0; i
< 10; i
++)
6582 uint32 statType
= 0;
6585 if(proto
->ScalingStatDistribution
)
6587 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6589 statType
= ssd
->StatMod
[i
];
6591 if(uint32 modifier
= ssd
->Modifier
[i
])
6593 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6594 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6596 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6597 val
= (multiplier
* modifier
) / 10000;
6604 statType
= proto
->ItemStat
[i
].ItemStatType
;
6605 val
= proto
->ItemStat
[i
].ItemStatValue
;
6614 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6616 case ITEM_MOD_HEALTH
: // modify HP
6617 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6619 case ITEM_MOD_AGILITY
: // modify agility
6620 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6621 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6623 case ITEM_MOD_STRENGTH
: //modify strength
6624 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6625 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6627 case ITEM_MOD_INTELLECT
: //modify intellect
6628 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6629 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6631 case ITEM_MOD_SPIRIT
: //modify spirit
6632 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6633 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6635 case ITEM_MOD_STAMINA
: //modify stamina
6636 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6637 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6639 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6640 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6642 case ITEM_MOD_DODGE_RATING
:
6643 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6645 case ITEM_MOD_PARRY_RATING
:
6646 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6648 case ITEM_MOD_BLOCK_RATING
:
6649 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6651 case ITEM_MOD_HIT_MELEE_RATING
:
6652 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6654 case ITEM_MOD_HIT_RANGED_RATING
:
6655 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6657 case ITEM_MOD_HIT_SPELL_RATING
:
6658 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6660 case ITEM_MOD_CRIT_MELEE_RATING
:
6661 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6663 case ITEM_MOD_CRIT_RANGED_RATING
:
6664 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6666 case ITEM_MOD_CRIT_SPELL_RATING
:
6667 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6669 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6670 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6672 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6673 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6675 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6676 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6678 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6679 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6681 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6682 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6684 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6685 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6687 case ITEM_MOD_HASTE_MELEE_RATING
:
6688 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6690 case ITEM_MOD_HASTE_RANGED_RATING
:
6691 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6693 case ITEM_MOD_HASTE_SPELL_RATING
:
6694 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6696 case ITEM_MOD_HIT_RATING
:
6697 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6698 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6699 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6701 case ITEM_MOD_CRIT_RATING
:
6702 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6703 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6704 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6706 case ITEM_MOD_HIT_TAKEN_RATING
:
6707 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6708 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6709 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6711 case ITEM_MOD_CRIT_TAKEN_RATING
:
6712 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6713 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6714 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6716 case ITEM_MOD_RESILIENCE_RATING
:
6717 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6718 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6719 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6721 case ITEM_MOD_HASTE_RATING
:
6722 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6723 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6724 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6726 case ITEM_MOD_EXPERTISE_RATING
:
6727 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6729 case ITEM_MOD_ATTACK_POWER
:
6730 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6732 case ITEM_MOD_RANGED_ATTACK_POWER
:
6733 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6735 case ITEM_MOD_FERAL_ATTACK_POWER
:
6736 ApplyFeralAPBonus(int32(val
), apply
);
6738 case ITEM_MOD_SPELL_HEALING_DONE
:
6739 ApplySpellHealingBonus(int32(val
), apply
);
6741 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6742 ApplySpellDamageBonus(int32(val
), apply
);
6744 case ITEM_MOD_MANA_REGENERATION
:
6745 ApplyManaRegenBonus(int32(val
), apply
);
6747 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6748 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6750 case ITEM_MOD_SPELL_POWER
:
6751 ApplySpellHealingBonus(int32(val
), apply
);
6752 ApplySpellDamageBonus(int32(val
), apply
);
6758 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6761 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6764 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6767 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6769 if (proto
->NatureRes
)
6770 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6772 if (proto
->FrostRes
)
6773 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6775 if (proto
->ShadowRes
)
6776 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6778 if (proto
->ArcaneRes
)
6779 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6781 WeaponAttackType attType
= BASE_ATTACK
;
6782 float damage
= 0.0f
;
6784 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6785 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6786 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6788 attType
= RANGED_ATTACK
;
6790 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6792 attType
= OFF_ATTACK
;
6795 if (proto
->Damage
[0].DamageMin
> 0 )
6797 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6798 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6799 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6802 if (proto
->Damage
[0].DamageMax
> 0 )
6804 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6805 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6808 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6813 if(slot
== EQUIPMENT_SLOT_RANGED
)
6814 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6815 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6816 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6817 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6818 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6821 if(CanModifyStats() && (damage
|| proto
->Delay
))
6822 UpdateDamagePhysical(attType
);
6825 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6827 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6828 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6829 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6831 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6832 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6833 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6835 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6836 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6837 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6840 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6842 // generic not weapon specific case processes in aura code
6843 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6846 BaseModGroup mod
= BASEMOD_END
;
6849 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6850 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6851 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6855 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6857 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6861 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6863 // ignore spell mods for not wands
6864 Modifier
const* modifier
= aura
->GetModifier();
6865 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6868 // generic not weapon specific case processes in aura code
6869 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6872 UnitMods unitMod
= UNIT_MOD_END
;
6875 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6876 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6877 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6881 UnitModifierType unitModType
= TOTAL_VALUE
;
6882 switch(modifier
->m_auraname
)
6884 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6885 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6889 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6891 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6895 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6900 ItemPrototype
const *proto
= item
->GetProto();
6904 for (int i
= 0; i
< 5; i
++)
6906 _Spell
const& spellData
= proto
->Spells
[i
];
6909 if(!spellData
.SpellId
)
6912 // wrong triggering type
6913 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6916 // check if it is valid spell
6917 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6921 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6925 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6929 // Cannot be used in this stance/form
6930 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6933 if(form_change
) // check aura active state from other form
6936 for (int k
=0; k
< 3; ++k
)
6938 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6939 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6941 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6951 if(found
) // and skip re-cast already active aura at form change
6955 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6957 CastSpell(this,spellInfo
,true,item
);
6961 if(form_change
) // check aura compatibility
6963 // Cannot be used in this stance/form
6964 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6965 return; // and remove only not compatible at form change
6969 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6971 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6975 void Player::UpdateEquipSpellsAtFormChange()
6977 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6979 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6981 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6982 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6986 // item set bonuses not dependent from item broken state
6987 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6989 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6993 for(uint32 y
=0;y
<8; ++y
)
6995 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6999 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7000 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7005 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
7007 if(!item
|| item
->IsBroken())
7010 ItemPrototype
const *proto
= item
->GetProto();
7014 if (!Target
|| Target
== this )
7017 for (int i
= 0; i
< 5; i
++)
7019 _Spell
const& spellData
= proto
->Spells
[i
];
7022 if(!spellData
.SpellId
)
7025 // wrong triggering type
7026 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7029 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7032 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7036 // not allow proc extra attack spell at extra attack
7037 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7040 float chance
= spellInfo
->procChance
;
7042 if(spellData
.SpellPPMRate
)
7044 uint32 WeaponSpeed
= GetAttackTime(attType
);
7045 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7047 else if(chance
> 100.0f
)
7049 chance
= GetWeaponProcChance();
7052 if (roll_chance_f(chance
))
7053 CastSpell(Target
, spellInfo
->Id
, true, item
);
7056 // item combat enchantments
7057 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7059 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7060 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7061 if(!pEnchant
) continue;
7062 for (int s
=0;s
<3;s
++)
7064 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7067 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7070 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7074 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7075 if (roll_chance_f(chance
))
7077 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7078 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7080 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7086 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7088 ItemPrototype
const* proto
= item
->GetProto();
7089 // special learning case
7090 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7092 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7093 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7095 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7098 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7099 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7103 Spell
*spell
= new Spell(this, spellInfo
, false);
7104 spell
->m_CastItem
= item
;
7105 spell
->m_cast_count
= cast_count
; //set count of casts
7106 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7107 spell
->prepare(&targets
);
7111 // use triggered flag only for items with many spell casts and for not first cast
7114 // item spells casted at use
7115 for(int i
= 0; i
< 5; ++i
)
7117 _Spell
const& spellData
= proto
->Spells
[i
];
7120 if(!spellData
.SpellId
)
7123 // wrong triggering type
7124 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7127 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7130 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7134 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7135 spell
->m_CastItem
= item
;
7136 spell
->m_cast_count
= cast_count
; // set count of casts
7137 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7138 spell
->prepare(&targets
);
7143 // Item enchantments spells casted at use
7144 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7146 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7147 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7148 if(!pEnchant
) continue;
7149 for (int s
=0;s
<3;s
++)
7151 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7154 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7157 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7161 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7162 spell
->m_CastItem
= item
;
7163 spell
->m_cast_count
= cast_count
; // set count of casts
7164 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7165 spell
->prepare(&targets
);
7172 void Player::_RemoveAllItemMods()
7174 sLog
.outDebug("_RemoveAllItemMods start.");
7176 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7180 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7184 // item set bonuses not dependent from item broken state
7186 RemoveItemsSetItem(this,proto
);
7188 if(m_items
[i
]->IsBroken())
7191 ApplyItemEquipSpell(m_items
[i
],false);
7192 ApplyEnchantment(m_items
[i
], false);
7196 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7200 if(m_items
[i
]->IsBroken())
7202 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7206 uint32 attacktype
= Player::GetAttackBySlot(i
);
7207 if(attacktype
< MAX_ATTACK
)
7208 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7210 _ApplyItemBonuses(proto
,i
, false);
7212 if( i
== EQUIPMENT_SLOT_RANGED
)
7213 _ApplyAmmoBonuses();
7217 sLog
.outDebug("_RemoveAllItemMods complete.");
7220 void Player::_ApplyAllItemMods()
7222 sLog
.outDebug("_ApplyAllItemMods start.");
7224 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7228 if(m_items
[i
]->IsBroken())
7231 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7235 uint32 attacktype
= Player::GetAttackBySlot(i
);
7236 if(attacktype
< MAX_ATTACK
)
7237 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7239 _ApplyItemBonuses(proto
,i
, true);
7241 if( i
== EQUIPMENT_SLOT_RANGED
)
7242 _ApplyAmmoBonuses();
7246 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7250 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7254 // item set bonuses not dependent from item broken state
7256 AddItemsSetItem(this,m_items
[i
]);
7258 if(m_items
[i
]->IsBroken())
7261 ApplyItemEquipSpell(m_items
[i
],true);
7262 ApplyEnchantment(m_items
[i
], true);
7266 sLog
.outDebug("_ApplyAllItemMods complete.");
7269 void Player::_ApplyAmmoBonuses()
7272 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7276 float currentAmmoDPS
;
7278 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7279 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7280 currentAmmoDPS
= 0.0f
;
7282 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7284 if(currentAmmoDPS
== GetAmmoDPS())
7287 m_ammoDPS
= currentAmmoDPS
;
7289 if(CanModifyStats())
7290 UpdateDamagePhysical(RANGED_ATTACK
);
7293 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7298 // check ranged weapon
7299 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7300 if(!weapon
|| weapon
->IsBroken() )
7303 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7304 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7307 // check ammo ws. weapon compatibility
7308 switch(weapon_proto
->SubClass
)
7310 case ITEM_SUBCLASS_WEAPON_BOW
:
7311 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7312 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7315 case ITEM_SUBCLASS_WEAPON_GUN
:
7316 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7326 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7327 Called by remove insignia spell effect */
7328 void Player::RemovedInsignia(Player
* looterPlr
)
7330 if (!GetBattleGroundId())
7333 // If not released spirit, do it !
7334 if(m_deathTimer
> 0)
7341 Corpse
*corpse
= GetCorpse();
7345 // We have to convert player corpse to bones, not to be able to resurrect there
7346 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7347 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7351 // Now we must make bones lootable, and send player loot
7352 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7354 // We store the level of our player in the gold field
7355 // We retrieve this information at Player::SendLoot()
7356 bones
->loot
.gold
= getLevel();
7357 bones
->lootRecipient
= looterPlr
;
7358 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7367 void Player::SendLootRelease( uint64 guid
)
7369 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7370 data
<< uint64(guid
) << uint8(1);
7371 SendDirectMessage( &data
);
7374 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7377 PermissionTypes permission
= ALL_PERMISSION
;
7379 sLog
.outDebug("Player::SendLoot");
7380 if (IS_GAMEOBJECT_GUID(guid
))
7382 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7384 ObjectAccessor::GetGameObject(*this, guid
);
7386 // not check distance for GO in case owned GO (fishing bobber case, for example)
7387 // And permit out of range GO with no owner in case fishing hole
7388 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7390 SendLootRelease(guid
);
7396 if(go
->getLootState() == GO_READY
)
7398 uint32 lootid
= go
->GetLootId();
7402 sLog
.outDebug(" if(lootid)");
7404 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7407 if(loot_type
== LOOT_FISHING
)
7408 go
->getFishLoot(loot
);
7410 go
->SetLootState(GO_ACTIVATED
);
7413 else if (IS_ITEM_GUID(guid
))
7415 Item
*item
= GetItemByGuid( guid
);
7419 SendLootRelease(guid
);
7423 if(loot_type
== LOOT_DISENCHANTING
)
7427 if(!item
->m_lootGenerated
)
7429 item
->m_lootGenerated
= true;
7431 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7434 else if(loot_type
== LOOT_PROSPECTING
)
7438 if(!item
->m_lootGenerated
)
7440 item
->m_lootGenerated
= true;
7442 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7445 else if(loot_type
== LOOT_MILLING
)
7449 if(!item
->m_lootGenerated
)
7451 item
->m_lootGenerated
= true;
7453 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this);
7460 if(!item
->m_lootGenerated
)
7462 item
->m_lootGenerated
= true;
7464 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7466 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7470 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7472 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7474 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7476 SendLootRelease(guid
);
7480 loot
= &bones
->loot
;
7482 if (!bones
->lootForBody
)
7484 bones
->lootForBody
= true;
7485 uint32 pLevel
= bones
->loot
.gold
;
7486 bones
->loot
.clear();
7487 // It may need a better formula
7488 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7489 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7492 if (bones
->lootRecipient
!= this)
7493 permission
= NONE_PERMISSION
;
7497 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7499 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7500 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7502 SendLootRelease(guid
);
7506 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7508 SendLootRelease(guid
);
7512 loot
= &creature
->loot
;
7514 if(loot_type
== LOOT_PICKPOCKETING
)
7516 if ( !creature
->lootForPickPocketed
)
7518 creature
->lootForPickPocketed
= true;
7521 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7522 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7524 // Generate extra money for pick pocket loot
7525 const uint32 a
= urand(0, creature
->getLevel()/2);
7526 const uint32 b
= urand(0, getLevel()/2);
7527 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7532 // the player whose group may loot the corpse
7533 Player
*recipient
= creature
->GetLootRecipient();
7536 creature
->SetLootRecipient(this);
7540 if (creature
->lootForPickPocketed
)
7542 creature
->lootForPickPocketed
= false;
7546 if(!creature
->lootForBody
)
7548 creature
->lootForBody
= true;
7551 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7552 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7554 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7556 if(Group
* group
= recipient
->GetGroup())
7558 group
->UpdateLooterGuid(creature
,true);
7560 switch (group
->GetLootMethod())
7563 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7564 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7566 case NEED_BEFORE_GREED
:
7567 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7570 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7578 // possible only if creature->lootForBody && loot->empty() at spell cast check
7579 if (loot_type
== LOOT_SKINNING
)
7582 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7584 // set group rights only for loot_type != LOOT_SKINNING
7587 if(Group
* group
= GetGroup())
7589 if( group
== recipient
->GetGroup() )
7591 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7592 permission
= ALL_PERMISSION
;
7593 else if(group
->GetLooterGuid() == GetGUID())
7595 if(group
->GetLootMethod() == MASTER_LOOT
)
7596 permission
= MASTER_PERMISSION
;
7598 permission
= ALL_PERMISSION
;
7601 permission
= GROUP_PERMISSION
;
7604 permission
= NONE_PERMISSION
;
7606 else if(recipient
== this)
7607 permission
= ALL_PERMISSION
;
7609 permission
= NONE_PERMISSION
;
7616 QuestItemList
*q_list
= 0;
7617 if (permission
!= NONE_PERMISSION
)
7619 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7620 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7621 if (itr
== lootPlayerQuestItems
.end())
7622 q_list
= loot
->FillQuestLoot(this);
7624 q_list
= itr
->second
;
7627 QuestItemList
*ffa_list
= 0;
7628 if (permission
!= NONE_PERMISSION
)
7630 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7631 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7632 if (itr
== lootPlayerFFAItems
.end())
7633 ffa_list
= loot
->FillFFALoot(this);
7635 ffa_list
= itr
->second
;
7638 QuestItemList
*conditional_list
= 0;
7639 if (permission
!= NONE_PERMISSION
)
7641 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7642 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7643 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7644 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7646 conditional_list
= itr
->second
;
7649 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7650 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7651 loot_type
= LOOT_SKINNING
;
7653 if(loot_type
== LOOT_FISHINGHOLE
)
7654 loot_type
= LOOT_FISHING
;
7656 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7658 data
<< uint64(guid
);
7659 data
<< uint8(loot_type
);
7660 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7662 SendDirectMessage(&data
);
7664 // add 'this' player as one of the players that are looting 'loot'
7665 if (permission
!= NONE_PERMISSION
)
7666 loot
->AddLooter(GetGUID());
7668 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7669 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7672 void Player::SendNotifyLootMoneyRemoved()
7674 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7675 GetSession()->SendPacket( &data
);
7678 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7680 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7681 data
<< uint8(lootSlot
);
7682 GetSession()->SendPacket( &data
);
7685 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7687 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7690 GetSession()->SendPacket(&data
);
7693 void Player::SendInitWorldStates()
7695 // data depends on zoneid/mapid...
7696 BattleGround
* bg
= GetBattleGround();
7697 uint16 NumberOfFields
= 0;
7698 uint32 mapid
= GetMapId();
7699 uint32 zoneid
= GetZoneId();
7700 uint32 areaid
= GetAreaId();
7701 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7702 // may be exist better way to do this...
7725 NumberOfFields
= 41;
7728 NumberOfFields
= 15;
7731 NumberOfFields
= 83;
7734 NumberOfFields
= 16;
7738 NumberOfFields
= 40;
7741 NumberOfFields
= 27;
7744 NumberOfFields
= 39;
7747 NumberOfFields
= 38;
7750 NumberOfFields
= 37;
7755 NumberOfFields
= 11;
7758 NumberOfFields
= 11;
7761 NumberOfFields
= 12;
7765 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7766 data
<< uint32(mapid
); // mapid
7767 data
<< uint32(zoneid
); // zone id
7768 data
<< uint32(areaid
); // area id, new 2.1.0
7769 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7770 data
<< uint32(0x8d8) << uint32(0x0); // 1
7771 data
<< uint32(0x8d7) << uint32(0x0); // 2
7772 data
<< uint32(0x8d6) << uint32(0x0); // 3
7773 data
<< uint32(0x8d5) << uint32(0x0); // 4
7774 data
<< uint32(0x8d4) << uint32(0x0); // 5
7775 data
<< uint32(0x8d3) << uint32(0x0); // 6
7776 // 7 1 - Arena season in progress, 0 - end of season
7777 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7778 // 8 Arena season id
7779 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7780 if(mapid
== 530) // Outland
7782 data
<< uint32(0x9bf) << uint32(0x0); // 7
7783 data
<< uint32(0x9bd) << uint32(0xF); // 8
7784 data
<< uint32(0x9bb) << uint32(0xF); // 9
7799 data
<< uint32(0x7ae) << uint32(0x1); // 7
7800 data
<< uint32(0x532) << uint32(0x1); // 8
7801 data
<< uint32(0x531) << uint32(0x0); // 9
7802 data
<< uint32(0x52e) << uint32(0x0); // 10
7803 data
<< uint32(0x571) << uint32(0x0); // 11
7804 data
<< uint32(0x570) << uint32(0x0); // 12
7805 data
<< uint32(0x567) << uint32(0x1); // 13
7806 data
<< uint32(0x566) << uint32(0x1); // 14
7807 data
<< uint32(0x550) << uint32(0x1); // 15
7808 data
<< uint32(0x544) << uint32(0x0); // 16
7809 data
<< uint32(0x536) << uint32(0x0); // 17
7810 data
<< uint32(0x535) << uint32(0x1); // 18
7811 data
<< uint32(0x518) << uint32(0x0); // 19
7812 data
<< uint32(0x517) << uint32(0x0); // 20
7813 data
<< uint32(0x574) << uint32(0x0); // 21
7814 data
<< uint32(0x573) << uint32(0x0); // 22
7815 data
<< uint32(0x572) << uint32(0x0); // 23
7816 data
<< uint32(0x56f) << uint32(0x0); // 24
7817 data
<< uint32(0x56e) << uint32(0x0); // 25
7818 data
<< uint32(0x56d) << uint32(0x0); // 26
7819 data
<< uint32(0x56c) << uint32(0x0); // 27
7820 data
<< uint32(0x56b) << uint32(0x0); // 28
7821 data
<< uint32(0x56a) << uint32(0x1); // 29
7822 data
<< uint32(0x569) << uint32(0x1); // 30
7823 data
<< uint32(0x568) << uint32(0x1); // 13
7824 data
<< uint32(0x565) << uint32(0x0); // 32
7825 data
<< uint32(0x564) << uint32(0x0); // 33
7826 data
<< uint32(0x563) << uint32(0x0); // 34
7827 data
<< uint32(0x562) << uint32(0x0); // 35
7828 data
<< uint32(0x561) << uint32(0x0); // 36
7829 data
<< uint32(0x560) << uint32(0x0); // 37
7830 data
<< uint32(0x55f) << uint32(0x0); // 38
7831 data
<< uint32(0x55e) << uint32(0x0); // 39
7832 data
<< uint32(0x55d) << uint32(0x0); // 40
7833 data
<< uint32(0x3c6) << uint32(0x4); // 41
7834 data
<< uint32(0x3c4) << uint32(0x6); // 42
7835 data
<< uint32(0x3c2) << uint32(0x4); // 43
7836 data
<< uint32(0x516) << uint32(0x1); // 44
7837 data
<< uint32(0x515) << uint32(0x0); // 45
7838 data
<< uint32(0x3b6) << uint32(0x6); // 46
7839 data
<< uint32(0x55c) << uint32(0x0); // 47
7840 data
<< uint32(0x55b) << uint32(0x0); // 48
7841 data
<< uint32(0x55a) << uint32(0x0); // 49
7842 data
<< uint32(0x559) << uint32(0x0); // 50
7843 data
<< uint32(0x558) << uint32(0x0); // 51
7844 data
<< uint32(0x557) << uint32(0x0); // 52
7845 data
<< uint32(0x556) << uint32(0x0); // 53
7846 data
<< uint32(0x555) << uint32(0x0); // 54
7847 data
<< uint32(0x554) << uint32(0x1); // 55
7848 data
<< uint32(0x553) << uint32(0x1); // 56
7849 data
<< uint32(0x552) << uint32(0x1); // 57
7850 data
<< uint32(0x551) << uint32(0x1); // 58
7851 data
<< uint32(0x54f) << uint32(0x0); // 59
7852 data
<< uint32(0x54e) << uint32(0x0); // 60
7853 data
<< uint32(0x54d) << uint32(0x1); // 61
7854 data
<< uint32(0x54c) << uint32(0x0); // 62
7855 data
<< uint32(0x54b) << uint32(0x0); // 63
7856 data
<< uint32(0x545) << uint32(0x0); // 64
7857 data
<< uint32(0x543) << uint32(0x1); // 65
7858 data
<< uint32(0x542) << uint32(0x0); // 66
7859 data
<< uint32(0x540) << uint32(0x0); // 67
7860 data
<< uint32(0x53f) << uint32(0x0); // 68
7861 data
<< uint32(0x53e) << uint32(0x0); // 69
7862 data
<< uint32(0x53d) << uint32(0x0); // 70
7863 data
<< uint32(0x53c) << uint32(0x0); // 71
7864 data
<< uint32(0x53b) << uint32(0x0); // 72
7865 data
<< uint32(0x53a) << uint32(0x1); // 73
7866 data
<< uint32(0x539) << uint32(0x0); // 74
7867 data
<< uint32(0x538) << uint32(0x0); // 75
7868 data
<< uint32(0x537) << uint32(0x0); // 76
7869 data
<< uint32(0x534) << uint32(0x0); // 77
7870 data
<< uint32(0x533) << uint32(0x0); // 78
7871 data
<< uint32(0x530) << uint32(0x0); // 79
7872 data
<< uint32(0x52f) << uint32(0x0); // 80
7873 data
<< uint32(0x52d) << uint32(0x1); // 81
7876 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7877 bg
->FillInitialWorldStates(data
);
7880 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7881 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7882 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7883 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7884 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7885 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7886 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7887 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7891 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7892 bg
->FillInitialWorldStates(data
);
7895 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7896 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7897 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7898 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7899 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7900 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7901 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7902 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7903 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7904 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7905 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7906 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7907 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7908 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7909 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7910 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7911 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7912 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7913 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7914 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7915 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7916 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7917 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7918 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7919 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7920 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7921 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7922 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7923 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7924 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7925 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7926 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7930 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7931 bg
->FillInitialWorldStates(data
);
7934 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7935 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7936 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7937 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7938 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7939 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7940 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7941 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7942 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7943 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7944 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7945 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7946 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7947 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7948 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7949 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7950 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7951 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7952 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7953 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7954 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7955 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7956 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7957 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7958 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7959 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7960 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7961 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7962 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7963 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7964 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7965 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7966 // and some more ... unknown
7969 case 3483: // Hellfire Peninsula
7970 data
<< uint32(0x9ba) << uint32(0x1); // 10
7971 data
<< uint32(0x9b9) << uint32(0x1); // 11
7972 data
<< uint32(0x9b5) << uint32(0x0); // 12
7973 data
<< uint32(0x9b4) << uint32(0x1); // 13
7974 data
<< uint32(0x9b3) << uint32(0x0); // 14
7975 data
<< uint32(0x9b2) << uint32(0x0); // 15
7976 data
<< uint32(0x9b1) << uint32(0x1); // 16
7977 data
<< uint32(0x9b0) << uint32(0x0); // 17
7978 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7979 data
<< uint32(0x9ac) << uint32(0x0); // 19
7980 data
<< uint32(0x9a8) << uint32(0x0); // 20
7981 data
<< uint32(0x9a7) << uint32(0x0); // 21
7982 data
<< uint32(0x9a6) << uint32(0x1); // 22
7984 case 3519: // Terokkar Forest
7985 data
<< uint32(0xa41) << uint32(0x0); // 10
7986 data
<< uint32(0xa40) << uint32(0x14); // 11
7987 data
<< uint32(0xa3f) << uint32(0x0); // 12
7988 data
<< uint32(0xa3e) << uint32(0x0); // 13
7989 data
<< uint32(0xa3d) << uint32(0x5); // 14
7990 data
<< uint32(0xa3c) << uint32(0x0); // 15
7991 data
<< uint32(0xa87) << uint32(0x0); // 16
7992 data
<< uint32(0xa86) << uint32(0x0); // 17
7993 data
<< uint32(0xa85) << uint32(0x0); // 18
7994 data
<< uint32(0xa84) << uint32(0x0); // 19
7995 data
<< uint32(0xa83) << uint32(0x0); // 20
7996 data
<< uint32(0xa82) << uint32(0x0); // 21
7997 data
<< uint32(0xa81) << uint32(0x0); // 22
7998 data
<< uint32(0xa80) << uint32(0x0); // 23
7999 data
<< uint32(0xa7e) << uint32(0x0); // 24
8000 data
<< uint32(0xa7d) << uint32(0x0); // 25
8001 data
<< uint32(0xa7c) << uint32(0x0); // 26
8002 data
<< uint32(0xa7b) << uint32(0x0); // 27
8003 data
<< uint32(0xa7a) << uint32(0x0); // 28
8004 data
<< uint32(0xa79) << uint32(0x0); // 29
8005 data
<< uint32(0x9d0) << uint32(0x5); // 30
8006 data
<< uint32(0x9ce) << uint32(0x0); // 31
8007 data
<< uint32(0x9cd) << uint32(0x0); // 32
8008 data
<< uint32(0x9cc) << uint32(0x0); // 33
8009 data
<< uint32(0xa88) << uint32(0x0); // 34
8010 data
<< uint32(0xad0) << uint32(0x0); // 35
8011 data
<< uint32(0xacf) << uint32(0x1); // 36
8013 case 3521: // Zangarmarsh
8014 data
<< uint32(0x9e1) << uint32(0x0); // 10
8015 data
<< uint32(0x9e0) << uint32(0x0); // 11
8016 data
<< uint32(0x9df) << uint32(0x0); // 12
8017 data
<< uint32(0xa5d) << uint32(0x1); // 13
8018 data
<< uint32(0xa5c) << uint32(0x0); // 14
8019 data
<< uint32(0xa5b) << uint32(0x1); // 15
8020 data
<< uint32(0xa5a) << uint32(0x0); // 16
8021 data
<< uint32(0xa59) << uint32(0x1); // 17
8022 data
<< uint32(0xa58) << uint32(0x0); // 18
8023 data
<< uint32(0xa57) << uint32(0x0); // 19
8024 data
<< uint32(0xa56) << uint32(0x0); // 20
8025 data
<< uint32(0xa55) << uint32(0x1); // 21
8026 data
<< uint32(0xa54) << uint32(0x0); // 22
8027 data
<< uint32(0x9e7) << uint32(0x0); // 23
8028 data
<< uint32(0x9e6) << uint32(0x0); // 24
8029 data
<< uint32(0x9e5) << uint32(0x0); // 25
8030 data
<< uint32(0xa00) << uint32(0x0); // 26
8031 data
<< uint32(0x9ff) << uint32(0x1); // 27
8032 data
<< uint32(0x9fe) << uint32(0x0); // 28
8033 data
<< uint32(0x9fd) << uint32(0x0); // 29
8034 data
<< uint32(0x9fc) << uint32(0x1); // 30
8035 data
<< uint32(0x9fb) << uint32(0x0); // 31
8036 data
<< uint32(0xa62) << uint32(0x0); // 32
8037 data
<< uint32(0xa61) << uint32(0x1); // 33
8038 data
<< uint32(0xa60) << uint32(0x1); // 34
8039 data
<< uint32(0xa5f) << uint32(0x0); // 35
8041 case 3698: // Nagrand Arena
8042 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8043 bg
->FillInitialWorldStates(data
);
8046 data
<< uint32(0xa0f) << uint32(0x0); // 7
8047 data
<< uint32(0xa10) << uint32(0x0); // 8
8048 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8051 case 3702: // Blade's Edge Arena
8052 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8053 bg
->FillInitialWorldStates(data
);
8056 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8057 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8058 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8061 case 3968: // Ruins of Lordaeron
8062 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8063 bg
->FillInitialWorldStates(data
);
8066 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8067 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8068 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8071 case 3703: // Shattrath City
8074 data
<< uint32(0x914) << uint32(0x0); // 7
8075 data
<< uint32(0x913) << uint32(0x0); // 8
8076 data
<< uint32(0x912) << uint32(0x0); // 9
8077 data
<< uint32(0x915) << uint32(0x0); // 10
8080 GetSession()->SendPacket(&data
);
8083 uint32
Player::GetXPRestBonus(uint32 xp
)
8085 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8087 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8090 SetRestBonus( GetRestBonus() - rested_bonus
);
8092 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8093 return rested_bonus
;
8096 void Player::SetBindPoint(uint64 guid
)
8098 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8099 data
<< uint64(guid
);
8100 GetSession()->SendPacket( &data
);
8103 void Player::SendTalentWipeConfirm(uint64 guid
)
8105 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8106 data
<< uint64(guid
);
8107 data
<< uint32(resetTalentsCost());
8108 GetSession()->SendPacket( &data
);
8111 void Player::SendPetSkillWipeConfirm()
8113 Pet
* pet
= GetPet();
8116 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8117 data
<< pet
->GetGUID();
8118 data
<< uint32(pet
->resetTalentsCost());
8119 GetSession()->SendPacket( &data
);
8122 /*********************************************************/
8123 /*** STORAGE SYSTEM ***/
8124 /*********************************************************/
8126 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8131 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8133 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8137 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8138 else if(charges
<= 1)
8140 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8141 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8146 void Player::SetSheath( uint32 sheathed
)
8150 case SHEATH_STATE_UNARMED
: // no prepared weapon
8151 SetVirtualItemSlot(0,NULL
);
8152 SetVirtualItemSlot(1,NULL
);
8153 SetVirtualItemSlot(2,NULL
);
8155 case SHEATH_STATE_MELEE
: // prepared melee weapon
8157 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8158 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8159 SetVirtualItemSlot(2,NULL
);
8161 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8162 SetVirtualItemSlot(0,NULL
);
8163 SetVirtualItemSlot(1,NULL
);
8164 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8167 SetVirtualItemSlot(0,NULL
);
8168 SetVirtualItemSlot(1,NULL
);
8169 SetVirtualItemSlot(2,NULL
);
8172 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
8175 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8177 uint8 pClass
= getClass();
8180 slots
[0] = NULL_SLOT
;
8181 slots
[1] = NULL_SLOT
;
8182 slots
[2] = NULL_SLOT
;
8183 slots
[3] = NULL_SLOT
;
8184 switch( proto
->InventoryType
)
8187 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8190 slots
[0] = EQUIPMENT_SLOT_NECK
;
8192 case INVTYPE_SHOULDERS
:
8193 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8196 slots
[0] = EQUIPMENT_SLOT_BODY
;
8199 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8202 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8205 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8208 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8211 slots
[0] = EQUIPMENT_SLOT_FEET
;
8213 case INVTYPE_WRISTS
:
8214 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8217 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8219 case INVTYPE_FINGER
:
8220 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8221 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8223 case INVTYPE_TRINKET
:
8224 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8225 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8228 slots
[0] = EQUIPMENT_SLOT_BACK
;
8230 case INVTYPE_WEAPON
:
8232 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8234 // suggest offhand slot only if know dual wielding
8235 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8237 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8240 case INVTYPE_SHIELD
:
8241 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8243 case INVTYPE_RANGED
:
8244 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8246 case INVTYPE_2HWEAPON
:
8247 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8248 if (CanDualWield() && CanTitanGrip())
8249 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8251 case INVTYPE_TABARD
:
8252 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8254 case INVTYPE_WEAPONMAINHAND
:
8255 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8257 case INVTYPE_WEAPONOFFHAND
:
8258 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8260 case INVTYPE_HOLDABLE
:
8261 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8263 case INVTYPE_THROWN
:
8264 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8266 case INVTYPE_RANGEDRIGHT
:
8267 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8270 slots
[0] = INVENTORY_SLOT_BAG_1
;
8271 slots
[1] = INVENTORY_SLOT_BAG_2
;
8272 slots
[2] = INVENTORY_SLOT_BAG_3
;
8273 slots
[3] = INVENTORY_SLOT_BAG_4
;
8277 switch(proto
->SubClass
)
8279 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8280 if (pClass
== CLASS_PALADIN
)
8281 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8283 case ITEM_SUBCLASS_ARMOR_IDOL
:
8284 if (pClass
== CLASS_DRUID
)
8285 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8287 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8288 if (pClass
== CLASS_SHAMAN
)
8289 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8291 case ITEM_SUBCLASS_ARMOR_MISC
:
8292 if (pClass
== CLASS_WARLOCK
)
8293 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8295 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8296 if (pClass
== CLASS_DEATH_KNIGHT
)
8297 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8306 if( slot
!= NULL_SLOT
)
8308 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8310 for (int i
= 0; i
< 4; i
++)
8312 if ( slots
[i
] == slot
)
8319 // search free slot at first
8320 for (int i
= 0; i
< 4; i
++)
8322 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8324 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8325 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8330 // if not found free and can swap return first appropriate from used
8331 for (int i
= 0; i
< 4; i
++)
8333 if ( slots
[i
] != NULL_SLOT
&& swap
)
8342 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8345 uint32 tempcount
= 0;
8347 uint8 res
= EQUIP_ERR_OK
;
8349 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8351 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8352 if( pItem
&& pItem
->GetEntry() == item
)
8354 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8355 if(ires
==EQUIP_ERR_OK
)
8357 tempcount
+= pItem
->GetCount();
8358 if( tempcount
>= count
)
8359 return EQUIP_ERR_OK
;
8365 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8367 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8368 if( pItem
&& pItem
->GetEntry() == item
)
8370 tempcount
+= pItem
->GetCount();
8371 if( tempcount
>= count
)
8372 return EQUIP_ERR_OK
;
8375 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8377 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8378 if( pItem
&& pItem
->GetEntry() == item
)
8380 tempcount
+= pItem
->GetCount();
8381 if( tempcount
>= count
)
8382 return EQUIP_ERR_OK
;
8386 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8388 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8391 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8393 pItem
= GetItemByPos( i
, j
);
8394 if( pItem
&& pItem
->GetEntry() == item
)
8396 tempcount
+= pItem
->GetCount();
8397 if( tempcount
>= count
)
8398 return EQUIP_ERR_OK
;
8404 // not found req. item count and have unequippable items
8408 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8411 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8413 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8414 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8415 count
+= pItem
->GetCount();
8417 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8419 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8420 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8421 count
+= pItem
->GetCount();
8423 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8425 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8427 count
+= pBag
->GetItemCount(item
,skipItem
);
8430 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8432 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8434 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8435 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8436 count
+= pItem
->GetGemCountWithID(item
);
8442 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8444 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8445 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8446 count
+= pItem
->GetCount();
8448 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8450 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8452 count
+= pBag
->GetItemCount(item
,skipItem
);
8455 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8457 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8459 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8460 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8461 count
+= pItem
->GetGemCountWithID(item
);
8469 Item
* Player::GetItemByGuid( uint64 guid
) const
8471 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8473 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8474 if( pItem
&& pItem
->GetGUID() == guid
)
8477 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8479 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8480 if( pItem
&& pItem
->GetGUID() == guid
)
8484 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8486 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8489 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8491 Item
* pItem
= pBag
->GetItemByPos( j
);
8492 if( pItem
&& pItem
->GetGUID() == guid
)
8497 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8499 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8502 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8504 Item
* pItem
= pBag
->GetItemByPos( j
);
8505 if( pItem
&& pItem
->GetGUID() == guid
)
8514 Item
* Player::GetItemByPos( uint16 pos
) const
8516 uint8 bag
= pos
>> 8;
8517 uint8 slot
= pos
& 255;
8518 return GetItemByPos( bag
, slot
);
8521 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8523 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8524 return m_items
[slot
];
8525 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8526 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8528 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8530 return pBag
->GetItemByPos(slot
);
8535 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8540 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8541 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8542 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8543 default: return NULL
;
8546 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8547 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8553 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8559 Item
* Player::GetShield(bool useable
) const
8561 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8562 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8568 if( item
->IsBroken())
8574 uint32
Player::GetAttackBySlot( uint8 slot
)
8578 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8579 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8580 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8581 default: return MAX_ATTACK
;
8585 bool Player::HasBankBagSlot( uint8 slot
) const
8587 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8588 if( slot
< maxslot
)
8593 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8595 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8597 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8599 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8601 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8606 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8608 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8610 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8615 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8617 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8619 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8621 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8626 bool Player::IsBagPos( uint16 pos
)
8628 uint8 bag
= pos
>> 8;
8629 uint8 slot
= pos
& 255;
8630 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8632 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8637 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8643 if (bag
== INVENTORY_SLOT_BAG_0
)
8645 // any post selected
8646 if (slot
== NULL_SLOT
)
8650 if (slot
< EQUIPMENT_SLOT_END
)
8654 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8658 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8662 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8666 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8670 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8676 // bag content slots
8677 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8679 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8683 // any post selected
8684 if (slot
== NULL_SLOT
)
8687 return slot
< pBag
->GetBagSize();
8690 // bank bag content slots
8691 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8693 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8697 // any post selected
8698 if (slot
== NULL_SLOT
)
8701 return slot
< pBag
->GetBagSize();
8709 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8711 uint32 tempcount
= 0;
8712 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8714 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8715 if( pItem
&& pItem
->GetEntry() == item
)
8717 tempcount
+= pItem
->GetCount();
8718 if( tempcount
>= count
)
8722 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8724 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8725 if( pItem
&& pItem
->GetEntry() == item
)
8727 tempcount
+= pItem
->GetCount();
8728 if( tempcount
>= count
)
8732 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8734 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8736 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8738 Item
* pItem
= GetItemByPos( i
, j
);
8739 if( pItem
&& pItem
->GetEntry() == item
)
8741 tempcount
+= pItem
->GetCount();
8742 if( tempcount
>= count
)
8751 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8753 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8754 if( pItem
&& pItem
->GetEntry() == item
)
8756 tempcount
+= pItem
->GetCount();
8757 if( tempcount
>= count
)
8761 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8763 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8765 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8767 Item
* pItem
= GetItemByPos( i
, j
);
8768 if( pItem
&& pItem
->GetEntry() == item
)
8770 tempcount
+= pItem
->GetCount();
8771 if( tempcount
>= count
)
8782 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8785 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8787 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8788 if( pItem
&& pItem
->GetEntry() == item
)
8792 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8793 if (pProto
&& pProto
->GemProperties
)
8795 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8797 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8798 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8800 if (pItem
->GetGemCountWithID(item
) > 0 )
8809 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8811 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8815 *no_space_count
= count
;
8816 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8820 if(pProto
->MaxCount
<= 0)
8821 return EQUIP_ERR_OK
;
8823 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8825 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8828 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8829 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8832 return EQUIP_ERR_OK
;
8835 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8838 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8840 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8841 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8844 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8846 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8847 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8850 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8852 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8854 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8856 pItem
= GetItemByPos( i
, j
);
8857 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8865 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8867 Item
* pItem2
= GetItemByPos( bag
, slot
);
8869 // ignore move item (this slot will be empty at move)
8870 if(pItem2
==pSrcItem
)
8875 // empty specific slot - check item fit to slot
8876 if( !pItem2
|| swap
)
8878 if( bag
== INVENTORY_SLOT_BAG_0
)
8881 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8882 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8884 // vanitypet case (not use, vanity pets stored as spells)
8885 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8886 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8888 // currencytoken case (disabled until proper implement)
8889 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8890 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8892 // guestbag case (disabled until proper implement)
8893 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8894 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8897 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8898 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8902 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8904 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8906 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8908 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8910 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8911 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8914 // non empty stack with space
8915 need_space
= pProto
->GetMaxStackSize();
8917 // non empty slot, check item type
8921 if(pItem2
->GetEntry() != pProto
->ItemId
)
8922 return EQUIP_ERR_ITEM_CANT_STACK
;
8925 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8926 return EQUIP_ERR_ITEM_CANT_STACK
;
8928 // free stack space or infinity
8929 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8932 if(need_space
> count
)
8935 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8936 if(!newPosition
.isContainedIn(dest
))
8938 dest
.push_back(newPosition
);
8939 count
-= need_space
;
8941 return EQUIP_ERR_OK
;
8944 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
8946 // skip specific bag already processed in first called _CanStoreItem_InBag
8948 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8950 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8952 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8954 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8956 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8958 // specialized bag mode or non-specilized
8959 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8960 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8962 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8963 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8965 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8967 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8971 Item
* pItem2
= GetItemByPos( bag
, j
);
8973 // ignore move item (this slot will be empty at move)
8974 if(pItem2
==pSrcItem
)
8977 // if merge skip empty, if !merge skip non-empty
8978 if((pItem2
!=NULL
)!=merge
)
8983 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8985 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8986 if(need_space
> count
)
8989 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8990 if(!newPosition
.isContainedIn(dest
))
8992 dest
.push_back(newPosition
);
8993 count
-= need_space
;
8996 return EQUIP_ERR_OK
;
9002 uint32 need_space
= pProto
->GetMaxStackSize();
9003 if(need_space
> count
)
9006 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9007 if(!newPosition
.isContainedIn(dest
))
9009 dest
.push_back(newPosition
);
9010 count
-= need_space
;
9013 return EQUIP_ERR_OK
;
9017 return EQUIP_ERR_OK
;
9020 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
9022 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
9024 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9025 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9028 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9030 // ignore move item (this slot will be empty at move)
9031 if(pItem2
==pSrcItem
)
9034 // if merge skip empty, if !merge skip non-empty
9035 if((pItem2
!=NULL
)!=merge
)
9040 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9042 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9043 if(need_space
> count
)
9045 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9046 if(!newPosition
.isContainedIn(dest
))
9048 dest
.push_back(newPosition
);
9049 count
-= need_space
;
9052 return EQUIP_ERR_OK
;
9058 uint32 need_space
= pProto
->GetMaxStackSize();
9059 if(need_space
> count
)
9062 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9063 if(!newPosition
.isContainedIn(dest
))
9065 dest
.push_back(newPosition
);
9066 count
-= need_space
;
9069 return EQUIP_ERR_OK
;
9073 return EQUIP_ERR_OK
;
9076 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9078 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9080 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
9084 *no_space_count
= count
;
9085 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9088 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
9091 *no_space_count
= count
;
9092 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9095 // check count of items (skip for auto move for same player from bank)
9096 uint32 no_similar_count
= 0; // can't store this amount similar items
9097 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9098 if(res
!=EQUIP_ERR_OK
)
9100 if(count
==no_similar_count
)
9103 *no_space_count
= no_similar_count
;
9106 count
-= no_similar_count
;
9110 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9112 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9113 if(res
!=EQUIP_ERR_OK
)
9116 *no_space_count
= count
+ no_similar_count
;
9122 if(no_similar_count
==0)
9123 return EQUIP_ERR_OK
;
9126 *no_space_count
= count
+ no_similar_count
;
9127 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9131 // not specific slot or have space for partly store only in specific slot
9134 if( bag
!= NULL_BAG
)
9136 // search stack in bag for merge to
9137 if( pProto
->Stackable
!= 1 )
9139 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9141 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9142 if(res
!=EQUIP_ERR_OK
)
9145 *no_space_count
= count
+ no_similar_count
;
9151 if(no_similar_count
==0)
9152 return EQUIP_ERR_OK
;
9155 *no_space_count
= count
+ no_similar_count
;
9156 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9159 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9160 if(res
!=EQUIP_ERR_OK
)
9163 *no_space_count
= count
+ no_similar_count
;
9169 if(no_similar_count
==0)
9170 return EQUIP_ERR_OK
;
9173 *no_space_count
= count
+ no_similar_count
;
9174 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9177 else // equipped bag
9179 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9180 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9181 if(res
!=EQUIP_ERR_OK
)
9182 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9184 if(res
!=EQUIP_ERR_OK
)
9187 *no_space_count
= count
+ no_similar_count
;
9193 if(no_similar_count
==0)
9194 return EQUIP_ERR_OK
;
9197 *no_space_count
= count
+ no_similar_count
;
9198 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9203 // search free slot in bag for place to
9204 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9206 // search free slot - keyring case
9207 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9209 uint32 keyringSize
= GetMaxKeyringSize();
9210 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9211 if(res
!=EQUIP_ERR_OK
)
9214 *no_space_count
= count
+ no_similar_count
;
9220 if(no_similar_count
==0)
9221 return EQUIP_ERR_OK
;
9224 *no_space_count
= count
+ no_similar_count
;
9225 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9229 // Vanity pet case skipped as not used
9231 /* until proper implementation
9232 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9234 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9235 if(res!=EQUIP_ERR_OK)
9238 *no_space_count = count + no_similar_count;
9244 if(no_similar_count==0)
9245 return EQUIP_ERR_OK;
9248 *no_space_count = count + no_similar_count;
9249 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9253 /* until proper implementation
9254 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9256 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9257 if(res!=EQUIP_ERR_OK)
9260 *no_space_count = count + no_similar_count;
9266 if(no_similar_count==0)
9267 return EQUIP_ERR_OK;
9270 *no_space_count = count + no_similar_count;
9271 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9276 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9277 if(res
!=EQUIP_ERR_OK
)
9280 *no_space_count
= count
+ no_similar_count
;
9286 if(no_similar_count
==0)
9287 return EQUIP_ERR_OK
;
9290 *no_space_count
= count
+ no_similar_count
;
9291 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9294 else // equipped bag
9296 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9297 if(res
!=EQUIP_ERR_OK
)
9298 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9300 if(res
!=EQUIP_ERR_OK
)
9303 *no_space_count
= count
+ no_similar_count
;
9309 if(no_similar_count
==0)
9310 return EQUIP_ERR_OK
;
9313 *no_space_count
= count
+ no_similar_count
;
9314 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9319 // not specific bag or have space for partly store only in specific bag
9321 // search stack for merge to
9322 if( pProto
->Stackable
!= 1 )
9324 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9325 if(res
!=EQUIP_ERR_OK
)
9328 *no_space_count
= count
+ no_similar_count
;
9334 if(no_similar_count
==0)
9335 return EQUIP_ERR_OK
;
9338 *no_space_count
= count
+ no_similar_count
;
9339 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9342 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9343 if(res
!=EQUIP_ERR_OK
)
9346 *no_space_count
= count
+ no_similar_count
;
9352 if(no_similar_count
==0)
9353 return EQUIP_ERR_OK
;
9356 *no_space_count
= count
+ no_similar_count
;
9357 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9360 if( pProto
->BagFamily
)
9362 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9364 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9365 if(res
!=EQUIP_ERR_OK
)
9370 if(no_similar_count
==0)
9371 return EQUIP_ERR_OK
;
9374 *no_space_count
= count
+ no_similar_count
;
9375 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9380 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9382 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9383 if(res
!=EQUIP_ERR_OK
)
9388 if(no_similar_count
==0)
9389 return EQUIP_ERR_OK
;
9392 *no_space_count
= count
+ no_similar_count
;
9393 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9398 // search free slot - special bag case
9399 if( pProto
->BagFamily
)
9401 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9403 uint32 keyringSize
= GetMaxKeyringSize();
9404 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9405 if(res
!=EQUIP_ERR_OK
)
9408 *no_space_count
= count
+ no_similar_count
;
9414 if(no_similar_count
==0)
9415 return EQUIP_ERR_OK
;
9418 *no_space_count
= count
+ no_similar_count
;
9419 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9423 // Vanity pet case skipped as not used
9425 /* until proper implementation
9426 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9428 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9429 if(res!=EQUIP_ERR_OK)
9432 *no_space_count = count + no_similar_count;
9438 if(no_similar_count==0)
9439 return EQUIP_ERR_OK;
9442 *no_space_count = count + no_similar_count;
9443 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9447 /* until proper implementation
9448 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9450 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9451 if(res!=EQUIP_ERR_OK)
9454 *no_space_count = count + no_similar_count;
9460 if(no_similar_count==0)
9461 return EQUIP_ERR_OK;
9464 *no_space_count = count + no_similar_count;
9465 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9470 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9472 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9473 if(res
!=EQUIP_ERR_OK
)
9478 if(no_similar_count
==0)
9479 return EQUIP_ERR_OK
;
9482 *no_space_count
= count
+ no_similar_count
;
9483 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9489 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9490 if(res
!=EQUIP_ERR_OK
)
9493 *no_space_count
= count
+ no_similar_count
;
9499 if(no_similar_count
==0)
9500 return EQUIP_ERR_OK
;
9503 *no_space_count
= count
+ no_similar_count
;
9504 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9507 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9509 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9510 if(res
!=EQUIP_ERR_OK
)
9515 if(no_similar_count
==0)
9516 return EQUIP_ERR_OK
;
9519 *no_space_count
= count
+ no_similar_count
;
9520 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9525 *no_space_count
= count
+ no_similar_count
;
9527 return EQUIP_ERR_INVENTORY_FULL
;
9530 //////////////////////////////////////////////////////////////////////////
9531 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9536 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9537 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9538 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9539 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9540 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9542 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9543 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9544 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9545 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9546 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9548 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9550 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9552 if (pItem2
&& !pItem2
->IsInTrade())
9554 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9558 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9560 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9562 if (pItem2
&& !pItem2
->IsInTrade())
9564 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9568 // Vanity pet case skipped as not used
9570 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9572 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9574 if (pItem2
&& !pItem2
->IsInTrade())
9576 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9580 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9582 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9584 if (pItem2
&& !pItem2
->IsInTrade())
9586 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9590 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9592 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9594 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9596 pItem2
= GetItemByPos( i
, j
);
9597 if (pItem2
&& !pItem2
->IsInTrade())
9599 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9605 // check free space for all items
9606 for (int k
=0;k
<count
;k
++)
9608 Item
*pItem
= pItems
[k
];
9611 if (!pItem
) continue;
9613 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9614 ItemPrototype
const *pProto
= pItem
->GetProto();
9618 return EQUIP_ERR_ITEM_NOT_FOUND
;
9621 if(pItem
->IsBindedNotWith(GetGUID()))
9622 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9625 ItemPrototype
const *pBagProto
;
9627 // item is 'one item only'
9628 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9629 if(res
!= EQUIP_ERR_OK
)
9632 // search stack for merge to
9633 if( pProto
->Stackable
!= 1 )
9635 bool b_found
= false;
9637 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9639 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9640 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9642 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9647 if (b_found
) continue;
9649 // Vanity pet case skipped as not used
9651 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9653 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9654 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9656 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9661 if (b_found
) continue;
9663 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9665 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9666 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9668 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9673 if (b_found
) continue;
9675 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9677 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9678 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9680 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9685 if (b_found
) continue;
9687 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9689 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9692 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9694 pItem2
= GetItemByPos( t
, j
);
9695 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9697 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9704 if (b_found
) continue;
9708 if( pProto
->BagFamily
)
9710 bool b_found
= false;
9711 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9713 uint32 keyringSize
= GetMaxKeyringSize();
9714 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9716 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9718 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9725 if (b_found
) continue;
9727 // Vanity pet case skipped as not used
9729 /* until proper implementation
9730 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9732 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9734 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9736 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9743 if (b_found) continue;
9745 /* until proper implementation
9746 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9748 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9750 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9752 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9759 if (b_found) continue;
9762 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9764 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9767 pBagProto
= pBag
->GetProto();
9769 // not plain container check
9770 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9771 ItemCanGoIntoBag(pProto
,pBagProto
) )
9773 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9775 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9777 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9785 if (b_found
) continue;
9789 bool b_found
= false;
9790 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9792 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9794 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9799 if (b_found
) continue;
9801 // search free slot in bags
9802 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9804 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9807 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9809 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9811 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9819 // no free slot found?
9821 return EQUIP_ERR_INVENTORY_FULL
;
9824 return EQUIP_ERR_OK
;
9827 //////////////////////////////////////////////////////////////////////////
9828 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9831 Item
*pItem
= Item::CreateItem( item
, 1, this );
9834 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9839 return EQUIP_ERR_ITEM_NOT_FOUND
;
9842 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9847 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9848 ItemPrototype
const *pProto
= pItem
->GetProto();
9851 // May be here should be more stronger checks; STUNNED checked
9852 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9853 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9854 return EQUIP_ERR_YOU_ARE_STUNNED
;
9856 if(pItem
->IsBindedNotWith(GetGUID()))
9857 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9859 // check count of items (skip for auto move for same player from bank)
9860 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9861 if(res
!= EQUIP_ERR_OK
)
9864 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9866 // - in-progress arenas
9867 if( !pProto
->CanChangeEquipStateInCombat() )
9870 return EQUIP_ERR_NOT_IN_COMBAT
;
9872 if(BattleGround
* bg
= GetBattleGround())
9873 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9874 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9877 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9878 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9880 if(IsNonMeleeSpellCasted(false))
9881 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9883 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9884 if( eslot
== NULL_SLOT
)
9885 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9887 uint8 msg
= CanUseItem( pItem
, not_loading
);
9888 if( msg
!= EQUIP_ERR_OK
)
9890 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9891 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9893 // check unique-equipped on item
9894 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9896 // there is an equip limit on this item
9897 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9898 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9899 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9902 // check unique-equipped on gems
9903 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9905 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9908 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9912 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9913 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9915 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9916 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9917 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9921 // check unique-equipped special item classes
9922 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9924 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9926 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9928 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9930 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9931 (!swap
|| pBag
->GetSlot() != eslot
) )
9933 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9934 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9936 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9943 uint32 type
= pProto
->InventoryType
;
9945 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9947 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9950 return EQUIP_ERR_CANT_DUAL_WIELD
;
9952 else if (type
== INVTYPE_2HWEAPON
)
9954 if(!CanDualWield() || !CanTitanGrip())
9955 return EQUIP_ERR_CANT_DUAL_WIELD
;
9959 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9962 // equip two-hand weapon case (with possible unequip 2 items)
9963 if( type
== INVTYPE_2HWEAPON
)
9965 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9967 if (!CanTitanGrip())
9968 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9970 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9971 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9973 if (!CanTitanGrip())
9975 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9976 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9977 ItemPosCountVec off_dest
;
9978 if( offItem
&& (!not_loading
||
9979 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9980 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9981 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9984 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9985 return EQUIP_ERR_OK
;
9989 return EQUIP_ERR_ITEM_NOT_FOUND
;
9991 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9994 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9996 // Applied only to equipped items and bank bags
9997 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9998 return EQUIP_ERR_OK
;
10000 Item
* pItem
= GetItemByPos(pos
);
10002 // Applied only to existed equipped item
10004 return EQUIP_ERR_OK
;
10006 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10008 ItemPrototype
const *pProto
= pItem
->GetProto();
10010 return EQUIP_ERR_ITEM_NOT_FOUND
;
10012 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10014 // - in-progress arenas
10015 if( !pProto
->CanChangeEquipStateInCombat() )
10018 return EQUIP_ERR_NOT_IN_COMBAT
;
10020 if(BattleGround
* bg
= GetBattleGround())
10021 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10022 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10025 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10026 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10028 return EQUIP_ERR_OK
;
10031 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10034 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10036 uint32 count
= pItem
->GetCount();
10038 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10039 ItemPrototype
const *pProto
= pItem
->GetProto();
10041 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10043 if( pItem
->IsBindedNotWith(GetGUID()) )
10044 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10046 // check count of items (skip for auto move for same player from bank)
10047 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10048 if(res
!= EQUIP_ERR_OK
)
10051 // in specific slot
10052 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10054 if( pProto
->InventoryType
== INVTYPE_BAG
)
10056 Bag
*pBag
= (Bag
*)pItem
;
10059 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10061 if( !HasBankBagSlot( slot
) )
10062 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10063 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10068 if( !pBag
->IsEmpty() )
10069 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10075 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10076 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10079 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10080 if(res
!=EQUIP_ERR_OK
)
10084 return EQUIP_ERR_OK
;
10087 // not specific slot or have space for partly store only in specific slot
10090 if( bag
!= NULL_BAG
)
10092 if( pProto
->InventoryType
== INVTYPE_BAG
)
10094 Bag
*pBag
= (Bag
*)pItem
;
10095 if( pBag
&& !pBag
->IsEmpty() )
10096 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10099 // search stack in bag for merge to
10100 if( pProto
->Stackable
!= 1 )
10102 if( bag
== INVENTORY_SLOT_BAG_0
)
10104 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10105 if(res
!=EQUIP_ERR_OK
)
10109 return EQUIP_ERR_OK
;
10113 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10114 if(res
!=EQUIP_ERR_OK
)
10115 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10117 if(res
!=EQUIP_ERR_OK
)
10121 return EQUIP_ERR_OK
;
10125 // search free slot in bag
10126 if( bag
== INVENTORY_SLOT_BAG_0
)
10128 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10129 if(res
!=EQUIP_ERR_OK
)
10133 return EQUIP_ERR_OK
;
10137 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
10138 if(res
!=EQUIP_ERR_OK
)
10139 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
10141 if(res
!=EQUIP_ERR_OK
)
10145 return EQUIP_ERR_OK
;
10149 // not specific bag or have space for partly store only in specific bag
10151 // search stack for merge to
10152 if( pProto
->Stackable
!= 1 )
10155 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10156 if(res
!=EQUIP_ERR_OK
)
10160 return EQUIP_ERR_OK
;
10163 if( pProto
->BagFamily
)
10165 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10167 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10168 if(res
!=EQUIP_ERR_OK
)
10172 return EQUIP_ERR_OK
;
10176 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10178 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10179 if(res
!=EQUIP_ERR_OK
)
10183 return EQUIP_ERR_OK
;
10187 // search free place in special bag
10188 if( pProto
->BagFamily
)
10190 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10192 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10193 if(res
!=EQUIP_ERR_OK
)
10197 return EQUIP_ERR_OK
;
10201 // search free space
10202 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10203 if(res
!=EQUIP_ERR_OK
)
10207 return EQUIP_ERR_OK
;
10209 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10211 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10212 if(res
!=EQUIP_ERR_OK
)
10216 return EQUIP_ERR_OK
;
10218 return EQUIP_ERR_BANK_FULL
;
10221 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10225 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10226 if( !isAlive() && not_loading
)
10227 return EQUIP_ERR_YOU_ARE_DEAD
;
10228 //if( isStunned() )
10229 // return EQUIP_ERR_YOU_ARE_STUNNED;
10230 ItemPrototype
const *pProto
= pItem
->GetProto();
10233 if( pItem
->IsBindedNotWith(GetGUID()) )
10234 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10235 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10236 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10237 if( pItem
->GetSkill() != 0 )
10239 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10240 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10242 if( pProto
->RequiredSkill
!= 0 )
10244 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10245 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10246 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10247 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10249 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10250 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10251 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10252 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10253 if( getLevel() < pProto
->RequiredLevel
)
10254 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10255 return EQUIP_ERR_OK
;
10258 return EQUIP_ERR_ITEM_NOT_FOUND
;
10261 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10263 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10267 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10269 if( pProto
->RequiredSkill
!= 0 )
10271 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10273 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10276 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10278 if( getLevel() < pProto
->RequiredLevel
)
10285 uint8
Player::CanUseAmmo( uint32 item
) const
10287 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10289 return EQUIP_ERR_YOU_ARE_DEAD
;
10290 //if( isStunned() )
10291 // return EQUIP_ERR_YOU_ARE_STUNNED;
10292 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10295 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10296 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10297 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10298 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10299 if( pProto
->RequiredSkill
!= 0 )
10301 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10302 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10303 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10304 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10306 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10307 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10308 /*if( GetReputation() < pProto->RequiredReputation )
10309 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10311 if( getLevel() < pProto
->RequiredLevel
)
10312 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10314 // Requires No Ammo
10315 if(GetDummyAura(46699))
10316 return EQUIP_ERR_BAG_FULL6
;
10318 return EQUIP_ERR_OK
;
10320 return EQUIP_ERR_ITEM_NOT_FOUND
;
10323 void Player::SetAmmo( uint32 item
)
10329 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10335 uint8 msg
= CanUseAmmo( item
);
10336 if( msg
!= EQUIP_ERR_OK
)
10338 SendEquipError( msg
, NULL
, NULL
);
10343 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10345 _ApplyAmmoBonuses();
10348 void Player::RemoveAmmo()
10350 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10354 if(CanModifyStats())
10355 UpdateDamagePhysical(RANGED_ATTACK
);
10358 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10359 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10362 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10363 count
+= itr
->count
;
10365 Item
*pItem
= Item::CreateItem( item
, count
, this );
10368 ItemAddedQuestCheck( item
, count
);
10369 if(randomPropertyId
)
10370 pItem
->SetItemRandomProperties(randomPropertyId
);
10371 pItem
= StoreItem( dest
, pItem
, update
);
10376 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10381 Item
* lastItem
= pItem
;
10383 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10385 uint16 pos
= itr
->pos
;
10386 uint32 count
= itr
->count
;
10390 if(itr
== dest
.end())
10392 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10396 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10402 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10403 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10408 uint8 bag
= pos
>> 8;
10409 uint8 slot
= pos
& 255;
10411 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10413 Item
*pItem2
= GetItemByPos( bag
, slot
);
10418 pItem
= pItem
->CloneItem(count
,this);
10420 pItem
->SetCount(count
);
10425 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10426 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10427 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10428 pItem
->SetBinding( true );
10430 if( bag
== INVENTORY_SLOT_BAG_0
)
10432 m_items
[slot
] = pItem
;
10433 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10434 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10435 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10437 pItem
->SetSlot( slot
);
10438 pItem
->SetContainer( NULL
);
10440 if( IsInWorld() && update
)
10442 pItem
->AddToWorld();
10443 pItem
->SendUpdateToPlayer( this );
10446 pItem
->SetState(ITEM_CHANGED
, this);
10450 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10453 pBag
->StoreItem( slot
, pItem
, update
);
10454 if( IsInWorld() && update
)
10456 pItem
->AddToWorld();
10457 pItem
->SendUpdateToPlayer( this );
10459 pItem
->SetState(ITEM_CHANGED
, this);
10460 pBag
->SetState(ITEM_CHANGED
, this);
10464 AddEnchantmentDurations(pItem
);
10465 AddItemDurations(pItem
);
10471 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10472 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10473 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10474 pItem2
->SetBinding( true );
10476 pItem2
->SetCount( pItem2
->GetCount() + count
);
10477 if( IsInWorld() && update
)
10478 pItem2
->SendUpdateToPlayer( this );
10482 // delete item (it not in any slot currently)
10483 if( IsInWorld() && update
)
10485 pItem
->RemoveFromWorld();
10486 pItem
->DestroyForPlayer( this );
10489 RemoveEnchantmentDurations(pItem
);
10490 RemoveItemDurations(pItem
);
10492 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10493 pItem
->SetState(ITEM_REMOVED
, this);
10495 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10496 AddEnchantmentDurations(pItem2
);
10498 pItem2
->SetState(ITEM_CHANGED
, this);
10504 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10506 Item
*pItem
= Item::CreateItem( item
, 1, this );
10509 ItemAddedQuestCheck( item
, 1 );
10510 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10517 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10521 AddEnchantmentDurations(pItem
);
10522 AddItemDurations(pItem
);
10524 uint8 bag
= pos
>> 8;
10525 uint8 slot
= pos
& 255;
10527 Item
*pItem2
= GetItemByPos( bag
, slot
);
10531 VisualizeItem( slot
, pItem
);
10535 ItemPrototype
const *pProto
= pItem
->GetProto();
10537 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10538 if(pProto
&& pProto
->ItemSet
)
10539 AddItemsSetItem(this,pItem
);
10541 _ApplyItemMods(pItem
, slot
, true);
10543 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10545 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10547 if (getClass() == CLASS_ROGUE
)
10548 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10550 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10553 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10556 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10558 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10559 data
<< uint64(GetGUID());
10561 data
<< uint32(cooldownSpell
);
10563 GetSession()->SendPacket(&data
);
10568 if( IsInWorld() && update
)
10570 pItem
->AddToWorld();
10571 pItem
->SendUpdateToPlayer( this );
10574 ApplyEquipCooldown(pItem
);
10576 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10577 UpdateExpertise(BASE_ATTACK
);
10578 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10579 UpdateExpertise(OFF_ATTACK
);
10583 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10584 if( IsInWorld() && update
)
10585 pItem2
->SendUpdateToPlayer( this );
10587 // delete item (it not in any slot currently)
10588 //pItem->DeleteFromDB();
10589 if( IsInWorld() && update
)
10591 pItem
->RemoveFromWorld();
10592 pItem
->DestroyForPlayer( this );
10595 RemoveEnchantmentDurations(pItem
);
10596 RemoveItemDurations(pItem
);
10598 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10599 pItem
->SetState(ITEM_REMOVED
, this);
10600 pItem2
->SetState(ITEM_CHANGED
, this);
10602 ApplyEquipCooldown(pItem2
);
10611 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10615 AddEnchantmentDurations(pItem
);
10616 AddItemDurations(pItem
);
10618 uint8 slot
= pos
& 255;
10619 VisualizeItem( slot
, pItem
);
10623 pItem
->AddToWorld();
10624 pItem
->SendUpdateToPlayer( this );
10629 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10631 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10632 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10633 // entry // Size: 1
10634 // inspected enchantments // Size: 6
10636 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10637 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10642 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10644 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10645 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10647 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10648 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10650 // Use SetInt16Value to prevent set high part to FFFF for negative value
10651 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10652 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10656 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10658 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10659 SetUInt32Value(VisibleBase
+ 0, 0);
10661 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10662 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10664 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10665 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10669 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10674 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10675 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10676 pItem
->SetBinding( true );
10678 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10680 m_items
[slot
] = pItem
;
10681 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10682 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10683 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10684 pItem
->SetSlot( slot
);
10685 pItem
->SetContainer( NULL
);
10687 if( slot
< EQUIPMENT_SLOT_END
)
10688 SetVisibleItemSlot(slot
,pItem
);
10690 pItem
->SetState(ITEM_CHANGED
, this);
10693 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10695 // note: removeitem does not actually change the item
10696 // it only takes the item out of storage temporarily
10697 // note2: if removeitem is to be used for delinking
10698 // the item must be removed from the player's updatequeue
10700 Item
*pItem
= GetItemByPos( bag
, slot
);
10703 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10705 RemoveEnchantmentDurations(pItem
);
10706 RemoveItemDurations(pItem
);
10708 if( bag
== INVENTORY_SLOT_BAG_0
)
10710 if ( slot
< INVENTORY_SLOT_BAG_END
)
10712 ItemPrototype
const *pProto
= pItem
->GetProto();
10713 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10715 if(pProto
&& pProto
->ItemSet
)
10716 RemoveItemsSetItem(this,pProto
);
10718 _ApplyItemMods(pItem
, slot
, false);
10720 // remove item dependent auras and casts (only weapon and armor slots)
10721 if(slot
< EQUIPMENT_SLOT_END
)
10722 RemoveItemDependentAurasAndCasts(pItem
);
10724 // remove held enchantments
10725 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10727 if (pItem
->GetItemSuffixFactor())
10729 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10730 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10734 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10735 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10740 m_items
[slot
] = NULL
;
10741 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10743 if ( slot
< EQUIPMENT_SLOT_END
)
10744 SetVisibleItemSlot(slot
,NULL
);
10748 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10750 pBag
->RemoveItem(slot
, update
);
10752 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10753 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10754 pItem
->SetSlot( NULL_SLOT
);
10755 if( IsInWorld() && update
)
10756 pItem
->SendUpdateToPlayer( this );
10758 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10759 UpdateExpertise(BASE_ATTACK
);
10760 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10761 UpdateExpertise(OFF_ATTACK
);
10765 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10766 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10768 if(Item
* it
= GetItemByPos(bag
,slot
))
10770 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10771 RemoveItem( bag
,slot
,update
);
10772 it
->RemoveFromUpdateQueueOf(this);
10773 if(it
->IsInWorld())
10775 it
->RemoveFromWorld();
10776 it
->DestroyForPlayer( this );
10781 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10782 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10784 // update quest counters
10785 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10788 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10790 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10791 if(pLastItem
==pItem
)
10793 // update owner for last item (this can be original item with wrong owner
10794 if(pLastItem
->GetOwnerGUID() != GetGUID())
10795 pLastItem
->SetOwnerGUID(GetGUID());
10797 // if this original item then it need create record in inventory
10798 // in case trade we already have item in other player inventory
10799 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10803 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10805 Item
*pItem
= GetItemByPos( bag
, slot
);
10808 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10810 // start from destroy contained items (only equipped bag can have its)
10811 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10813 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10814 DestroyItem(slot
,i
,update
);
10817 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10818 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10820 RemoveEnchantmentDurations(pItem
);
10821 RemoveItemDurations(pItem
);
10823 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10825 if( bag
== INVENTORY_SLOT_BAG_0
)
10827 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10829 // equipment and equipped bags can have applied bonuses
10830 if ( slot
< INVENTORY_SLOT_BAG_END
)
10832 ItemPrototype
const *pProto
= pItem
->GetProto();
10834 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10835 if(pProto
&& pProto
->ItemSet
)
10836 RemoveItemsSetItem(this,pProto
);
10838 _ApplyItemMods(pItem
, slot
, false);
10841 if ( slot
< EQUIPMENT_SLOT_END
)
10843 // remove item dependent auras and casts (only weapon and armor slots)
10844 RemoveItemDependentAurasAndCasts(pItem
);
10846 // equipment visual show
10847 SetVisibleItemSlot(slot
,NULL
);
10850 m_items
[slot
] = NULL
;
10852 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10853 pBag
->RemoveItem(slot
, update
);
10855 if( IsInWorld() && update
)
10857 pItem
->RemoveFromWorld();
10858 pItem
->DestroyForPlayer(this);
10861 //pItem->SetOwnerGUID(0);
10862 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10863 pItem
->SetSlot( NULL_SLOT
);
10864 pItem
->SetState(ITEM_REMOVED
, this);
10868 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10870 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10872 ItemPrototype
const *pProto
;
10873 uint32 remcount
= 0;
10876 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10878 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10879 if( pItem
&& pItem
->GetEntry() == item
)
10881 if( pItem
->GetCount() + remcount
<= count
)
10883 // all items in inventory can unequipped
10884 remcount
+= pItem
->GetCount();
10885 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10887 if(remcount
>=count
)
10892 pProto
= pItem
->GetProto();
10893 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10894 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10895 if( IsInWorld() & update
)
10896 pItem
->SendUpdateToPlayer( this );
10897 pItem
->SetState(ITEM_CHANGED
, this);
10902 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10904 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10905 if( pItem
&& pItem
->GetEntry() == item
)
10907 if( pItem
->GetCount() + remcount
<= count
)
10909 // all keys can be unequipped
10910 remcount
+= pItem
->GetCount();
10911 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10913 if(remcount
>=count
)
10918 pProto
= pItem
->GetProto();
10919 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10920 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10921 if( IsInWorld() & update
)
10922 pItem
->SendUpdateToPlayer( this );
10923 pItem
->SetState(ITEM_CHANGED
, this);
10929 // in inventory bags
10930 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10932 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10934 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10936 pItem
= pBag
->GetItemByPos(j
);
10937 if( pItem
&& pItem
->GetEntry() == item
)
10939 // all items in bags can be unequipped
10940 if( pItem
->GetCount() + remcount
<= count
)
10942 remcount
+= pItem
->GetCount();
10943 DestroyItem( i
, j
, update
);
10945 if(remcount
>=count
)
10950 pProto
= pItem
->GetProto();
10951 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10952 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10953 if( IsInWorld() && update
)
10954 pItem
->SendUpdateToPlayer( this );
10955 pItem
->SetState(ITEM_CHANGED
, this);
10963 // in equipment and bag list
10964 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10966 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10967 if( pItem
&& pItem
->GetEntry() == item
)
10969 if( pItem
->GetCount() + remcount
<= count
)
10971 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10973 remcount
+= pItem
->GetCount();
10974 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10976 if(remcount
>=count
)
10982 pProto
= pItem
->GetProto();
10983 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10984 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10985 if( IsInWorld() & update
)
10986 pItem
->SendUpdateToPlayer( this );
10987 pItem
->SetState(ITEM_CHANGED
, this);
10994 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10996 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10999 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11001 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11002 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11003 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11005 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
11007 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11008 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11009 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11012 // in inventory bags
11013 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11015 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11018 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11020 Item
* pItem
= pBag
->GetItemByPos(j
);
11021 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11022 DestroyItem( i
, j
, update
);
11027 // in equipment and bag list
11028 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11030 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11031 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11032 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11036 void Player::DestroyConjuredItems( bool update
)
11038 // used when entering arena
11039 // destroys all conjured items
11040 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11043 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11045 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11046 if( pItem
&& pItem
->GetProto() &&
11047 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11048 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11049 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11052 // in inventory bags
11053 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11055 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11058 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11060 Item
* pItem
= pBag
->GetItemByPos(j
);
11061 if( pItem
&& pItem
->GetProto() &&
11062 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11063 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11064 DestroyItem( i
, j
, update
);
11069 // in equipment and bag list
11070 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11072 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11073 if( pItem
&& pItem
->GetProto() &&
11074 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11075 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11076 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11080 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11085 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11087 if( pItem
->GetCount() <= count
)
11089 count
-= pItem
->GetCount();
11091 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11095 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11096 pItem
->SetCount( pItem
->GetCount() - count
);
11098 if( IsInWorld() & update
)
11099 pItem
->SendUpdateToPlayer( this );
11100 pItem
->SetState(ITEM_CHANGED
, this);
11104 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11106 uint8 srcbag
= src
>> 8;
11107 uint8 srcslot
= src
& 255;
11109 uint8 dstbag
= dst
>> 8;
11110 uint8 dstslot
= dst
& 255;
11112 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11115 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11119 // not let split all items (can be only at cheating)
11120 if(pSrcItem
->GetCount() == count
)
11122 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11126 // not let split more existed items (can be only at cheating)
11127 if(pSrcItem
->GetCount() < count
)
11129 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11133 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11135 //best error message found for attempting to split while looting
11136 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11140 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11141 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11144 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11148 if( IsInventoryPos( dst
) )
11150 // change item amount before check (for unique max count check)
11151 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11153 ItemPosCountVec dest
;
11154 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11155 if( msg
!= EQUIP_ERR_OK
)
11158 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11159 SendEquipError( msg
, pSrcItem
, NULL
);
11164 pSrcItem
->SendUpdateToPlayer( this );
11165 pSrcItem
->SetState(ITEM_CHANGED
, this);
11166 StoreItem( dest
, pNewItem
, true);
11168 else if( IsBankPos ( dst
) )
11170 // change item amount before check (for unique max count check)
11171 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11173 ItemPosCountVec dest
;
11174 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11175 if( msg
!= EQUIP_ERR_OK
)
11178 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11179 SendEquipError( msg
, pSrcItem
, NULL
);
11184 pSrcItem
->SendUpdateToPlayer( this );
11185 pSrcItem
->SetState(ITEM_CHANGED
, this);
11186 BankItem( dest
, pNewItem
, true);
11188 else if( IsEquipmentPos ( dst
) )
11190 // change item amount before check (for unique max count check), provide space for splitted items
11191 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11194 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11195 if( msg
!= EQUIP_ERR_OK
)
11198 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11199 SendEquipError( msg
, pSrcItem
, NULL
);
11204 pSrcItem
->SendUpdateToPlayer( this );
11205 pSrcItem
->SetState(ITEM_CHANGED
, this);
11206 EquipItem( dest
, pNewItem
, true);
11207 AutoUnequipOffhandIfNeed();
11211 void Player::SwapItem( uint16 src
, uint16 dst
)
11213 uint8 srcbag
= src
>> 8;
11214 uint8 srcslot
= src
& 255;
11216 uint8 dstbag
= dst
>> 8;
11217 uint8 dstslot
= dst
& 255;
11219 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11220 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11225 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11229 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11233 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11235 //best error message found for attempting to swap while looting
11236 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11240 // check unequip potability for equipped items and bank bags
11241 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11243 // bags can be swapped with empty bag slots
11244 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
11245 if(msg
!= EQUIP_ERR_OK
)
11247 SendEquipError( msg
, pSrcItem
, pDstItem
);
11252 // prevent put equipped/bank bag in self
11253 if( IsBagPos ( src
) && srcslot
== dstbag
)
11255 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11261 if( IsInventoryPos( dst
) )
11263 ItemPosCountVec dest
;
11264 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11265 if( msg
!= EQUIP_ERR_OK
)
11267 SendEquipError( msg
, pSrcItem
, NULL
);
11271 RemoveItem(srcbag
, srcslot
, true);
11272 StoreItem( dest
, pSrcItem
, true);
11274 else if( IsBankPos ( dst
) )
11276 ItemPosCountVec dest
;
11277 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11278 if( msg
!= EQUIP_ERR_OK
)
11280 SendEquipError( msg
, pSrcItem
, NULL
);
11284 RemoveItem(srcbag
, srcslot
, true);
11285 BankItem( dest
, pSrcItem
, true);
11287 else if( IsEquipmentPos ( dst
) )
11290 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11291 if( msg
!= EQUIP_ERR_OK
)
11293 SendEquipError( msg
, pSrcItem
, NULL
);
11297 RemoveItem(srcbag
, srcslot
, true);
11298 EquipItem( dest
, pSrcItem
, true);
11299 AutoUnequipOffhandIfNeed();
11302 else // if (!pDstItem)
11304 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11306 //best error message found for attempting to swap while looting
11307 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11311 // check unequip potability for equipped items and bank bags
11312 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11314 // bags can be swapped with empty bag slots
11315 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
11316 if(msg
!= EQUIP_ERR_OK
)
11318 SendEquipError( msg
, pSrcItem
, pDstItem
);
11323 // attempt merge to / fill target item
11326 ItemPosCountVec sDest
;
11328 if( IsInventoryPos( dst
) )
11329 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11330 else if( IsBankPos ( dst
) )
11331 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11332 else if( IsEquipmentPos ( dst
) )
11333 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11337 // can be merge/fill
11338 if(msg
== EQUIP_ERR_OK
)
11340 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11342 RemoveItem(srcbag
, srcslot
, true);
11344 if( IsInventoryPos( dst
) )
11345 StoreItem( sDest
, pSrcItem
, true);
11346 else if( IsBankPos ( dst
) )
11347 BankItem( sDest
, pSrcItem
, true);
11348 else if( IsEquipmentPos ( dst
) )
11350 EquipItem( eDest
, pSrcItem
, true);
11351 AutoUnequipOffhandIfNeed();
11356 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11357 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11358 pSrcItem
->SetState(ITEM_CHANGED
, this);
11359 pDstItem
->SetState(ITEM_CHANGED
, this);
11362 pSrcItem
->SendUpdateToPlayer( this );
11363 pDstItem
->SendUpdateToPlayer( this );
11370 // impossible merge/fill, do real swap
11373 // check src->dest move possibility
11374 ItemPosCountVec sDest
;
11376 if( IsInventoryPos( dst
) )
11377 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11378 else if( IsBankPos( dst
) )
11379 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11380 else if( IsEquipmentPos( dst
) )
11382 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11383 if( msg
== EQUIP_ERR_OK
)
11384 msg
= CanUnequipItem( eDest
, true );
11387 if( msg
!= EQUIP_ERR_OK
)
11389 SendEquipError( msg
, pSrcItem
, pDstItem
);
11393 // check dest->src move possibility
11394 ItemPosCountVec sDest2
;
11396 if( IsInventoryPos( src
) )
11397 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11398 else if( IsBankPos( src
) )
11399 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11400 else if( IsEquipmentPos( src
) )
11402 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11403 if( msg
== EQUIP_ERR_OK
)
11404 msg
= CanUnequipItem( eDest2
, true);
11407 if( msg
!= EQUIP_ERR_OK
)
11409 SendEquipError( msg
, pDstItem
, pSrcItem
);
11413 // now do moves, remove...
11414 RemoveItem(dstbag
, dstslot
, false);
11415 RemoveItem(srcbag
, srcslot
, false);
11418 if( IsInventoryPos( dst
) )
11419 StoreItem(sDest
, pSrcItem
, true);
11420 else if( IsBankPos( dst
) )
11421 BankItem(sDest
, pSrcItem
, true);
11422 else if( IsEquipmentPos( dst
) )
11423 EquipItem(eDest
, pSrcItem
, true);
11426 if( IsInventoryPos( src
) )
11427 StoreItem(sDest2
, pDstItem
, true);
11428 else if( IsBankPos( src
) )
11429 BankItem(sDest2
, pDstItem
, true);
11430 else if( IsEquipmentPos( src
) )
11431 EquipItem(eDest2
, pDstItem
, true);
11433 AutoUnequipOffhandIfNeed();
11437 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11441 uint32 slot
= m_currentBuybackSlot
;
11442 // if current back slot non-empty search oldest or free
11445 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11446 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11448 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11457 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11459 if(oldest_time
> i_time
)
11461 oldest_time
= i_time
;
11467 slot
= oldest_slot
;
11470 RemoveItemFromBuyBackSlot( slot
, true );
11471 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11473 m_items
[slot
] = pItem
;
11474 time_t base
= time(NULL
);
11475 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11476 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11478 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11479 ItemPrototype
const *pProto
= pItem
->GetProto();
11481 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11483 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11484 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11486 // move to next (for non filled list is move most optimized choice)
11487 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11488 ++m_currentBuybackSlot
;
11492 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11494 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11495 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11496 return m_items
[slot
];
11500 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11502 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11503 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11505 Item
*pItem
= m_items
[slot
];
11508 pItem
->RemoveFromWorld();
11509 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11512 m_items
[slot
] = NULL
;
11514 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11515 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11516 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11517 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11519 // if current backslot is filled set to now free slot
11520 if(m_items
[m_currentBuybackSlot
])
11521 m_currentBuybackSlot
= slot
;
11525 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11527 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11528 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11529 data
<< uint8(msg
);
11533 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11534 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11535 data
<< uint8(0); // not 0 there...
11537 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11542 if(ItemPrototype
const* proto
= pItem
->GetProto())
11543 level
= proto
->RequiredLevel
;
11545 data
<< uint32(level
); // new 2.4.0
11548 GetSession()->SendPacket(&data
);
11551 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11553 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11554 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11555 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11556 data
<< uint32(item
);
11558 data
<< uint32(param
);
11559 data
<< uint8(msg
);
11560 GetSession()->SendPacket(&data
);
11563 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11565 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11566 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11567 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11568 data
<< uint64(guid
);
11570 data
<< uint32(param
);
11571 data
<< uint8(msg
);
11572 GetSession()->SendPacket(&data
);
11575 void Player::ClearTrade()
11578 acceptTrade
= false;
11579 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11580 tradeItems
[i
] = NULL_SLOT
;
11583 void Player::TradeCancel(bool sendback
)
11587 // send yellow "Trade canceled" message to both traders
11591 ws
->SendCancelTrade();
11592 ws
= pTrader
->GetSession();
11593 if(!ws
->PlayerLogout())
11594 ws
->SendCancelTrade();
11598 pTrader
->ClearTrade();
11599 // prevent loss of reference
11600 pTrader
->pTrader
= NULL
;
11605 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11607 if(m_itemDuration
.empty())
11610 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11612 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11615 ++itr
; // current element can be erased in UpdateDuration
11617 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11618 item
->UpdateDuration(this,time
);
11622 void Player::UpdateEnchantTime(uint32 time
)
11624 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11628 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11630 next
= m_enchantDuration
.erase(itr
);
11632 else if(itr
->leftduration
<= time
)
11634 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11635 itr
->item
->ClearEnchantment(itr
->slot
);
11636 next
= m_enchantDuration
.erase(itr
);
11638 else if(itr
->leftduration
> time
)
11640 itr
->leftduration
-= time
;
11646 void Player::AddEnchantmentDurations(Item
*item
)
11648 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11650 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11653 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11655 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11659 void Player::RemoveEnchantmentDurations(Item
*item
)
11661 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11663 if(itr
->item
== item
)
11665 // save duration in item
11666 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11667 itr
= m_enchantDuration
.erase(itr
);
11674 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11676 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11677 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11680 if(itr
->slot
==slot
)
11682 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11684 // remove from stats
11685 ApplyEnchantment(itr
->item
,slot
,false,false);
11687 itr
->item
->ClearEnchantment(slot
);
11689 // remove from update list
11690 next
= m_enchantDuration
.erase(itr
);
11696 // remove enchants from inventory items
11697 // NOTE: no need to remove these from stats, since these aren't equipped
11699 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11701 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11702 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11703 pItem
->ClearEnchantment(slot
);
11706 // in inventory bags
11707 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11709 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11712 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11714 Item
* pItem
= pBag
->GetItemByPos(j
);
11715 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11716 pItem
->ClearEnchantment(slot
);
11722 // duration == 0 will remove item enchant
11723 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11728 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11731 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11733 if(itr
->item
== item
&& itr
->slot
== slot
)
11735 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11736 m_enchantDuration
.erase(itr
);
11740 if(item
&& duration
> 0 )
11742 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11743 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11747 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11749 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11750 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11753 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11758 if(!item
->IsEquipped())
11761 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11764 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11768 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11772 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11775 for (int s
=0; s
<3; s
++)
11777 uint32 enchant_display_type
= pEnchant
->type
[s
];
11778 uint32 enchant_amount
= pEnchant
->amount
[s
];
11779 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11781 switch(enchant_display_type
)
11783 case ITEM_ENCHANTMENT_TYPE_NONE
:
11785 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11786 // processed in Player::CastItemCombatSpell
11788 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11789 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11790 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11791 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11792 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11793 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11794 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11796 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11797 if(enchant_spell_id
)
11801 int32 basepoints
= 0;
11802 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11803 if (item
->GetItemRandomPropertyId())
11805 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11808 // Search enchant_amount
11809 for (int k
=0; k
<3; k
++)
11811 if(item_rand
->enchant_id
[k
] == enchant_id
)
11813 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11819 // Cast custom spell vs all equal basepoints getted from enchant_amount
11821 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11823 CastSpell(this,enchant_spell_id
,true,item
);
11826 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11829 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11830 if (!enchant_amount
)
11832 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11835 for (int k
=0; k
<3; k
++)
11837 if(item_rand
->enchant_id
[k
] == enchant_id
)
11839 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11846 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11848 case ITEM_ENCHANTMENT_TYPE_STAT
:
11850 if (!enchant_amount
)
11852 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11853 if(item_rand_suffix
)
11855 for (int k
=0; k
<3; k
++)
11857 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11859 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11866 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11867 switch (enchant_spell_id
)
11869 case ITEM_MOD_AGILITY
:
11870 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11871 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11872 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11874 case ITEM_MOD_STRENGTH
:
11875 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11876 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11877 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11879 case ITEM_MOD_INTELLECT
:
11880 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11881 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11882 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11884 case ITEM_MOD_SPIRIT
:
11885 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11886 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11887 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11889 case ITEM_MOD_STAMINA
:
11890 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11891 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11892 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11894 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11895 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11896 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11898 case ITEM_MOD_DODGE_RATING
:
11899 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11900 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11902 case ITEM_MOD_PARRY_RATING
:
11903 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11904 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11906 case ITEM_MOD_BLOCK_RATING
:
11907 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11908 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11910 case ITEM_MOD_HIT_MELEE_RATING
:
11911 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11912 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11914 case ITEM_MOD_HIT_RANGED_RATING
:
11915 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11916 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11918 case ITEM_MOD_HIT_SPELL_RATING
:
11919 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11920 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11922 case ITEM_MOD_CRIT_MELEE_RATING
:
11923 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11924 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11926 case ITEM_MOD_CRIT_RANGED_RATING
:
11927 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11928 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11930 case ITEM_MOD_CRIT_SPELL_RATING
:
11931 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11932 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11934 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11936 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11937 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11939 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11940 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11942 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11943 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11945 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11946 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11948 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11949 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11951 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11952 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11954 // case ITEM_MOD_HASTE_MELEE_RATING:
11955 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11957 // case ITEM_MOD_HASTE_RANGED_RATING:
11958 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11960 case ITEM_MOD_HASTE_SPELL_RATING
:
11961 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11963 case ITEM_MOD_HIT_RATING
:
11964 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11965 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11966 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11967 sLog
.outDebug("+ %u HIT", enchant_amount
);
11969 case ITEM_MOD_CRIT_RATING
:
11970 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11971 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11972 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11973 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11975 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11976 // case ITEM_MOD_HIT_TAKEN_RATING:
11977 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11978 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11979 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11981 // case ITEM_MOD_CRIT_TAKEN_RATING:
11982 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11983 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11984 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11986 case ITEM_MOD_RESILIENCE_RATING
:
11987 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11988 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11989 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11990 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11992 case ITEM_MOD_HASTE_RATING
:
11993 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11994 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11995 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11996 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11998 case ITEM_MOD_EXPERTISE_RATING
:
11999 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12000 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12002 case ITEM_MOD_ATTACK_POWER
:
12003 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12004 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12006 case ITEM_MOD_RANGED_ATTACK_POWER
:
12007 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12008 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12010 case ITEM_MOD_FERAL_ATTACK_POWER
:
12011 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
12012 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12014 case ITEM_MOD_SPELL_HEALING_DONE
:
12015 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12016 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
12018 case ITEM_MOD_SPELL_DAMAGE_DONE
:
12019 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12020 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
12022 case ITEM_MOD_MANA_REGENERATION
:
12023 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12024 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12026 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12027 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12028 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12030 case ITEM_MOD_SPELL_POWER
:
12031 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12032 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12033 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12040 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12042 if(getClass() == CLASS_SHAMAN
)
12044 float addValue
= 0.0f
;
12045 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12047 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12048 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12050 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12052 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12053 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12058 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12059 // processed in Player::CastItemUseSpell
12062 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12064 } /*switch(enchant_display_type)*/
12067 // visualize enchantment at player and equipped items
12068 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
12070 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
12071 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
12079 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12081 AddEnchantmentDuration(item
,slot
,duration
);
12085 // duration == 0 will remove EnchantDuration
12086 AddEnchantmentDuration(item
,slot
,0);
12091 void Player::SendEnchantmentDurations()
12093 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
12095 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
12099 void Player::SendItemDurations()
12101 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
12103 (*itr
)->SendTimeUpdate(this);
12107 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12109 if(!item
) // prevent crash
12112 // last check 2.0.10
12113 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12114 data
<< GetGUID(); // player GUID
12115 data
<< uint32(received
); // 0=looted, 1=from npc
12116 data
<< uint32(created
); // 0=received, 1=created
12117 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12118 data
<< (uint8
)item
->GetBagSlot(); // bagslot
12119 // item slot, but when added to stack: 0xFFFFFFFF
12120 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
12121 data
<< uint32(item
->GetEntry()); // item id
12122 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12123 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12124 data
<< uint32(count
); // count of items
12125 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
12127 if (broadcast
&& GetGroup())
12128 GetGroup()->BroadcastPacket(&data
);
12130 GetSession()->SendPacket(&data
);
12133 /*********************************************************/
12134 /*** QUEST SYSTEM ***/
12135 /*********************************************************/
12137 void Player::PrepareQuestMenu( uint64 guid
)
12140 QuestRelations
* pObjectQR
;
12141 QuestRelations
* pObjectQIR
;
12142 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12145 pObject
= (Object
*)pCreature
;
12146 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12147 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12151 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12154 pObject
= (Object
*)pGameObject
;
12155 pObjectQR
= &objmgr
.mGOQuestRelations
;
12156 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12162 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12165 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12167 uint32 quest_id
= i
->second
;
12168 QuestStatus status
= GetQuestStatus( quest_id
);
12169 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12170 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12171 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12172 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
12173 else if (status
== QUEST_STATUS_AVAILABLE
)
12174 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12177 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12179 uint32 quest_id
= i
->second
;
12180 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12181 if(!pQuest
) continue;
12183 QuestStatus status
= GetQuestStatus( quest_id
);
12185 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12186 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12187 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12188 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12192 void Player::SendPreparedQuest( uint64 guid
)
12194 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12195 if( questMenu
.Empty() )
12198 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12200 uint32 status
= qmi0
.m_qIcon
;
12202 // single element case
12203 if ( questMenu
.MenuItemCount() == 1 )
12205 // Auto open -- maybe also should verify there is no greeting
12206 uint32 quest_id
= qmi0
.m_qId
;
12207 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12210 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12211 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12212 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12213 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12214 // Send completable on repeatable quest if player don't have quest
12215 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12216 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12218 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12221 // multiply entries
12227 std::string title
= "";
12228 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12231 uint32 textid
= pCreature
->GetNpcTextId();
12232 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
12235 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12236 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12241 qe
= gossiptext
->Options
[0].Emotes
[0];
12243 if(!gossiptext
->Options
[0].Text_0
.empty())
12245 title
= gossiptext
->Options
[0].Text_0
;
12247 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12250 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12253 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12254 title
= nl
->Text_0
[0][loc_idx
];
12260 title
= gossiptext
->Options
[0].Text_1
;
12262 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12265 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12268 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12269 title
= nl
->Text_1
[0][loc_idx
];
12275 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12279 bool Player::IsActiveQuest( uint32 quest_id
) const
12281 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12283 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12286 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12289 QuestRelations
* pObjectQR
;
12290 QuestRelations
* pObjectQIR
;
12292 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12295 pObject
= (Object
*)pCreature
;
12296 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12297 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12301 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12304 pObject
= (Object
*)pGameObject
;
12305 pObjectQR
= &objmgr
.mGOQuestRelations
;
12306 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12312 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12313 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12315 if (itr
->second
== nextQuestID
)
12316 return objmgr
.GetQuestTemplate(nextQuestID
);
12322 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12324 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12325 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12326 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12327 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12329 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12335 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12337 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12338 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12339 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12340 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12341 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12342 && SatisfyQuestDay( pQuest
, msg
);
12345 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12347 if( !SatisfyQuestLog( msg
) )
12350 uint32 srcitem
= pQuest
->GetSrcItemId();
12353 uint32 count
= pQuest
->GetSrcItemCount();
12354 ItemPosCountVec dest
;
12355 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12357 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12358 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12360 else if( msg
!= EQUIP_ERR_OK
)
12362 SendEquipError( msg
, NULL
, NULL
);
12369 bool Player::CanCompleteQuest( uint32 quest_id
)
12373 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12374 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12375 return false; // not allow re-complete quest
12377 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12382 // auto complete quest
12383 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12386 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12389 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12391 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12393 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12398 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12400 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12402 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12405 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12410 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12413 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12416 if ( qInfo
->GetRewOrReqMoney() < 0 )
12418 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12422 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12423 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12432 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12434 // Solve problem that player don't have the quest and try complete it.
12435 // if repeatable she must be able to complete event if player don't have it.
12436 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12437 if( !CanTakeQuest(pQuest
, false) )
12440 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12441 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12442 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12445 if( !CanRewardQuest(pQuest
, false) )
12451 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12453 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12454 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12457 // daily quest can't be rewarded (25 daily quest already completed)
12458 if(!SatisfyQuestDay(pQuest
,true))
12461 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12462 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12465 // prevent receive reward with quest items in bank
12466 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12468 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12470 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12471 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12474 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12480 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12481 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12487 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12489 // prevent receive reward with quest items in bank or for not completed quest
12490 if(!CanRewardQuest(pQuest
,msg
))
12493 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12495 if( pQuest
->RewChoiceItemId
[reward
] )
12497 ItemPosCountVec dest
;
12498 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12499 if( res
!= EQUIP_ERR_OK
)
12501 SendEquipError( res
, NULL
, NULL
);
12507 if ( pQuest
->GetRewItemsCount() > 0 )
12509 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12511 if( pQuest
->RewItemId
[i
] )
12513 ItemPosCountVec dest
;
12514 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12515 if( res
!= EQUIP_ERR_OK
)
12517 SendEquipError( res
, NULL
, NULL
);
12527 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12529 uint16 log_slot
= FindQuestSlot( 0 );
12530 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12532 uint32 quest_id
= pQuest
->GetQuestId();
12534 // if not exist then created with set uState==NEW and rewarded=false
12535 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12537 // check for repeatable quests status reset
12538 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12539 questStatusData
.m_explored
= false;
12541 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12543 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12544 questStatusData
.m_itemcount
[i
] = 0;
12547 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12549 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12550 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12553 GiveQuestSourceItem( pQuest
);
12554 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12556 if( pQuest
->GetRepObjectiveFaction() )
12557 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12560 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12562 uint32 limittime
= pQuest
->GetLimitTime();
12564 // shared timed quest
12565 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12566 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12568 AddTimedQuest( quest_id
);
12569 questStatusData
.m_timer
= limittime
* 1000;
12570 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12573 questStatusData
.m_timer
= 0;
12575 SetQuestSlot(log_slot
, quest_id
, qtime
);
12577 if (questStatusData
.uState
!= QUEST_NEW
)
12578 questStatusData
.uState
= QUEST_CHANGED
;
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 q_status
.m_timer
= 0;
12810 if (q_status
.uState
!= QUEST_NEW
)
12811 q_status
.uState
= QUEST_CHANGED
;
12813 IncompleteQuest( quest_id
);
12815 uint16 log_slot
= FindQuestSlot( quest_id
);
12816 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12818 SetQuestSlotTimer(log_slot
, 1 );
12819 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12821 SendQuestTimerFailed( quest_id
);
12825 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12827 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12828 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12830 // skip zone zoneOrSort and 0 case skillOrClass
12831 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12834 int32 questSort
= -zoneOrSort
;
12835 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12837 // check class sort cases in zoneOrSort
12838 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12841 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12846 if( skillOrClass
< 0 )
12848 uint8 reqClass
= -int32(skillOrClass
);
12849 if(getClass() != reqClass
)
12852 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12857 else if( skillOrClass
> 0 )
12859 uint32 reqSkill
= skillOrClass
;
12860 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12863 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12871 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12873 if( getLevel() < qInfo
->GetMinLevel() )
12876 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12882 bool Player::SatisfyQuestLog( bool msg
)
12885 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12890 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12891 GetSession()->SendPacket( &data
);
12892 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12897 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12899 // No previous quest (might be first quest in a series)
12900 if( qInfo
->prevQuests
.empty())
12903 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12905 uint32 prevId
= abs(*iter
);
12907 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12908 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12910 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12912 // If any of the positive previous quests completed, return true
12913 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12915 // skip one-from-all exclusive group
12916 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12919 // each-from-all exclusive group ( < 0)
12920 // can be start if only all quests in prev quest exclusive group completed and rewarded
12921 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12922 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12924 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12926 for(; iter
!= end
; ++iter
)
12928 uint32 exclude_Id
= iter
->second
;
12930 // skip checked quest id, only state of other quests in group is interesting
12931 if(exclude_Id
== prevId
)
12934 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12936 // alternative quest from group also must be completed and rewarded(reported)
12937 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12940 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12946 // If any of the negative previous quests active, return true
12947 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12948 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12950 // skip one-from-all exclusive group
12951 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12954 // each-from-all exclusive group ( < 0)
12955 // can be start if only all quests in prev quest exclusive group active
12956 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12957 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12959 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12961 for(; iter
!= end
; ++iter
)
12963 uint32 exclude_Id
= iter
->second
;
12965 // skip checked quest id, only state of other quests in group is interesting
12966 if(exclude_Id
== prevId
)
12969 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12971 // alternative quest from group also must be active
12972 if( i_exstatus
== mQuestStatus
.end() ||
12973 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12974 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12977 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12986 // Has only positive prev. quests in non-rewarded state
12987 // and negative prev. quests in non-active state
12989 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12994 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12996 uint32 reqraces
= qInfo
->GetRequiredRaces();
12997 if ( reqraces
== 0 )
12999 if( (reqraces
& getRaceMask()) == 0 )
13002 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13008 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13010 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13011 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13014 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13018 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13019 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13022 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13029 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13031 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13032 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13035 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13041 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
13043 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
13046 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13052 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13054 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13055 if(qInfo
->GetExclusiveGroup() <= 0)
13058 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13059 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13061 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13063 for(; iter
!= end
; ++iter
)
13065 uint32 exclude_Id
= iter
->second
;
13067 // skip checked quest id, only state of other quests in group is interesting
13068 if(exclude_Id
== qInfo
->GetQuestId())
13071 // not allow have daily quest if daily quest from exclusive group already recently completed
13072 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13073 if( !SatisfyQuestDay(Nquest
, false) )
13076 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13080 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13082 // alternative quest already started or completed
13083 if( i_exstatus
!= mQuestStatus
.end()
13084 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13087 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13094 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13096 if(!qInfo
->GetNextQuestInChain())
13099 // next quest in chain already started or completed
13100 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13101 if( itr
!= mQuestStatus
.end()
13102 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13105 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13109 // check for all quests further up the chain
13110 // only necessary if there are quest chains with more than one quest that can be skipped
13111 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13115 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13117 // No previous quest in chain
13118 if( qInfo
->prevChainQuests
.empty())
13121 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13123 uint32 prevId
= *iter
;
13125 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13127 if( i_prevstatus
!= mQuestStatus
.end() )
13129 // If any of the previous quests in chain active, return false
13130 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13131 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13134 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13139 // check for all quests further down the chain
13140 // only necessary if there are quest chains with more than one quest that can be skipped
13141 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13145 // No previous quest in chain active
13149 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13151 if(!qInfo
->IsDaily())
13154 bool have_slot
= false;
13155 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13157 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13158 if(qInfo
->GetQuestId()==id
)
13168 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13175 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13177 uint32 srcitem
= pQuest
->GetSrcItemId();
13180 uint32 count
= pQuest
->GetSrcItemCount();
13184 ItemPosCountVec dest
;
13185 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13186 if( msg
== EQUIP_ERR_OK
)
13188 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13189 SendNewItem(item
, count
, true, false);
13192 // player already have max amount required item, just report success
13193 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13196 SendEquipError( msg
, NULL
, NULL
);
13203 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13205 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13208 uint32 srcitem
= qInfo
->GetSrcItemId();
13211 uint32 count
= qInfo
->GetSrcItemCount();
13215 // exist one case when destroy source quest item not possible:
13216 // non un-equippable item (equipped non-empty bag, for example)
13217 uint8 res
= CanUnequipItems(srcitem
,count
);
13218 if(res
!= EQUIP_ERR_OK
)
13221 SendEquipError( res
, NULL
, NULL
);
13225 DestroyItemCount(srcitem
, count
, true, true);
13231 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13233 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13236 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13237 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13238 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13239 && !qInfo
->IsRepeatable() )
13240 return itr
->second
.m_rewarded
;
13247 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13251 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13252 if( itr
!= mQuestStatus
.end() )
13253 return itr
->second
.m_status
;
13255 return QUEST_STATUS_NONE
;
13258 bool Player::CanShareQuest(uint32 quest_id
) const
13260 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13261 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13263 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13264 if( itr
!= mQuestStatus
.end() )
13265 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13270 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13272 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13275 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13277 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13278 m_timedquests
.erase(qInfo
->GetQuestId());
13281 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13283 q_status
.m_status
= status
;
13284 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13287 UpdateForQuestsGO();
13290 // not used in MaNGOS, but used in scripting code
13291 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13293 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13297 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13298 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13299 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13304 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13306 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13308 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13310 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13311 if( reqitemcount
!= 0 )
13313 uint32 quest_id
= pQuest
->GetQuestId();
13314 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13316 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13317 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.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
);
19459 uint32
Player::GetPhaseMaskForSpawn() const
19461 uint32 phase
= PHASEMASK_NORMAL
;
19462 if(!isGameMaster())
19463 phase
= GetPhaseMask();
19466 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19468 phase
= GetPhaseMask();
19470 phase
= phases
.front()->GetMiscValue();
19473 // some aura phases include 1 normal map in addition to phase itself
19474 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19477 return PHASEMASK_NORMAL
;