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
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
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
= 3*MINUTE
*1000; // default duration
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 is being 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 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2312 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2313 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2314 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2315 SetInt32Value(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 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2379 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2380 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2382 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2383 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2385 // restore if need some important flags
2386 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2388 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2389 _ApplyAllStatBonuses();
2391 // set current level health and mana/energy to maximum after applying all mods.
2392 SetHealth(GetMaxHealth());
2393 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2394 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2395 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2396 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2397 SetPower(POWER_FOCUS
, 0);
2398 SetPower(POWER_HAPPINESS
, 0);
2399 SetPower(POWER_RUNIC_POWER
, 0);
2402 void Player::SendInitialSpells()
2404 uint16 spellCount
= 0;
2406 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2409 size_t countPos
= data
.wpos();
2410 data
<< uint16(spellCount
); // spell count placeholder
2412 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2414 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2417 if(!itr
->second
->active
|| itr
->second
->disabled
)
2420 data
<< uint16(itr
->first
);
2421 data
<< uint16(0); // it's not slot id
2426 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2428 uint16 spellCooldowns
= m_spellCooldowns
.size();
2429 data
<< uint16(spellCooldowns
);
2430 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2432 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2436 data
<< uint16(itr
->first
);
2438 time_t cooldown
= 0;
2439 time_t curTime
= time(NULL
);
2440 if(itr
->second
.end
> curTime
)
2441 cooldown
= (itr
->second
.end
-curTime
)*1000;
2443 data
<< uint16(itr
->second
.itemid
); // cast item id
2444 data
<< uint16(sEntry
->Category
); // spell category
2445 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2447 data
<< uint32(0); // cooldown
2448 data
<< uint32(cooldown
); // category cooldown
2452 data
<< uint32(cooldown
); // cooldown
2453 data
<< uint32(0); // category cooldown
2457 GetSession()->SendPacket(&data
);
2459 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2462 void Player::RemoveMail(uint32 id
)
2464 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2466 if ((*itr
)->messageID
== id
)
2468 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2475 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2477 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2478 data
<< (uint32
) mailId
;
2479 data
<< (uint32
) mailAction
;
2480 data
<< (uint32
) mailError
;
2481 if ( mailError
== MAIL_ERR_BAG_FULL
)
2482 data
<< (uint32
) equipError
;
2483 else if( mailAction
== MAIL_ITEM_TAKEN
)
2485 data
<< (uint32
) item_guid
; // item guid low?
2486 data
<< (uint32
) item_count
; // item count?
2488 GetSession()->SendPacket(&data
);
2491 void Player::SendNewMail()
2493 // deliver undelivered mail
2494 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2496 GetSession()->SendPacket(&data
);
2499 void Player::UpdateNextMailTimeAndUnreads()
2501 // calculate next delivery time (min. from non-delivered mails
2502 // and recalculate unReadMail
2503 time_t cTime
= time(NULL
);
2504 m_nextMailDelivereTime
= 0;
2506 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2508 if((*itr
)->deliver_time
> cTime
)
2510 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2511 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2513 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2518 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2520 if(deliver_time
<= time(NULL
)) // ready now
2525 else // not ready and no have ready mails
2527 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2528 m_nextMailDelivereTime
= deliver_time
;
2532 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2534 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2537 // do character spell book cleanup (all characters)
2538 if(!IsInWorld() && !learning
) // spell load case
2540 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2541 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2544 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2549 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2551 // do character spell book cleanup (all characters)
2552 if(!IsInWorld() && !learning
) // spell load case
2554 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2555 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2558 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2563 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2565 bool dependent_set
= false;
2566 bool disabled_case
= false;
2567 bool superceded_old
= false;
2569 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2570 if (itr
!= m_spells
.end())
2572 uint32 next_active_spell_id
= 0;
2573 // fix activate state for non-stackable low rank (and find next spell for !active case)
2574 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2576 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2577 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2579 if(HasSpell(next_itr
->second
))
2581 // high rank already known so this must !active
2583 next_active_spell_id
= next_itr
->second
;
2589 // not do anything if already known in expected state
2590 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2591 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2593 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2594 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2599 // dependent spell known as not dependent, overwrite state
2600 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2602 itr
->second
->dependent
= dependent
;
2603 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2604 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2605 dependent_set
= true;
2608 // update active state for known spell
2609 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2611 itr
->second
->active
= active
;
2613 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2614 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2615 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2616 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2620 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2621 CastSpell (this,spell_id
,true);
2623 else if(IsInWorld())
2625 if(next_active_spell_id
)
2627 // update spell ranks in spellbook and action bar
2628 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2629 data
<< uint16(spell_id
);
2630 data
<< uint16(next_active_spell_id
);
2631 GetSession()->SendPacket( &data
);
2635 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2636 data
<< uint16(spell_id
);
2637 GetSession()->SendPacket(&data
);
2641 return active
; // learn (show in spell book if active now)
2644 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2646 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2647 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2648 itr
->second
->disabled
= disabled
;
2653 disabled_case
= true;
2655 else switch(itr
->second
->state
)
2657 case PLAYERSPELL_UNCHANGED
: // known saved spell
2659 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2662 m_spells
.erase(itr
);
2663 state
= PLAYERSPELL_CHANGED
;
2664 break; // need re-add
2666 default: // known not saved yet spell (new or modified)
2668 // can be in case spell loading but learned at some previous spell loading
2669 if(!IsInWorld() && !learning
&& !dependent_set
)
2670 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2677 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2679 // talent: unlearn all other talent ranks (high and low)
2680 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2682 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2684 for(int i
=0; i
<5; ++i
)
2686 // skip learning spell and no rank spell case
2687 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2688 if(!rankSpellId
|| rankSpellId
==spell_id
)
2691 removeSpell(rankSpellId
);
2695 // non talent spell: learn low ranks (recursive call)
2696 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2698 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2699 addSpell(prev_spell
,active
,true,true,disabled
);
2700 else // at normal learning
2701 learnSpell(prev_spell
,true);
2704 PlayerSpell
*newspell
= new PlayerSpell
;
2705 newspell
->state
= state
;
2706 newspell
->active
= active
;
2707 newspell
->dependent
= dependent
;
2708 newspell
->disabled
= disabled
;
2710 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2711 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2713 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2715 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2716 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2717 if(!i_spellInfo
) continue;
2719 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2721 if(itr
->second
->active
)
2723 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2725 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2727 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2728 data
<< uint16(itr
->first
);
2729 data
<< uint16(spell_id
);
2730 GetSession()->SendPacket( &data
);
2733 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2734 itr
->second
->active
= false;
2735 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2736 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2737 superceded_old
= true; // new spell replace old in action bars and spell book.
2739 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2741 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2743 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2744 data
<< uint16(spell_id
);
2745 data
<< uint16(itr
->first
);
2746 GetSession()->SendPacket( &data
);
2749 // mark new spell as disable (not learned yet for client and will not learned)
2750 newspell
->active
= false;
2751 if(newspell
->state
!= PLAYERSPELL_NEW
)
2752 newspell
->state
= PLAYERSPELL_CHANGED
;
2759 m_spells
[spell_id
] = newspell
;
2761 // return false if spell disabled
2762 if (newspell
->disabled
)
2766 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2768 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2769 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2770 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2772 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2773 CastSpell(this, spell_id
, true);
2775 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2776 else if (IsPassiveSpell(spell_id
))
2778 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2779 CastSpell(this, spell_id
, true);
2781 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2783 CastSpell(this, spell_id
, true);
2787 // update used talent points count
2788 m_usedTalentCount
+= talentCost
;
2790 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2791 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2793 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2794 SetFreePrimaryProffesions(freeProfs
-1);
2797 // add dependent skills
2798 uint16 maxskill
= GetMaxSkillValueForLevel();
2800 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2804 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2805 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2807 if(skill_value
< spellLearnSkill
->value
)
2808 skill_value
= spellLearnSkill
->value
;
2810 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2812 if(skill_max_value
< new_skill_max_value
)
2813 skill_max_value
= new_skill_max_value
;
2815 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2819 // not ranked skills
2820 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2821 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2823 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2825 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2829 if(HasSkill(pSkill
->id
))
2832 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2833 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2834 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2836 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2838 case SKILL_RANGE_LANGUAGE
:
2839 SetSkill(pSkill
->id
, 300, 300 );
2841 case SKILL_RANGE_LEVEL
:
2842 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2844 case SKILL_RANGE_MONO
:
2845 SetSkill(pSkill
->id
, 1, 1 );
2854 // learn dependent spells
2855 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2856 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2858 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2860 if(!itr
->second
.autoLearned
)
2862 if(!IsInWorld() || !itr
->second
.active
) // at spells loading, no output, but allow save
2863 addSpell(itr
->second
.spell
,itr
->second
.active
,true,true,false);
2864 else // at normal learning
2865 learnSpell(itr
->second
.spell
,true);
2871 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
);
2872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
);
2875 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2876 return active
&& !disabled
&& !superceded_old
;
2879 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2881 bool need_cast
= false;
2883 switch(spellInfo
->Id
)
2885 // some spells not have stance data expacted cast at form change or present
2886 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2887 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2888 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2889 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2890 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2891 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2892 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2893 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2894 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2895 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2896 // another spells have proper stance data
2897 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2900 //Check CasterAuraStates
2901 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
2904 void Player::learnSpell(uint32 spell_id
, bool dependent
)
2906 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2908 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2909 bool active
= disabled
? itr
->second
->active
: true;
2911 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
2913 // learn all disabled higher ranks (recursive)
2916 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2917 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2919 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2920 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
2921 learnSpell(i
->second
,false);
2925 // prevent duplicated entires in spell book, also not send if not in world (loading)
2926 if(!learning
|| !IsInWorld ())
2929 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2930 data
<< uint32(spell_id
);
2931 GetSession()->SendPacket(&data
);
2934 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
2936 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2937 if (itr
== m_spells
.end())
2940 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2943 // unlearn non talent higher ranks (recursive)
2944 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2945 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2946 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2947 removeSpell(itr2
->second
,disabled
);
2949 bool cur_active
= itr
->second
->active
;
2950 bool cur_dependent
= itr
->second
->dependent
;
2954 itr
->second
->disabled
= disabled
;
2955 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2956 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2960 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2963 m_spells
.erase(itr
);
2966 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2969 RemoveAurasDueToSpell(spell_id
);
2972 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2973 RemovePetAura(petSpell
);
2975 // free talent points
2976 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2979 if(talentCosts
< m_usedTalentCount
)
2980 m_usedTalentCount
-= talentCosts
;
2982 m_usedTalentCount
= 0;
2985 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2986 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2988 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2989 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2990 SetFreePrimaryProffesions(freeProfs
);
2993 // remove dependent skill
2994 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2997 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2998 if(!prev_spell
) // first rank, remove skill
2999 SetSkill(spellLearnSkill
->skill
,0,0);
3002 // search prev. skill setting by spell ranks chain
3003 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3004 while(!prevSkill
&& prev_spell
)
3006 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3007 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3010 if(!prevSkill
) // not found prev skill setting, remove skill
3011 SetSkill(spellLearnSkill
->skill
,0,0);
3012 else // set to prev. skill setting values
3014 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3015 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3017 if(skill_value
> prevSkill
->value
)
3018 skill_value
= prevSkill
->value
;
3020 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3022 if(skill_max_value
> new_skill_max_value
)
3023 skill_max_value
= new_skill_max_value
;
3025 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3032 // not ranked skills
3033 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3034 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3036 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3038 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3042 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3043 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3044 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
3046 // not reset skills for professions and racial abilities
3047 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3048 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3051 SetSkill(pSkill
->id
, 0, 0 );
3056 // remove dependent spells
3057 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3058 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3060 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3061 removeSpell(itr2
->second
.spell
, disabled
);
3063 // activate lesser rank in spellbook/action bar, and cast it if need
3064 bool prev_activate
= false;
3066 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3068 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3070 // if talent then lesser rank also talent and need learn
3072 learnSpell (prev_id
,false);
3073 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3074 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3076 // need manually update dependence state (learn spell ignore like attempts)
3077 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3078 if (prev_itr
!= m_spells
.end())
3080 if(prev_itr
->second
->dependent
!= cur_dependent
)
3082 prev_itr
->second
->dependent
= cur_dependent
;
3083 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3084 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3087 // now re-learn if need re-activate
3088 if(cur_active
&& !prev_itr
->second
->active
)
3090 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3092 if(update_action_bar_for_low_rank
)
3094 // downgrade spell ranks in spellbook and action bar
3095 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3096 data
<< uint16(spell_id
);
3097 data
<< uint16(prev_id
);
3098 GetSession()->SendPacket( &data
);
3099 prev_activate
= true;
3107 // remove from spell book if not replaced by lesser rank
3110 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3111 data
<< uint16(spell_id
);
3112 GetSession()->SendPacket(&data
);
3116 void Player::RemoveArenaSpellCooldowns()
3118 // remove cooldowns on spells that has < 15 min CD
3119 SpellCooldowns::iterator itr
, next
;
3120 // iterate spell cooldowns
3121 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3125 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3126 // check if spellentry is present and if the cooldown is less than 15 mins
3128 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
3129 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
3132 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3133 data
<< uint32(itr
->first
);
3135 GetSession()->SendPacket(&data
);
3137 m_spellCooldowns
.erase(itr
);
3142 void Player::RemoveAllSpellCooldown()
3144 if(!m_spellCooldowns
.empty())
3146 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3148 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3149 data
<< uint32(itr
->first
);
3150 data
<< uint64(GetGUID());
3151 GetSession()->SendPacket(&data
);
3153 m_spellCooldowns
.clear();
3157 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3159 m_spellCooldowns
.clear();
3161 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3165 time_t curTime
= time(NULL
);
3169 Field
*fields
= result
->Fetch();
3171 uint32 spell_id
= fields
[0].GetUInt32();
3172 uint32 item_id
= fields
[1].GetUInt32();
3173 time_t db_time
= (time_t)fields
[2].GetUInt64();
3175 if(!sSpellStore
.LookupEntry(spell_id
))
3177 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3181 // skip outdated cooldown
3182 if(db_time
<= curTime
)
3185 AddSpellCooldown(spell_id
, item_id
, db_time
);
3187 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3189 while( result
->NextRow() );
3195 void Player::_SaveSpellCooldowns()
3197 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3199 time_t curTime
= time(NULL
);
3201 // remove outdated and save active
3202 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3204 if(itr
->second
.end
<= curTime
)
3205 m_spellCooldowns
.erase(itr
++);
3208 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
));
3214 uint32
Player::resetTalentsCost() const
3216 // The first time reset costs 1 gold
3217 if(m_resetTalentsCost
< 1*GOLD
)
3220 else if(m_resetTalentsCost
< 5*GOLD
)
3222 // After that it increases in increments of 5 gold
3223 else if(m_resetTalentsCost
< 10*GOLD
)
3227 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3230 // This cost will be reduced by a rate of 5 gold per month
3231 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3232 // to a minimum of 10 gold.
3233 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3237 // After that it increases in increments of 5 gold
3238 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3239 // until it hits a cap of 50 gold.
3240 if(new_cost
> 50*GOLD
)
3247 bool Player::resetTalents(bool no_cost
)
3249 // not need after this call
3250 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3252 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3253 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3256 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3258 if (m_usedTalentCount
== 0)
3260 SetFreeTalentPoints(talentPointsForLevel
);
3268 cost
= resetTalentsCost();
3270 if (GetMoney() < cost
)
3272 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3277 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3279 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3281 if (!talentInfo
) continue;
3283 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3288 // unlearn only talents for character class
3289 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3290 // to prevent unexpected lost normal learned spell skip another class talents
3291 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3294 for (int j
= 0; j
< 5; j
++)
3296 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3298 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3304 // remove learned spells (all ranks)
3305 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3307 // unlearn if first rank is talent or learned by talent
3308 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3310 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3311 itr
= GetSpellMap().begin();
3320 SetFreeTalentPoints(talentPointsForLevel
);
3324 ModifyMoney(-(int32
)cost
);
3326 m_resetTalentsCost
= cost
;
3327 m_resetTalentsTime
= time(NULL
);
3330 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3331 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3336 Mail
* Player::GetMail(uint32 id
)
3338 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3340 if ((*itr
)->messageID
== id
)
3348 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3352 Object::_SetCreateBits(updateMask
, target
);
3356 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3358 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3359 updateMask
->SetBit(index
);
3364 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3368 Object::_SetUpdateBits(updateMask
, target
);
3372 Object::_SetUpdateBits(updateMask
, target
);
3373 *updateMask
&= updateVisualBits
;
3377 void Player::InitVisibleBits()
3379 updateVisualBits
.SetCount(PLAYER_END
);
3381 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3382 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3383 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3384 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3385 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3386 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3387 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3388 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3389 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3390 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3391 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3392 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3393 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3394 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3395 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3396 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3397 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3398 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3399 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3400 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3401 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3402 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3403 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3404 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3405 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3406 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3407 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3408 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3409 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3410 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3411 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3412 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3413 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3414 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3415 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3416 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3417 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3418 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3419 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3420 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3421 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3422 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3423 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3424 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3425 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3426 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3427 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3428 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3429 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3430 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3431 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3432 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3433 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3434 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3435 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3437 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3438 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3439 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3440 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3441 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3442 updateVisualBits
.SetBit(PLAYER_BYTES
);
3443 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3444 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3445 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3446 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3448 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3449 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3450 updateVisualBits
.SetBit(i
);
3452 // Players visible items are not inventory stuff
3453 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3455 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3458 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3459 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3462 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3464 // item enchantments
3465 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3466 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3468 // random properties
3469 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3470 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3471 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3474 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3477 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3479 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3481 if(m_items
[i
] == NULL
)
3484 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3489 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3491 if(m_items
[i
] == NULL
)
3494 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3496 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3498 if(m_items
[i
] == NULL
)
3501 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3505 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3508 void Player::DestroyForPlayer( Player
*target
) const
3510 Unit::DestroyForPlayer( target
);
3512 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3514 if(m_items
[i
] == NULL
)
3517 m_items
[i
]->DestroyForPlayer( target
);
3522 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3524 if(m_items
[i
] == NULL
)
3527 m_items
[i
]->DestroyForPlayer( target
);
3529 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3531 if(m_items
[i
] == NULL
)
3534 m_items
[i
]->DestroyForPlayer( target
);
3539 bool Player::HasSpell(uint32 spell
) const
3541 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3542 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3543 !itr
->second
->disabled
);
3546 bool Player::HasActiveSpell(uint32 spell
) const
3548 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3549 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3550 itr
->second
->active
&& !itr
->second
->disabled
);
3553 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3556 return TRAINER_SPELL_RED
;
3558 if (!trainer_spell
->learnedSpell
)
3559 return TRAINER_SPELL_RED
;
3562 if(HasSpell(trainer_spell
->learnedSpell
))
3563 return TRAINER_SPELL_GRAY
;
3565 // check race/class requirement
3566 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3567 return TRAINER_SPELL_RED
;
3569 // check level requirement
3570 if(getLevel() < trainer_spell
->reqLevel
)
3571 return TRAINER_SPELL_RED
;
3573 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3575 // check prev.rank requirement
3576 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3577 return TRAINER_SPELL_RED
;
3579 // check additional spell requirement
3580 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3581 return TRAINER_SPELL_RED
;
3584 // check skill requirement
3585 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3586 return TRAINER_SPELL_RED
;
3588 // exist, already checked at loading
3589 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3591 // secondary prof. or not prof. spell
3592 uint32 skill
= spell
->EffectMiscValue
[1];
3594 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3595 return TRAINER_SPELL_GREEN
;
3597 // check primary prof. limit
3598 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3599 return TRAINER_SPELL_RED
;
3601 return TRAINER_SPELL_GREEN
;
3604 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3606 uint32 guid
= GUID_LOPART(playerguid
);
3608 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3609 // bones will be deleted by corpse/bones deleting thread shortly
3610 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3612 // remove from guild
3613 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3616 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3618 guild
->DelMember(guid
);
3621 // remove from arena teams
3622 LeaveAllArenaTeams(playerguid
);
3624 // the player was uninvited already on logout so just remove from group
3625 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3628 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3630 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3633 RemoveFromGroup(group
, playerguid
);
3637 // remove signs from petitions (also remove petitions if owner);
3638 RemovePetitionsAndSigns(playerguid
, 10);
3640 // return back all mails with COD and Item 0 1 2 3 4 5 6
3641 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
);
3646 Field
*fields
= resultMail
->Fetch();
3648 uint32 mail_id
= fields
[0].GetUInt32();
3649 uint16 mailTemplateId
= fields
[1].GetUInt16();
3650 uint32 sender
= fields
[2].GetUInt32();
3651 std::string subject
= fields
[3].GetCppString();
3652 uint32 itemTextId
= fields
[4].GetUInt32();
3653 uint32 money
= fields
[5].GetUInt32();
3654 bool has_items
= fields
[6].GetBool();
3656 //we can return mail now
3657 //so firstly delete the old one
3658 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3663 // data needs to be at first place for Item::LoadFromDB
3664 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
);
3669 Field
*fields2
= resultItems
->Fetch();
3671 uint32 item_guidlow
= fields2
[1].GetUInt32();
3672 uint32 item_template
= fields2
[2].GetUInt32();
3674 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3677 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3681 Item
*pItem
= NewItemOrBag(itemProto
);
3682 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3684 pItem
->FSetState(ITEM_REMOVED
);
3685 pItem
->SaveToDB(); // it also deletes item object !
3689 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3691 while (resultItems
->NextRow());
3697 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3699 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3701 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3703 while (resultMail
->NextRow());
3708 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3709 // Get guids of character's pets, will deleted in transaction
3710 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3712 // NOW we can finally clear other DB data related to character
3713 CharacterDatabase
.BeginTransaction();
3718 Field
*fields3
= resultPets
->Fetch();
3719 uint32 petguidlow
= fields3
[0].GetUInt32();
3720 Pet::DeleteFromDB(petguidlow
);
3721 } while (resultPets
->NextRow());
3725 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3726 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3727 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3728 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3729 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3730 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3731 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3732 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3733 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3734 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3735 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3736 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3737 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3738 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3739 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3740 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3741 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3742 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3743 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3744 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3745 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3746 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3747 CharacterDatabase
.CommitTransaction();
3749 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3750 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3753 void Player::SetMovement(PlayerMovementType pType
)
3758 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3759 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3760 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3761 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3763 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3766 data
.append(GetPackGUID());
3768 GetSession()->SendPacket( &data
);
3772 - a resurrectable corpse must not be loaded for the player (only bones)
3773 - the player must be in world
3775 void Player::BuildPlayerRepop()
3777 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3778 data
.append(GetPackGUID());
3779 GetSession()->SendPacket(&data
);
3781 if(getRace() == RACE_NIGHTELF
)
3782 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)
3783 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3785 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3786 // there must be SMSG.STOP_MIRROR_TIMER
3787 // there we must send 888 opcode
3789 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3792 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3796 // create a corpse and place it at the player's location
3798 Corpse
*corpse
= GetCorpse();
3801 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3804 GetMap()->Add(corpse
);
3806 // convert player body to ghost
3809 SetMovement(MOVE_WATER_WALK
);
3810 if(!GetSession()->isLogingOut())
3811 SetMovement(MOVE_UNROOT
);
3813 // BG - remove insignia related
3814 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3816 SendCorpseReclaimDelay();
3818 // to prevent cheating
3819 corpse
->ResetGhostTime();
3821 StopMirrorTimers(); //disable timers(bars)
3823 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3825 // set and clear other
3826 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3829 void Player::SendDelayResponse(const uint32 ml_seconds
)
3831 //FIXME: is this delay time arg really need? 50msec by default in code
3832 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3833 data
<< (uint32
)time(NULL
);
3835 GetSession()->SendPacket( &data
);
3838 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3840 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3845 GetSession()->SendPacket(&data
);
3847 // speed change, land walk
3849 // remove death flag + set aura
3850 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3851 if(getRace() == RACE_NIGHTELF
)
3852 RemoveAurasDueToSpell(20584); // speed bonuses
3853 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3855 setDeathState(ALIVE
);
3857 SetMovement(MOVE_LAND_WALK
);
3858 SetMovement(MOVE_UNROOT
);
3862 // set health/powers (0- will be set in caller)
3863 if(restore_percent
>0.0f
)
3865 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3866 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3867 SetPower(POWER_RAGE
, 0);
3868 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3871 // update visibility
3872 ObjectAccessor::UpdateVisibilityForPlayer(this);
3874 // some items limited to specific map
3875 DestroyZoneLimitedItem( true, GetZoneId());
3880 //Characters from level 1-10 are not affected by resurrection sickness.
3881 //Characters from level 11-19 will suffer from one minute of sickness
3882 //for each level they are above 10.
3883 //Characters level 20 and up suffer from ten minutes of sickness.
3884 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3886 if(int32(getLevel()) >= startLevel
)
3888 // set resurrection sickness
3889 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3891 // not full duration
3892 if(int32(getLevel()) < startLevel
+9)
3894 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3896 for(int i
=0; i
< 3; ++i
)
3898 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3900 Aur
->SetAuraDuration(delta
*1000);
3901 Aur
->SendAuraUpdate(false);
3908 void Player::KillPlayer()
3910 SetMovement(MOVE_ROOT
);
3912 StopMirrorTimers(); //disable timers(bars)
3914 setDeathState(CORPSE
);
3915 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3917 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3918 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3920 // 6 minutes until repop at graveyard
3921 m_deathTimer
= 6*MINUTE
*1000;
3923 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3925 // don't create corpse at this moment, player might be falling
3927 // update visibility
3928 ObjectAccessor::UpdateObjectVisibility(this);
3931 void Player::CreateCorpse()
3933 // prevent existence 2 corpse for player
3936 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3938 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3941 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
3947 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3948 _pb
= GetUInt32Value(PLAYER_BYTES
);
3949 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3951 uint8 race
= (uint8
)(_uf
);
3952 uint8 skin
= (uint8
)(_pb
);
3953 uint8 face
= (uint8
)(_pb
>> 8);
3954 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3955 uint8 haircolor
= (uint8
)(_pb
>> 24);
3956 uint8 facialhair
= (uint8
)(_pb2
);
3958 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3959 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3961 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3962 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3964 uint32 flags
= CORPSE_FLAG_UNK2
;
3965 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3966 flags
|= CORPSE_FLAG_HIDE_HELM
;
3967 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3968 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3969 if(InBattleGround())
3970 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3971 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3973 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3975 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3978 uint16 iIventoryType
;
3980 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3984 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3985 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3987 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3988 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3992 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3993 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3995 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3998 // register for player, but not show
3999 ObjectAccessor::Instance().AddCorpse(corpse
);
4002 void Player::SpawnCorpseBones()
4004 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4005 SaveToDB(); // prevent loading as ghost without corpse
4008 Corpse
* Player::GetCorpse() const
4010 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4013 void Player::DurabilityLossAll(double percent
, bool inventory
)
4015 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4016 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4017 DurabilityLoss(pItem
,percent
);
4021 // bags not have durability
4022 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4024 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4025 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4026 DurabilityLoss(pItem
,percent
);
4028 // keys not have durability
4029 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4031 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4032 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4033 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4034 if(Item
* pItem
= GetItemByPos( i
, j
))
4035 DurabilityLoss(pItem
,percent
);
4039 void Player::DurabilityLoss(Item
* item
, double percent
)
4044 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4049 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4051 if(pDurabilityLoss
< 1 )
4052 pDurabilityLoss
= 1;
4054 DurabilityPointsLoss(item
,pDurabilityLoss
);
4057 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4059 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4060 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4061 DurabilityPointsLoss(pItem
,points
);
4065 // bags not have durability
4066 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4068 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4069 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4070 DurabilityPointsLoss(pItem
,points
);
4072 // keys not have durability
4073 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4075 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4076 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4077 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4078 if(Item
* pItem
= GetItemByPos( i
, j
))
4079 DurabilityPointsLoss(pItem
,points
);
4083 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4085 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4086 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4087 int32 pNewDurability
= pOldDurability
- points
;
4089 if (pNewDurability
< 0)
4091 else if (pNewDurability
> pMaxDurability
)
4092 pNewDurability
= pMaxDurability
;
4094 if (pOldDurability
!= pNewDurability
)
4096 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4097 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4098 _ApplyItemMods(item
,item
->GetSlot(), false);
4100 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4102 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4103 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4104 _ApplyItemMods(item
,item
->GetSlot(), true);
4106 item
->SetState(ITEM_CHANGED
, this);
4110 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4112 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4113 DurabilityPointsLoss(pItem
,1);
4116 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4118 uint32 TotalCost
= 0;
4119 // equipped, backpack, bags itself
4120 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4121 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4123 // bank, buyback and keys not repaired
4125 // items in inventory bags
4126 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4127 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4128 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4132 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4134 Item
* item
= GetItemByPos(pos
);
4136 uint32 TotalCost
= 0;
4140 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4144 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4148 uint32 LostDurability
= maxDurability
- curDurability
;
4149 if(LostDurability
>0)
4151 ItemPrototype
const *ditemProto
= item
->GetProto();
4153 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4156 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4160 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4161 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4162 if(!dQualitymodEntry
)
4164 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4168 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4169 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4171 costs
= uint32(costs
* discountMod
);
4173 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4178 if (GetGuildId()==0)
4180 DEBUG_LOG("You are not member of a guild");
4184 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4188 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4190 DEBUG_LOG("You do not have rights to withdraw for repairs");
4194 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4196 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4200 if (pGuild
->GetGuildBankMoney() < costs
)
4202 DEBUG_LOG("There is not enough money in bank");
4206 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4209 else if (GetMoney() < costs
)
4211 DEBUG_LOG("You do not have enough money");
4215 ModifyMoney( -int32(costs
) );
4219 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4220 item
->SetState(ITEM_CHANGED
, this);
4222 // reapply mods for total broken and repaired item if equipped
4223 if(IsEquipmentPos(pos
) && !curDurability
)
4224 _ApplyItemMods(item
,pos
& 255, true);
4228 void Player::RepopAtGraveyard()
4230 // note: this can be called also when the player is alive
4231 // for example from WorldSession::HandleMovementOpcodes
4233 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4235 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4236 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4238 ResurrectPlayer(0.5f
);
4242 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4244 // Special handle for battleground maps
4245 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4247 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4248 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4250 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4252 // stop countdown until repop
4255 // if no grave found, stay at the current location
4256 // and don't show spirit healer location
4259 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4260 if(isDead()) // not send if alive, because it used in TeleportTo()
4262 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4263 data
<< ClosestGrave
->map_id
;
4264 data
<< ClosestGrave
->x
;
4265 data
<< ClosestGrave
->y
;
4266 data
<< ClosestGrave
->z
;
4267 GetSession()->SendPacket(&data
);
4272 void Player::JoinedChannel(Channel
*c
)
4274 m_channels
.push_back(c
);
4277 void Player::LeftChannel(Channel
*c
)
4279 m_channels
.remove(c
);
4282 void Player::CleanupChannels()
4284 while(!m_channels
.empty())
4286 Channel
* ch
= *m_channels
.begin();
4287 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4288 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4289 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4290 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4293 sLog
.outDebug("Player: channels cleaned up!");
4296 void Player::UpdateLocalChannels(uint32 newZone
)
4298 if(m_channels
.empty())
4301 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4305 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4309 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4311 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4315 // skip non built-in channels
4316 if(!(*i
)->IsConstant())
4319 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4323 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4327 char new_channel_name_buf
[100];
4328 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4329 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4331 if((*i
)!=new_channel
)
4333 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4335 // leave old channel
4336 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4337 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4338 LeftChannel(*i
); // remove from player's channel list
4339 cMgr
->LeftChannel(name
); // delete if empty
4342 sLog
.outDebug("Player: channels cleaned up!");
4345 void Player::LeaveLFGChannel()
4347 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4351 (*i
)->Leave(GetGUID());
4357 void Player::UpdateDefense()
4359 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4361 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4363 // update dependent from defense skill part
4364 UpdateDefenseBonusesMod();
4368 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4370 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4372 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4381 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4384 if(amount
<= -100.0f
)
4387 val
= (100.0f
+ amount
) / 100.0f
;
4388 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4392 if(!CanModifyStats())
4397 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4398 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4399 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4400 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4405 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4407 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4409 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4413 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4416 return m_auraBaseMod
[modGroup
][modType
];
4419 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4421 if(modGroup
>= BASEMOD_END
)
4423 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4427 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4430 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4433 uint32
Player::GetShieldBlockValue() const
4435 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4437 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
) * 0.5f
- 10;
4439 value
= (value
< 0) ? 0 : value
;
4441 return uint32(value
);
4444 float Player::GetMeleeCritFromAgility()
4446 uint32 level
= getLevel();
4447 uint32 pclass
= getClass();
4449 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4451 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4452 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4453 if (critBase
==NULL
|| critRatio
==NULL
)
4456 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4460 float Player::GetDodgeFromAgility()
4462 // Table for base dodge values
4463 float dodge_base
[MAX_CLASSES
] = {
4465 0.00652f
, // Paladin
4472 0.02011f
, // Warlock
4476 // Crit/agility to dodge/agility coefficient multipliers
4477 float crit_to_dodge
[MAX_CLASSES
] = {
4491 uint32 level
= getLevel();
4492 uint32 pclass
= getClass();
4494 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4496 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4497 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4498 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4501 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4502 return dodge
*100.0f
;
4505 float Player::GetSpellCritFromIntellect()
4507 uint32 level
= getLevel();
4508 uint32 pclass
= getClass();
4510 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4512 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4513 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4514 if (critBase
==NULL
|| critRatio
==NULL
)
4517 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4521 float Player::GetRatingCoefficient(CombatRating cr
) const
4523 uint32 level
= getLevel();
4525 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4527 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4529 return 1.0f
; // By default use minimum coefficient (not must be called)
4531 return Rating
->ratio
;
4534 float Player::GetRatingBonusValue(CombatRating cr
) const
4536 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4539 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4541 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4542 if (melee
>25.0f
) melee
= 25.0f
;
4543 return uint32 (melee
* damage
/100.0f
);
4546 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4548 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4549 if (ranged
>25.0f
) ranged
=25.0f
;
4550 return uint32 (ranged
* damage
/100.0f
);
4553 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4555 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4556 // In wow script resilience limited to 25%
4559 return uint32 (spell
* damage
/ 100.0f
);
4562 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4564 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4565 // Dot resilience not limited (limit it by 100%)
4566 if (spellDot
> 100.0f
)
4568 return uint32 (spellDot
* damage
/ 100.0f
);
4571 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4576 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4578 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4585 float Player::OCTRegenHPPerSpirit()
4587 uint32 level
= getLevel();
4588 uint32 pclass
= getClass();
4590 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4592 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4593 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4594 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4597 // Formula from PaperDollFrame script
4598 float spirit
= GetStat(STAT_SPIRIT
);
4599 float baseSpirit
= spirit
;
4600 if (baseSpirit
>50) baseSpirit
= 50;
4601 float moreSpirit
= spirit
- baseSpirit
;
4602 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4606 float Player::OCTRegenMPPerSpirit()
4608 uint32 level
= getLevel();
4609 uint32 pclass
= getClass();
4611 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4613 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4614 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4615 if (moreRatio
==NULL
)
4618 // Formula get from PaperDollFrame script
4619 float spirit
= GetStat(STAT_SPIRIT
);
4620 float regen
= spirit
* moreRatio
->ratio
;
4624 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4626 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4628 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4629 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4630 // stat used stored in miscValueB for this aura
4631 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4632 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4633 if ((*i
)->GetMiscValue() & (1<<cr
))
4634 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4637 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4639 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4640 float RatingChange
= 0.0f
;
4642 bool affectStats
= CanModifyStats();
4646 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4647 case CR_DEFENSE_SKILL
:
4648 UpdateDefenseBonusesMod();
4651 UpdateDodgePercentage();
4654 UpdateParryPercentage();
4657 UpdateBlockPercentage();
4660 UpdateMeleeHitChances();
4663 UpdateRangedHitChances();
4666 UpdateSpellHitChances();
4671 UpdateCritPercentage(BASE_ATTACK
);
4672 UpdateCritPercentage(OFF_ATTACK
);
4675 case CR_CRIT_RANGED
:
4677 UpdateCritPercentage(RANGED_ATTACK
);
4681 UpdateAllSpellCritChances();
4683 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4684 case CR_HIT_TAKEN_RANGED
:
4686 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4688 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4689 case CR_CRIT_TAKEN_RANGED
:
4691 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4693 case CR_HASTE_MELEE
:
4694 RatingChange
= value
/ RatingCoeffecient
;
4695 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4696 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4698 case CR_HASTE_RANGED
:
4699 RatingChange
= value
/ RatingCoeffecient
;
4700 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4702 case CR_HASTE_SPELL
:
4703 RatingChange
= value
/ RatingCoeffecient
;
4704 ApplyCastTimePercentMod(RatingChange
,apply
);
4706 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4707 case CR_WEAPON_SKILL_OFFHAND
:
4708 case CR_WEAPON_SKILL_RANGED
:
4713 UpdateExpertise(BASE_ATTACK
);
4714 UpdateExpertise(OFF_ATTACK
);
4720 void Player::SetRegularAttackTime()
4722 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4724 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4725 if(tmpitem
&& !tmpitem
->IsBroken())
4727 ItemPrototype
const *proto
= tmpitem
->GetProto();
4729 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4731 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4736 //skill+step, checking for max value
4737 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4743 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4744 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4747 if(i
>=PLAYER_MAX_SKILLS
)
4750 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4751 uint32 value
= SKILL_VALUE(data
);
4752 uint32 max
= SKILL_MAX(data
);
4754 if ((!max
) || (!value
) || (value
>= max
))
4757 if (value
*512 < max
*urand(0,512))
4759 uint32 new_value
= value
+step
;
4763 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4764 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4771 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4773 if ( SkillValue
>= GrayLevel
)
4774 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4775 if ( SkillValue
>= GreenLevel
)
4776 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4777 if ( SkillValue
>= YellowLevel
)
4778 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4779 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4782 bool Player::UpdateCraftSkill(uint32 spellid
)
4784 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4786 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4787 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4789 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4791 if(_spell_idx
->second
->skillId
)
4793 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4795 // Alchemy Discoveries here
4796 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4797 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4799 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4800 learnSpell(discoveredSpell
,false);
4803 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4805 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4806 _spell_idx
->second
->max_value
,
4807 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4808 _spell_idx
->second
->min_value
),
4815 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4817 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4819 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4821 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4824 case SKILL_HERBALISM
:
4825 case SKILL_LOCKPICKING
:
4826 case SKILL_JEWELCRAFTING
:
4827 case SKILL_INSCRIPTION
:
4828 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4829 case SKILL_SKINNING
:
4830 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4831 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4833 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4835 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4836 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4838 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4843 bool Player::UpdateFishingSkill()
4845 sLog
.outDebug("UpdateFishingSkill");
4847 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4849 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4851 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4853 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4856 // levels sync. with spell requirement for skill levels to learn
4857 // bonus abilities in sSkillLineAbilityStore
4858 // Used only to avoid scan DBC at each skill grow
4859 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4861 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4863 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4867 if(Chance
<= 0) // speedup in 0 chance case
4869 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4874 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4875 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4876 if ( i
>= PLAYER_MAX_SKILLS
)
4879 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4880 uint16 SkillValue
= SKILL_VALUE(data
);
4881 uint16 MaxValue
= SKILL_MAX(data
);
4883 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4886 int32 Roll
= irand(1,1000);
4888 if ( Roll
<= Chance
)
4890 uint32 new_value
= SkillValue
+step
;
4891 if(new_value
> MaxValue
)
4892 new_value
= MaxValue
;
4894 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4895 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
4897 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
4899 learnSkillRewardedSpells( SkillId
, new_value
);
4903 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4904 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4908 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4912 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4914 // no skill gain in pvp
4915 Unit
*pVictim
= getVictim();
4916 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4920 return; // always maximized SKILL_FERAL_COMBAT in fact
4922 if(m_form
== FORM_TREE
)
4923 return; // use weapon but not skill up
4925 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4931 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4934 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4935 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4936 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4942 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4944 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4948 UpdateAllCritPercentages();
4951 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
4953 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4954 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4955 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4956 if(moblevel
< greylevel
)
4959 if (moblevel
> plevel
+ 5)
4960 moblevel
= plevel
+ 5;
4962 uint32 lvldif
= moblevel
- greylevel
;
4966 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4970 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4973 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4974 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4977 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4979 if(roll_chance_f(chance
))
4984 UpdateWeaponSkill(attType
);
4990 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4992 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4993 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4995 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4996 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4997 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4999 if(talent
) // permanent bonus stored in high part
5000 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5001 else // temporary/item bonus stored in low part
5002 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5007 void Player::UpdateSkillsForLevel()
5009 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5010 uint32 maxSkill
= GetMaxSkillValueForLevel();
5012 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5014 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5015 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5017 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5019 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5023 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5026 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5027 uint32 max
= SKILL_MAX(data
);
5028 uint32 val
= SKILL_VALUE(data
);
5030 /// update only level dependent max skill values
5033 /// miximize skill always
5035 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5036 /// update max skill value if current max skill not maximized
5037 else if(max
!= maxconfskill
)
5038 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5043 void Player::UpdateSkillsToMaxSkillsForLevel()
5045 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5046 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5048 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5049 if( IsProfessionOrRidingSkill(pskill
))
5051 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5053 uint32 max
= SKILL_MAX(data
);
5056 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5058 if(pskill
== SKILL_DEFENSE
)
5059 UpdateDefenseBonusesMod();
5063 // This functions sets a skill line value (and adds if doesn't exist yet)
5064 // To "remove" a skill line, set it's values to zero
5065 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5071 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5072 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5074 if(i
<PLAYER_MAX_SKILLS
) //has skill
5078 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5079 learnSkillRewardedSpells(id
, currVal
);
5080 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5084 // clear skill fields
5085 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5086 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5087 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5089 // remove all spells that related to this skill
5090 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5091 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5092 if (pAbility
->skillId
==id
)
5093 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5096 else if(currVal
) //add
5098 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5099 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5101 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5104 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5107 // enable unlearn button for primary professions only
5108 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5109 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5111 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5112 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5113 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5115 // apply skill bonuses
5116 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5118 // temporary bonuses
5119 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5120 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5121 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5122 (*i
)->ApplyModifier(true);
5124 // permanent bonuses
5125 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5126 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5127 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5128 (*i
)->ApplyModifier(true);
5130 // Learn all spells for skill
5131 learnSkillRewardedSpells(id
, currVal
);
5137 bool Player::HasSkill(uint32 skill
) const
5139 if(!skill
)return false;
5140 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5142 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5150 uint16
Player::GetSkillValue(uint32 skill
) const
5155 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5157 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5159 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5161 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5162 result
+= SKILL_TEMP_BONUS(bonus
);
5163 result
+= SKILL_PERM_BONUS(bonus
);
5164 return result
< 0 ? 0 : result
;
5170 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5173 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5175 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5177 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5179 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5180 result
+= SKILL_TEMP_BONUS(bonus
);
5181 result
+= SKILL_PERM_BONUS(bonus
);
5182 return result
< 0 ? 0 : result
;
5188 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5191 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5193 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5195 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5201 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5204 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5206 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5208 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5209 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5210 return result
< 0 ? 0 : result
;
5216 uint16
Player::GetPureSkillValue(uint32 skill
) const
5219 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5221 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5223 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5229 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5234 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5236 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5238 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5245 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5250 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5252 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5254 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5261 void Player::SendInitialActionButtons()
5263 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5265 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5266 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5268 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5269 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5271 data
<< uint16(itr
->second
.action
);
5272 data
<< uint8(itr
->second
.misc
);
5273 data
<< uint8(itr
->second
.type
);
5281 GetSession()->SendPacket( &data
);
5282 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5285 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5287 if(button
>= MAX_ACTION_BUTTONS
)
5289 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5293 // check cheating with adding non-known spells to action bar
5294 if(type
==ACTION_BUTTON_SPELL
)
5296 if(!sSpellStore
.LookupEntry(action
))
5298 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5302 if(!HasSpell(action
))
5304 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5309 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5311 if (buttonItr
==m_actionButtons
.end())
5312 { // just add new button
5313 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5316 { // change state of current button
5317 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5318 buttonItr
->second
= ActionButton(action
,type
,misc
);
5319 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5322 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5325 void Player::removeActionButton(uint8 button
)
5327 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5328 if (buttonItr
==m_actionButtons
.end())
5331 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5332 m_actionButtons
.erase(buttonItr
); // new and not saved
5334 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5336 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5339 void Player::SetDontMove(bool dontMove
)
5341 m_dontMove
= dontMove
;
5344 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5346 // prevent crash when a bad coord is sent by the client
5347 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5349 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5355 const float old_x
= GetPositionX();
5356 const float old_y
= GetPositionY();
5357 const float old_z
= GetPositionZ();
5358 const float old_r
= GetOrientation();
5360 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5362 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5363 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5365 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5367 // move and update visible state if need
5368 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5370 // reread after Map::Relocation
5377 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5378 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5381 // code block for underwater state update
5382 UpdateUnderwaterState(m
, x
, y
, z
);
5384 CheckExploreSystem();
5389 void Player::SaveRecallPosition()
5391 m_recallMap
= GetMapId();
5392 m_recallX
= GetPositionX();
5393 m_recallY
= GetPositionY();
5394 m_recallZ
= GetPositionZ();
5395 m_recallO
= GetOrientation();
5398 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5400 GetMap()->MessageBroadcast(this, data
, self
);
5403 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5405 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5408 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5410 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5413 void Player::SendDirectMessage(WorldPacket
*data
)
5415 GetSession()->SendPacket(data
);
5418 void Player::CheckExploreSystem()
5426 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5427 if(areaFlag
==0xffff)
5429 int offset
= areaFlag
/ 32;
5433 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
);
5437 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5438 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5440 if( !(currFields
& val
) )
5442 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5444 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5446 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5449 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5451 else if(p
->area_level
> 0)
5453 uint32 area
= p
->ID
;
5454 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5456 SendExplorationExperience(area
,0);
5460 int32 diff
= int32(getLevel()) - p
->area_level
;
5464 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5468 int32 exploration_percent
= (100-((diff
-5)*5));
5469 if (exploration_percent
> 100)
5470 exploration_percent
= 100;
5471 else if (exploration_percent
< 0)
5472 exploration_percent
= 0;
5474 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5478 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5482 SendExplorationExperience(area
,XP
);
5484 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5489 uint32
Player::TeamForRace(uint8 race
)
5491 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5494 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5498 switch(rEntry
->TeamID
)
5500 case 7: return ALLIANCE
;
5501 case 1: return HORDE
;
5504 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5508 uint32
Player::getFactionForRace(uint8 race
)
5510 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5513 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5517 return rEntry
->FactionID
;
5520 void Player::setFactionForRace(uint8 race
)
5522 m_team
= TeamForRace(race
);
5523 setFaction( getFactionForRace(race
) );
5526 void Player::UpdateReputation() const
5528 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5530 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5532 SendFactionState(&(itr
->second
));
5536 void Player::SendFactionState(FactionState
const* faction
) const
5538 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5540 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5541 data
<< (float) 0; // unk 2.4.0
5542 data
<< (uint8
) 0; // wotlk 8634
5543 data
<< (uint32
) 1; // count
5545 data
<< (uint32
) faction
->ReputationListID
;
5546 data
<< (uint32
) faction
->Standing
;
5548 GetSession()->SendPacket(&data
);
5552 void Player::SendInitialReputations()
5554 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5555 data
<< uint32 (0x00000080);
5559 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5561 // fill in absent fields
5562 for (; a
!= itr
->first
; a
++)
5564 data
<< uint8 (0x00);
5565 data
<< uint32 (0x00000000);
5568 // fill in encountered data
5569 data
<< uint8 (itr
->second
.Flags
);
5570 data
<< uint32 (itr
->second
.Standing
);
5575 // fill in absent fields
5576 for (; a
!= 128; a
++)
5578 data
<< uint8 (0x00);
5579 data
<< uint32 (0x00000000);
5582 GetSession()->SendPacket(&data
);
5585 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5587 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5588 if (itr
!= m_factions
.end())
5589 return &itr
->second
;
5594 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5596 // not allow declare war to own faction
5597 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5601 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5605 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5607 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5609 faction
->Changed
= true;
5612 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5614 // always invisible or hidden faction can't be inactive
5615 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5619 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5623 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5625 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5627 faction
->Changed
= true;
5630 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5632 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5634 if(!factionTemplateEntry
)
5637 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5640 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5642 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5646 if(factionEntry
->reputationListID
< 0)
5649 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5650 if (itr
== m_factions
.end())
5653 SetFactionVisible(&itr
->second
);
5656 void Player::SetFactionVisible(FactionState
* faction
)
5658 // always invisible or hidden faction can't be make visible
5659 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5663 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5666 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5667 faction
->Changed
= true;
5669 if(!m_session
->PlayerLoading())
5671 // make faction visible in reputation list at client
5672 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5673 data
<< faction
->ReputationListID
;
5674 GetSession()->SendPacket(&data
);
5678 void Player::SetInitialFactions()
5680 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5682 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5684 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5686 FactionState newFaction
;
5687 newFaction
.ID
= factionEntry
->ID
;
5688 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5689 newFaction
.Standing
= 0;
5690 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5691 newFaction
.Changed
= true;
5693 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5698 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5703 uint32 raceMask
= getRaceMask();
5704 uint32 classMask
= getClassMask();
5705 for (int i
=0; i
< 4; i
++)
5707 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5708 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5709 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5710 return factionEntry
->ReputationFlags
[i
];
5715 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5720 uint32 raceMask
= getRaceMask();
5721 uint32 classMask
= getClassMask();
5722 for (int i
=0; i
< 4; i
++)
5724 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5725 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5726 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5727 return factionEntry
->BaseRepValue
[i
];
5730 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5734 int32
Player::GetReputation(uint32 faction_id
) const
5736 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5740 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5744 return GetReputation(factionEntry
);
5747 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5749 // Faction without recorded reputation. Just ignore.
5753 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5754 if (itr
!= m_factions
.end())
5755 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5760 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5762 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5764 return MIN_REPUTATION_RANK
;
5766 return GetReputationRank(factionEntry
);
5769 ReputationRank
Player::ReputationToRank(int32 standing
) const
5771 int32 Limit
= Reputation_Cap
+ 1;
5772 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5774 Limit
-= ReputationRank_Length
[i
];
5775 if (standing
>= Limit
)
5776 return ReputationRank(i
);
5778 return MIN_REPUTATION_RANK
;
5781 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5783 int32 Reputation
= GetReputation(factionEntry
);
5784 return ReputationToRank(Reputation
);
5787 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5789 int32 Reputation
= GetBaseReputation(factionEntry
);
5790 return ReputationToRank(Reputation
);
5793 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5795 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5797 if(!factionTemplateEntry
)
5799 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5803 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5805 // Faction without recorded reputation. Just ignore.
5809 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5812 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5814 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5818 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5820 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5821 if(factionEntryCalc
)
5822 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5827 return ModifyOneFactionReputation(factionEntry
, standing
);
5830 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5832 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5833 if (itr
!= m_factions
.end())
5835 int32 BaseRep
= GetBaseReputation(factionEntry
);
5836 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5838 if (new_rep
> Reputation_Cap
)
5839 new_rep
= Reputation_Cap
;
5841 if (new_rep
< Reputation_Bottom
)
5842 new_rep
= Reputation_Bottom
;
5844 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5845 SetFactionAtWar(&itr
->second
,true);
5847 itr
->second
.Standing
= new_rep
- BaseRep
;
5848 itr
->second
.Changed
= true;
5850 SetFactionVisible(&itr
->second
);
5852 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
5854 if(uint32 questid
= GetQuestSlotQuestId(i
))
5856 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5857 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5859 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5860 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5862 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5863 if ( CanCompleteQuest( questid
) )
5864 CompleteQuest( questid
);
5866 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5868 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5869 IncompleteQuest( questid
);
5874 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5875 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5876 SendFactionState(&(itr
->second
));
5883 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5885 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5887 if(!factionTemplateEntry
)
5889 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5893 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5895 // Faction without recorded reputation. Just ignore.
5899 return SetFactionReputation(factionEntry
, standing
);
5902 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5904 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5908 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5910 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5911 if(factionEntryCalc
)
5912 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5917 return SetOneFactionReputation(factionEntry
, standing
);
5920 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5922 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5923 if (itr
!= m_factions
.end())
5925 if (standing
> Reputation_Cap
)
5926 standing
= Reputation_Cap
;
5928 if (standing
< Reputation_Bottom
)
5929 standing
= Reputation_Bottom
;
5931 int32 BaseRep
= GetBaseReputation(factionEntry
);
5932 itr
->second
.Standing
= standing
- BaseRep
;
5933 itr
->second
.Changed
= true;
5935 SetFactionVisible(&itr
->second
);
5937 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5938 SetFactionAtWar(&itr
->second
,true);
5940 SendFactionState(&(itr
->second
));
5941 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5942 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5948 //Calculate total reputation percent player gain with quest/creature level
5949 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5951 // for grey creature kill received 20%, in other case 100.
5952 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5954 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5956 percent
+= rep
> 0 ? repMod
: -repMod
;
5961 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5964 //Calculates how many reputation points player gains in victim's enemy factions
5965 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5967 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5970 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5975 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5977 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5978 donerep1
= int32(donerep1
*rate
);
5979 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5980 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5981 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5982 ModifyFactionReputation(factionEntry1
, donerep1
);
5984 // Wiki: Team factions value divided by 2
5985 if(Rep
->is_teamaward1
)
5987 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5988 if(team1_factionEntry
)
5989 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5993 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5995 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5996 donerep2
= int32(donerep2
*rate
);
5997 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5998 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5999 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
6000 ModifyFactionReputation(factionEntry2
, donerep2
);
6002 // Wiki: Team factions value divided by 2
6003 if(Rep
->is_teamaward2
)
6005 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6006 if(team2_factionEntry
)
6007 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
6012 //Calculate how many reputation points player gain with the quest
6013 void Player::RewardReputation(Quest
const *pQuest
)
6015 // quest reputation reward/loss
6016 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6018 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
6020 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
6021 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
6023 ModifyFactionReputation(factionEntry
, rep
);
6027 // TODO: implement reputation spillover
6030 void Player::UpdateArenaFields(void)
6032 /* arena calcs go here */
6035 void Player::UpdateHonorFields()
6037 /// called when rewarding honor and at each save
6038 uint64 now
= time(NULL
);
6039 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
6041 if(m_lastHonorUpdateTime
< today
)
6043 uint64 yesterday
= today
- DAY
;
6045 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6047 // update yesterday's contribution
6048 if(m_lastHonorUpdateTime
>= yesterday
)
6050 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6052 // this is the first update today, reset today's contribution
6053 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6054 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6058 // no honor/kills yesterday or today, reset
6059 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6060 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6064 m_lastHonorUpdateTime
= now
;
6067 ///Calculate the amount of honor gained based on the victim
6068 ///and the size of the group for which the honor is divided
6069 ///An exact honor value can also be given (overriding the calcs)
6070 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6072 // do not reward honor in arenas, but enable onkill spellproc
6075 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6078 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6084 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6085 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6088 uint64 victim_guid
= 0;
6089 uint32 victim_rank
= 0;
6091 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6092 UpdateHonorFields();
6096 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6099 victim_guid
= uVictim
->GetGUID();
6101 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6103 Player
*pVictim
= (Player
*)uVictim
;
6105 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6108 float f
= 1; //need for total kills (?? need more info)
6110 uint32 k_level
= getLevel();
6111 uint32 v_level
= pVictim
->getLevel();
6114 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6116 // [1..14] Alliance honor titles and player name
6117 // [15..28] Horde honor titles and player name
6118 // [29..38] Other title and player name
6120 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6121 // Get Killer titles, CharTitlesEntry::bit_index
6123 // title[1..14] -> rank[5..18]
6124 // title[15..28] -> rank[5..18]
6125 // title[other] -> 0
6126 if (victim_title
== 0)
6127 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6128 else if (victim_title
< 15)
6129 victim_rank
= victim_title
+ 4;
6130 else if (victim_title
< 29)
6131 victim_rank
= victim_title
- 14 + 4;
6133 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6136 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6141 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6143 int32 v_rank
=1; //need more info
6145 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6146 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6148 // count the number of playerkills in one day
6149 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6150 // and those in a lifetime
6151 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6155 Creature
*cVictim
= (Creature
*)uVictim
;
6157 if (!cVictim
->isRacialLeader())
6160 honor
= 100; // ??? need more info
6161 victim_rank
= 19; // HK: Leader
6165 if (uVictim
!= NULL
)
6167 honor
*= sWorld
.getRate(RATE_HONOR
);
6172 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6175 // honor - for show honor points in log
6176 // victim_guid - for show victim name in log
6177 // victim_rank [1..4] HK: <dishonored rank>
6178 // victim_rank [5..19] HK: <alliance\horde rank>
6179 // victim_rank [0,20+] HK: <>
6180 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6181 data
<< (uint32
) honor
;
6182 data
<< (uint64
) victim_guid
;
6183 data
<< (uint32
) victim_rank
;
6185 GetSession()->SendPacket(&data
);
6188 ModifyHonorPoints(int32(honor
));
6190 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6194 void Player::ModifyHonorPoints( int32 value
)
6198 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6199 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6201 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6204 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6207 void Player::ModifyArenaPoints( int32 value
)
6211 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6212 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6214 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6217 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6220 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6222 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6226 uint32 id
= result
->Fetch()[0].GetUInt32();
6231 uint32
Player::GetRankFromDB(uint64 guid
)
6233 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6236 uint32 v
= result
->Fetch()[0].GetUInt32();
6244 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6246 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
);
6250 uint32 id
= (*result
)[0].GetUInt32();
6255 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6257 uint32 guidLow
= GUID_LOPART(guid
);
6258 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6261 Field
* fields
= result
->Fetch();
6262 uint32 zone
= fields
[0].GetUInt32();
6267 // stored zone is zero, use generic and slow zone detection
6268 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6271 fields
= result
->Fetch();
6272 uint32 map
= fields
[0].GetUInt32();
6273 float posx
= fields
[1].GetFloat();
6274 float posy
= fields
[2].GetFloat();
6275 float posz
= fields
[3].GetFloat();
6278 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6280 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6286 void Player::UpdateArea(uint32 newArea
)
6288 // FFA_PVP flags are area and not zone id dependent
6289 // so apply them accordingly
6290 m_areaUpdateId
= newArea
;
6292 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6294 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6297 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6301 // remove ffa flag only if not ffapvp realm
6302 // removal in sanctuaries and capitals is handled in zone update
6303 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6304 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6307 UpdateAreaDependentAuras(newArea
);
6310 void Player::UpdateZone(uint32 newZone
)
6312 m_zoneUpdateId
= newZone
;
6313 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6315 // zone changed, so area changed as well, update it
6316 UpdateArea(GetAreaId());
6318 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6322 if (sWorld
.getConfig(CONFIG_WEATHER
))
6324 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6327 wth
->SendWeatherUpdateToPlayer(this);
6331 if(!sWorld
.AddWeather(zone
->ID
))
6333 // send fine weather packet to remove old zone's weather
6334 Weather::SendFineWeatherUpdateToPlayer(this);
6339 pvpInfo
.inHostileArea
=
6340 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6341 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6342 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6343 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6345 if(pvpInfo
.inHostileArea
) // in hostile area
6347 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6348 UpdatePvP(true, true);
6350 else // in friendly area
6352 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6353 pvpInfo
.endTimer
= time(0); // start toggle-off
6356 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6358 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6359 if(sWorld
.IsFFAPvPRealm())
6360 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6364 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6367 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6369 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6370 SetRestType(REST_TYPE_IN_CITY
);
6371 InnEnter(time(0),GetMapId(),0,0,0);
6373 if(sWorld
.IsFFAPvPRealm())
6374 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6376 else // anywhere else
6378 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6380 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6382 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6384 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6385 SetRestType(REST_TYPE_NO
);
6387 if(sWorld
.IsFFAPvPRealm())
6388 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6391 else // not in tavern (leave city then)
6393 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6394 SetRestType(REST_TYPE_NO
);
6396 // Set player to FFA PVP when not in rested environment.
6397 if(sWorld
.IsFFAPvPRealm())
6398 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6403 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6404 // if player resurrected at teleport this will be applied in resurrect code
6406 DestroyZoneLimitedItem( true, newZone
);
6408 // recent client version not send leave/join channel packets for built-in local channels
6409 UpdateLocalChannels( newZone
);
6413 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6415 UpdateZoneDependentAuras(newZone
);
6418 //If players are too far way of duel flag... then player loose the duel
6419 void Player::CheckDuelDistance(time_t currTime
)
6424 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6425 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6429 if(duel
->outOfBound
== 0)
6431 if(!IsWithinDistInMap(obj
, 50))
6433 duel
->outOfBound
= currTime
;
6435 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6436 GetSession()->SendPacket(&data
);
6441 if(IsWithinDistInMap(obj
, 40))
6443 duel
->outOfBound
= 0;
6445 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6446 GetSession()->SendPacket(&data
);
6448 else if(currTime
>= (duel
->outOfBound
+10))
6450 DuelComplete(DUEL_FLED
);
6455 void Player::DuelComplete(DuelCompleteType type
)
6457 // duel not requested
6461 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6462 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6463 GetSession()->SendPacket(&data
);
6464 duel
->opponent
->GetSession()->SendPacket(&data
);
6466 if(type
!= DUEL_INTERUPTED
)
6468 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6469 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6470 data
<< duel
->opponent
->GetName();
6472 SendMessageToSet(&data
,true);
6475 // cool-down duel spell
6476 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6483 GetSession()->SendPacket(&data);
6484 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6485 data<<duel->opponent->GetGUID();
6489 duel->opponent->GetSession()->SendPacket(&data);*/
6491 //Remove Duel Flag object
6492 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6494 duel
->initiator
->RemoveGameObject(obj
,true);
6497 std::vector
<uint32
> auras2remove
;
6498 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6499 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6501 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6502 auras2remove
.push_back(i
->second
->GetId());
6505 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6506 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6508 auras2remove
.clear();
6509 AuraMap
const& auras
= GetAuras();
6510 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6512 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6513 auras2remove
.push_back(i
->second
->GetId());
6515 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6516 RemoveAurasDueToSpell(auras2remove
[i
]);
6518 // cleanup combo points
6519 if(GetComboTarget()==duel
->opponent
->GetGUID())
6521 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6524 if(duel
->opponent
->GetComboTarget()==GetGUID())
6525 duel
->opponent
->ClearComboPoints();
6526 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6527 duel
->opponent
->ClearComboPoints();
6530 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6531 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6532 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6533 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6535 delete duel
->opponent
->duel
;
6536 duel
->opponent
->duel
= NULL
;
6541 //---------------------------------------------------------//
6543 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6545 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6548 // not apply/remove mods for broken item
6549 if(item
->IsBroken())
6552 ItemPrototype
const *proto
= item
->GetProto();
6557 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6559 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6560 if(attacktype
< MAX_ATTACK
)
6561 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6563 _ApplyItemBonuses(proto
,slot
,apply
);
6565 if( slot
==EQUIPMENT_SLOT_RANGED
)
6566 _ApplyAmmoBonuses();
6568 ApplyItemEquipSpell(item
,apply
);
6569 ApplyEnchantment(item
, apply
);
6571 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6572 CorrectMetaGemEnchants(slot
, apply
);
6574 sLog
.outDebug("_ApplyItemMods complete.");
6577 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6579 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6582 for (int i
= 0; i
< 10; i
++)
6584 uint32 statType
= 0;
6587 if(proto
->ScalingStatDistribution
)
6589 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6591 statType
= ssd
->StatMod
[i
];
6593 if(uint32 modifier
= ssd
->Modifier
[i
])
6595 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6596 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6598 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6599 val
= (multiplier
* modifier
) / 10000;
6606 statType
= proto
->ItemStat
[i
].ItemStatType
;
6607 val
= proto
->ItemStat
[i
].ItemStatValue
;
6616 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6618 case ITEM_MOD_HEALTH
: // modify HP
6619 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6621 case ITEM_MOD_AGILITY
: // modify agility
6622 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6623 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6625 case ITEM_MOD_STRENGTH
: //modify strength
6626 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6627 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6629 case ITEM_MOD_INTELLECT
: //modify intellect
6630 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6631 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6633 case ITEM_MOD_SPIRIT
: //modify spirit
6634 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6635 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6637 case ITEM_MOD_STAMINA
: //modify stamina
6638 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6639 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6641 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6642 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6644 case ITEM_MOD_DODGE_RATING
:
6645 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6647 case ITEM_MOD_PARRY_RATING
:
6648 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6650 case ITEM_MOD_BLOCK_RATING
:
6651 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6653 case ITEM_MOD_HIT_MELEE_RATING
:
6654 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6656 case ITEM_MOD_HIT_RANGED_RATING
:
6657 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6659 case ITEM_MOD_HIT_SPELL_RATING
:
6660 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6662 case ITEM_MOD_CRIT_MELEE_RATING
:
6663 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6665 case ITEM_MOD_CRIT_RANGED_RATING
:
6666 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6668 case ITEM_MOD_CRIT_SPELL_RATING
:
6669 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6671 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6672 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6674 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6675 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6677 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6678 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6680 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6681 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6683 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6684 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6686 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6687 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6689 case ITEM_MOD_HASTE_MELEE_RATING
:
6690 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6692 case ITEM_MOD_HASTE_RANGED_RATING
:
6693 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6695 case ITEM_MOD_HASTE_SPELL_RATING
:
6696 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6698 case ITEM_MOD_HIT_RATING
:
6699 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6700 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6701 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6703 case ITEM_MOD_CRIT_RATING
:
6704 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6705 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6706 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6708 case ITEM_MOD_HIT_TAKEN_RATING
:
6709 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6710 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6711 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6713 case ITEM_MOD_CRIT_TAKEN_RATING
:
6714 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6715 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6716 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6718 case ITEM_MOD_RESILIENCE_RATING
:
6719 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6720 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6721 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6723 case ITEM_MOD_HASTE_RATING
:
6724 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6725 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6726 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6728 case ITEM_MOD_EXPERTISE_RATING
:
6729 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6731 case ITEM_MOD_ATTACK_POWER
:
6732 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6733 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6735 case ITEM_MOD_RANGED_ATTACK_POWER
:
6736 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6738 case ITEM_MOD_FERAL_ATTACK_POWER
:
6739 ApplyFeralAPBonus(int32(val
), apply
);
6741 case ITEM_MOD_SPELL_HEALING_DONE
:
6742 ApplySpellHealingBonus(int32(val
), apply
);
6744 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6745 ApplySpellDamageBonus(int32(val
), apply
);
6747 case ITEM_MOD_MANA_REGENERATION
:
6748 ApplyManaRegenBonus(int32(val
), apply
);
6750 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6751 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6753 case ITEM_MOD_SPELL_POWER
:
6754 ApplySpellHealingBonus(int32(val
), apply
);
6755 ApplySpellDamageBonus(int32(val
), apply
);
6761 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6764 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6767 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6770 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6772 if (proto
->NatureRes
)
6773 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6775 if (proto
->FrostRes
)
6776 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6778 if (proto
->ShadowRes
)
6779 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6781 if (proto
->ArcaneRes
)
6782 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6784 WeaponAttackType attType
= BASE_ATTACK
;
6785 float damage
= 0.0f
;
6787 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6788 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6789 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6791 attType
= RANGED_ATTACK
;
6793 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6795 attType
= OFF_ATTACK
;
6798 if (proto
->Damage
[0].DamageMin
> 0 )
6800 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6801 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6802 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6805 if (proto
->Damage
[0].DamageMax
> 0 )
6807 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6808 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6811 // Druids get feral AP bonus from weapon dps
6812 if(getClass() == CLASS_DRUID
)
6814 int32 feral_bonus
= proto
->getFeralBonus();
6815 if (feral_bonus
> 0)
6816 ApplyFeralAPBonus(feral_bonus
, apply
);
6819 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6824 if(slot
== EQUIPMENT_SLOT_RANGED
)
6825 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6826 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6827 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6828 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6829 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6832 if(CanModifyStats() && (damage
|| proto
->Delay
))
6833 UpdateDamagePhysical(attType
);
6836 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6838 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6839 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6840 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6842 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6843 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6844 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6846 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6847 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6848 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6851 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6853 // generic not weapon specific case processes in aura code
6854 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6857 BaseModGroup mod
= BASEMOD_END
;
6860 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6861 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6862 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6866 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6868 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6872 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6874 // ignore spell mods for not wands
6875 Modifier
const* modifier
= aura
->GetModifier();
6876 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6879 // generic not weapon specific case processes in aura code
6880 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6883 UnitMods unitMod
= UNIT_MOD_END
;
6886 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6887 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6888 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6892 UnitModifierType unitModType
= TOTAL_VALUE
;
6893 switch(modifier
->m_auraname
)
6895 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6896 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6900 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6902 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6906 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6911 ItemPrototype
const *proto
= item
->GetProto();
6915 for (int i
= 0; i
< 5; i
++)
6917 _Spell
const& spellData
= proto
->Spells
[i
];
6920 if(!spellData
.SpellId
)
6923 // wrong triggering type
6924 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6927 // check if it is valid spell
6928 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6932 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6936 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6940 // Cannot be used in this stance/form
6941 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6944 if(form_change
) // check aura active state from other form
6947 for (int k
=0; k
< 3; ++k
)
6949 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6950 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6952 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6962 if(found
) // and skip re-cast already active aura at form change
6966 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6968 CastSpell(this,spellInfo
,true,item
);
6972 if(form_change
) // check aura compatibility
6974 // Cannot be used in this stance/form
6975 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6976 return; // and remove only not compatible at form change
6980 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6982 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6986 void Player::UpdateEquipSpellsAtFormChange()
6988 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6990 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6992 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6993 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6997 // item set bonuses not dependent from item broken state
6998 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
7000 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
7004 for(uint32 y
=0;y
<8; ++y
)
7006 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7010 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7011 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7016 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
7018 if(!item
|| item
->IsBroken())
7021 ItemPrototype
const *proto
= item
->GetProto();
7025 if (!Target
|| Target
== this )
7028 for (int i
= 0; i
< 5; i
++)
7030 _Spell
const& spellData
= proto
->Spells
[i
];
7033 if(!spellData
.SpellId
)
7036 // wrong triggering type
7037 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7040 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7043 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7047 // not allow proc extra attack spell at extra attack
7048 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7051 float chance
= spellInfo
->procChance
;
7053 if(spellData
.SpellPPMRate
)
7055 uint32 WeaponSpeed
= GetAttackTime(attType
);
7056 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7058 else if(chance
> 100.0f
)
7060 chance
= GetWeaponProcChance();
7063 if (roll_chance_f(chance
))
7064 CastSpell(Target
, spellInfo
->Id
, true, item
);
7067 // item combat enchantments
7068 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7070 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7071 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7072 if(!pEnchant
) continue;
7073 for (int s
=0;s
<3;s
++)
7075 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7078 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7081 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7085 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7086 if (roll_chance_f(chance
))
7088 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7089 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7091 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7097 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7099 ItemPrototype
const* proto
= item
->GetProto();
7100 // special learning case
7101 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7103 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7104 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7106 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7109 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7110 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7114 Spell
*spell
= new Spell(this, spellInfo
, false);
7115 spell
->m_CastItem
= item
;
7116 spell
->m_cast_count
= cast_count
; //set count of casts
7117 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7118 spell
->prepare(&targets
);
7122 // use triggered flag only for items with many spell casts and for not first cast
7125 // item spells casted at use
7126 for(int i
= 0; i
< 5; ++i
)
7128 _Spell
const& spellData
= proto
->Spells
[i
];
7131 if(!spellData
.SpellId
)
7134 // wrong triggering type
7135 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7138 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7141 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7145 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7146 spell
->m_CastItem
= item
;
7147 spell
->m_cast_count
= cast_count
; // set count of casts
7148 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7149 spell
->prepare(&targets
);
7154 // Item enchantments spells casted at use
7155 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7157 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7158 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7159 if(!pEnchant
) continue;
7160 for (int s
=0;s
<3;s
++)
7162 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7165 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7168 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7172 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7173 spell
->m_CastItem
= item
;
7174 spell
->m_cast_count
= cast_count
; // set count of casts
7175 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7176 spell
->prepare(&targets
);
7183 void Player::_RemoveAllItemMods()
7185 sLog
.outDebug("_RemoveAllItemMods start.");
7187 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7191 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7195 // item set bonuses not dependent from item broken state
7197 RemoveItemsSetItem(this,proto
);
7199 if(m_items
[i
]->IsBroken())
7202 ApplyItemEquipSpell(m_items
[i
],false);
7203 ApplyEnchantment(m_items
[i
], false);
7207 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7211 if(m_items
[i
]->IsBroken())
7213 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7217 uint32 attacktype
= Player::GetAttackBySlot(i
);
7218 if(attacktype
< MAX_ATTACK
)
7219 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7221 _ApplyItemBonuses(proto
,i
, false);
7223 if( i
== EQUIPMENT_SLOT_RANGED
)
7224 _ApplyAmmoBonuses();
7228 sLog
.outDebug("_RemoveAllItemMods complete.");
7231 void Player::_ApplyAllItemMods()
7233 sLog
.outDebug("_ApplyAllItemMods start.");
7235 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7239 if(m_items
[i
]->IsBroken())
7242 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7246 uint32 attacktype
= Player::GetAttackBySlot(i
);
7247 if(attacktype
< MAX_ATTACK
)
7248 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7250 _ApplyItemBonuses(proto
,i
, true);
7252 if( i
== EQUIPMENT_SLOT_RANGED
)
7253 _ApplyAmmoBonuses();
7257 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7261 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7265 // item set bonuses not dependent from item broken state
7267 AddItemsSetItem(this,m_items
[i
]);
7269 if(m_items
[i
]->IsBroken())
7272 ApplyItemEquipSpell(m_items
[i
],true);
7273 ApplyEnchantment(m_items
[i
], true);
7277 sLog
.outDebug("_ApplyAllItemMods complete.");
7280 void Player::_ApplyAmmoBonuses()
7283 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7287 float currentAmmoDPS
;
7289 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7290 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7291 currentAmmoDPS
= 0.0f
;
7293 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7295 if(currentAmmoDPS
== GetAmmoDPS())
7298 m_ammoDPS
= currentAmmoDPS
;
7300 if(CanModifyStats())
7301 UpdateDamagePhysical(RANGED_ATTACK
);
7304 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7309 // check ranged weapon
7310 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7311 if(!weapon
|| weapon
->IsBroken() )
7314 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7315 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7318 // check ammo ws. weapon compatibility
7319 switch(weapon_proto
->SubClass
)
7321 case ITEM_SUBCLASS_WEAPON_BOW
:
7322 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7323 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7326 case ITEM_SUBCLASS_WEAPON_GUN
:
7327 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7337 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7338 Called by remove insignia spell effect */
7339 void Player::RemovedInsignia(Player
* looterPlr
)
7341 if (!GetBattleGroundId())
7344 // If not released spirit, do it !
7345 if(m_deathTimer
> 0)
7352 Corpse
*corpse
= GetCorpse();
7356 // We have to convert player corpse to bones, not to be able to resurrect there
7357 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7358 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7362 // Now we must make bones lootable, and send player loot
7363 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7365 // We store the level of our player in the gold field
7366 // We retrieve this information at Player::SendLoot()
7367 bones
->loot
.gold
= getLevel();
7368 bones
->lootRecipient
= looterPlr
;
7369 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7378 void Player::SendLootRelease( uint64 guid
)
7380 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7381 data
<< uint64(guid
) << uint8(1);
7382 SendDirectMessage( &data
);
7385 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7388 PermissionTypes permission
= ALL_PERMISSION
;
7390 sLog
.outDebug("Player::SendLoot");
7391 if (IS_GAMEOBJECT_GUID(guid
))
7393 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7395 ObjectAccessor::GetGameObject(*this, guid
);
7397 // not check distance for GO in case owned GO (fishing bobber case, for example)
7398 // And permit out of range GO with no owner in case fishing hole
7399 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7401 SendLootRelease(guid
);
7407 if(go
->getLootState() == GO_READY
)
7409 uint32 lootid
= go
->GetLootId();
7413 sLog
.outDebug(" if(lootid)");
7415 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7418 if(loot_type
== LOOT_FISHING
)
7419 go
->getFishLoot(loot
,this);
7421 go
->SetLootState(GO_ACTIVATED
);
7424 else if (IS_ITEM_GUID(guid
))
7426 Item
*item
= GetItemByGuid( guid
);
7430 SendLootRelease(guid
);
7434 if(loot_type
== LOOT_DISENCHANTING
)
7438 if(!item
->m_lootGenerated
)
7440 item
->m_lootGenerated
= true;
7442 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7445 else if(loot_type
== LOOT_PROSPECTING
)
7449 if(!item
->m_lootGenerated
)
7451 item
->m_lootGenerated
= true;
7453 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7456 else if(loot_type
== LOOT_MILLING
)
7460 if(!item
->m_lootGenerated
)
7462 item
->m_lootGenerated
= true;
7464 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7471 if(!item
->m_lootGenerated
)
7473 item
->m_lootGenerated
= true;
7475 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7477 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7481 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7483 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7485 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7487 SendLootRelease(guid
);
7491 loot
= &bones
->loot
;
7493 if (!bones
->lootForBody
)
7495 bones
->lootForBody
= true;
7496 uint32 pLevel
= bones
->loot
.gold
;
7497 bones
->loot
.clear();
7498 // It may need a better formula
7499 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7500 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7503 if (bones
->lootRecipient
!= this)
7504 permission
= NONE_PERMISSION
;
7508 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7510 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7511 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7513 SendLootRelease(guid
);
7517 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7519 SendLootRelease(guid
);
7523 loot
= &creature
->loot
;
7525 if(loot_type
== LOOT_PICKPOCKETING
)
7527 if ( !creature
->lootForPickPocketed
)
7529 creature
->lootForPickPocketed
= true;
7532 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7533 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7535 // Generate extra money for pick pocket loot
7536 const uint32 a
= urand(0, creature
->getLevel()/2);
7537 const uint32 b
= urand(0, getLevel()/2);
7538 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7543 // the player whose group may loot the corpse
7544 Player
*recipient
= creature
->GetLootRecipient();
7547 creature
->SetLootRecipient(this);
7551 if (creature
->lootForPickPocketed
)
7553 creature
->lootForPickPocketed
= false;
7557 if(!creature
->lootForBody
)
7559 creature
->lootForBody
= true;
7562 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7563 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7565 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7567 if(Group
* group
= recipient
->GetGroup())
7569 group
->UpdateLooterGuid(creature
,true);
7571 switch (group
->GetLootMethod())
7574 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7575 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7577 case NEED_BEFORE_GREED
:
7578 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7581 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7589 // possible only if creature->lootForBody && loot->empty() at spell cast check
7590 if (loot_type
== LOOT_SKINNING
)
7593 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7595 // set group rights only for loot_type != LOOT_SKINNING
7598 if(Group
* group
= GetGroup())
7600 if( group
== recipient
->GetGroup() )
7602 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7603 permission
= ALL_PERMISSION
;
7604 else if(group
->GetLooterGuid() == GetGUID())
7606 if(group
->GetLootMethod() == MASTER_LOOT
)
7607 permission
= MASTER_PERMISSION
;
7609 permission
= ALL_PERMISSION
;
7612 permission
= GROUP_PERMISSION
;
7615 permission
= NONE_PERMISSION
;
7617 else if(recipient
== this)
7618 permission
= ALL_PERMISSION
;
7620 permission
= NONE_PERMISSION
;
7627 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7628 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7629 loot_type
= LOOT_SKINNING
;
7631 if(loot_type
== LOOT_FISHINGHOLE
)
7632 loot_type
= LOOT_FISHING
;
7634 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7636 data
<< uint64(guid
);
7637 data
<< uint8(loot_type
);
7638 data
<< LootView(*loot
, this, permission
);
7640 SendDirectMessage(&data
);
7642 // add 'this' player as one of the players that are looting 'loot'
7643 if (permission
!= NONE_PERMISSION
)
7644 loot
->AddLooter(GetGUID());
7646 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7647 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7650 void Player::SendNotifyLootMoneyRemoved()
7652 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7653 GetSession()->SendPacket( &data
);
7656 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7658 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7659 data
<< uint8(lootSlot
);
7660 GetSession()->SendPacket( &data
);
7663 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7665 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7668 GetSession()->SendPacket(&data
);
7671 void Player::SendInitWorldStates()
7673 // data depends on zoneid/mapid...
7674 BattleGround
* bg
= GetBattleGround();
7675 uint16 NumberOfFields
= 0;
7676 uint32 mapid
= GetMapId();
7677 uint32 zoneid
= GetZoneId();
7678 uint32 areaid
= GetAreaId();
7679 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7680 // may be exist better way to do this...
7703 NumberOfFields
= 41;
7706 NumberOfFields
= 15;
7709 NumberOfFields
= 83;
7712 NumberOfFields
= 16;
7716 NumberOfFields
= 40;
7719 NumberOfFields
= 27;
7722 NumberOfFields
= 39;
7725 NumberOfFields
= 38;
7728 NumberOfFields
= 37;
7733 NumberOfFields
= 11;
7736 NumberOfFields
= 11;
7739 NumberOfFields
= 12;
7743 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7744 data
<< uint32(mapid
); // mapid
7745 data
<< uint32(zoneid
); // zone id
7746 data
<< uint32(areaid
); // area id, new 2.1.0
7747 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7748 data
<< uint32(0x8d8) << uint32(0x0); // 1
7749 data
<< uint32(0x8d7) << uint32(0x0); // 2
7750 data
<< uint32(0x8d6) << uint32(0x0); // 3
7751 data
<< uint32(0x8d5) << uint32(0x0); // 4
7752 data
<< uint32(0x8d4) << uint32(0x0); // 5
7753 data
<< uint32(0x8d3) << uint32(0x0); // 6
7754 // 7 1 - Arena season in progress, 0 - end of season
7755 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7756 // 8 Arena season id
7757 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7758 if(mapid
== 530) // Outland
7760 data
<< uint32(0x9bf) << uint32(0x0); // 7
7761 data
<< uint32(0x9bd) << uint32(0xF); // 8
7762 data
<< uint32(0x9bb) << uint32(0xF); // 9
7777 data
<< uint32(0x7ae) << uint32(0x1); // 7
7778 data
<< uint32(0x532) << uint32(0x1); // 8
7779 data
<< uint32(0x531) << uint32(0x0); // 9
7780 data
<< uint32(0x52e) << uint32(0x0); // 10
7781 data
<< uint32(0x571) << uint32(0x0); // 11
7782 data
<< uint32(0x570) << uint32(0x0); // 12
7783 data
<< uint32(0x567) << uint32(0x1); // 13
7784 data
<< uint32(0x566) << uint32(0x1); // 14
7785 data
<< uint32(0x550) << uint32(0x1); // 15
7786 data
<< uint32(0x544) << uint32(0x0); // 16
7787 data
<< uint32(0x536) << uint32(0x0); // 17
7788 data
<< uint32(0x535) << uint32(0x1); // 18
7789 data
<< uint32(0x518) << uint32(0x0); // 19
7790 data
<< uint32(0x517) << uint32(0x0); // 20
7791 data
<< uint32(0x574) << uint32(0x0); // 21
7792 data
<< uint32(0x573) << uint32(0x0); // 22
7793 data
<< uint32(0x572) << uint32(0x0); // 23
7794 data
<< uint32(0x56f) << uint32(0x0); // 24
7795 data
<< uint32(0x56e) << uint32(0x0); // 25
7796 data
<< uint32(0x56d) << uint32(0x0); // 26
7797 data
<< uint32(0x56c) << uint32(0x0); // 27
7798 data
<< uint32(0x56b) << uint32(0x0); // 28
7799 data
<< uint32(0x56a) << uint32(0x1); // 29
7800 data
<< uint32(0x569) << uint32(0x1); // 30
7801 data
<< uint32(0x568) << uint32(0x1); // 13
7802 data
<< uint32(0x565) << uint32(0x0); // 32
7803 data
<< uint32(0x564) << uint32(0x0); // 33
7804 data
<< uint32(0x563) << uint32(0x0); // 34
7805 data
<< uint32(0x562) << uint32(0x0); // 35
7806 data
<< uint32(0x561) << uint32(0x0); // 36
7807 data
<< uint32(0x560) << uint32(0x0); // 37
7808 data
<< uint32(0x55f) << uint32(0x0); // 38
7809 data
<< uint32(0x55e) << uint32(0x0); // 39
7810 data
<< uint32(0x55d) << uint32(0x0); // 40
7811 data
<< uint32(0x3c6) << uint32(0x4); // 41
7812 data
<< uint32(0x3c4) << uint32(0x6); // 42
7813 data
<< uint32(0x3c2) << uint32(0x4); // 43
7814 data
<< uint32(0x516) << uint32(0x1); // 44
7815 data
<< uint32(0x515) << uint32(0x0); // 45
7816 data
<< uint32(0x3b6) << uint32(0x6); // 46
7817 data
<< uint32(0x55c) << uint32(0x0); // 47
7818 data
<< uint32(0x55b) << uint32(0x0); // 48
7819 data
<< uint32(0x55a) << uint32(0x0); // 49
7820 data
<< uint32(0x559) << uint32(0x0); // 50
7821 data
<< uint32(0x558) << uint32(0x0); // 51
7822 data
<< uint32(0x557) << uint32(0x0); // 52
7823 data
<< uint32(0x556) << uint32(0x0); // 53
7824 data
<< uint32(0x555) << uint32(0x0); // 54
7825 data
<< uint32(0x554) << uint32(0x1); // 55
7826 data
<< uint32(0x553) << uint32(0x1); // 56
7827 data
<< uint32(0x552) << uint32(0x1); // 57
7828 data
<< uint32(0x551) << uint32(0x1); // 58
7829 data
<< uint32(0x54f) << uint32(0x0); // 59
7830 data
<< uint32(0x54e) << uint32(0x0); // 60
7831 data
<< uint32(0x54d) << uint32(0x1); // 61
7832 data
<< uint32(0x54c) << uint32(0x0); // 62
7833 data
<< uint32(0x54b) << uint32(0x0); // 63
7834 data
<< uint32(0x545) << uint32(0x0); // 64
7835 data
<< uint32(0x543) << uint32(0x1); // 65
7836 data
<< uint32(0x542) << uint32(0x0); // 66
7837 data
<< uint32(0x540) << uint32(0x0); // 67
7838 data
<< uint32(0x53f) << uint32(0x0); // 68
7839 data
<< uint32(0x53e) << uint32(0x0); // 69
7840 data
<< uint32(0x53d) << uint32(0x0); // 70
7841 data
<< uint32(0x53c) << uint32(0x0); // 71
7842 data
<< uint32(0x53b) << uint32(0x0); // 72
7843 data
<< uint32(0x53a) << uint32(0x1); // 73
7844 data
<< uint32(0x539) << uint32(0x0); // 74
7845 data
<< uint32(0x538) << uint32(0x0); // 75
7846 data
<< uint32(0x537) << uint32(0x0); // 76
7847 data
<< uint32(0x534) << uint32(0x0); // 77
7848 data
<< uint32(0x533) << uint32(0x0); // 78
7849 data
<< uint32(0x530) << uint32(0x0); // 79
7850 data
<< uint32(0x52f) << uint32(0x0); // 80
7851 data
<< uint32(0x52d) << uint32(0x1); // 81
7854 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7855 bg
->FillInitialWorldStates(data
);
7858 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7859 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7860 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7861 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7862 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7863 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7864 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7865 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7869 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7870 bg
->FillInitialWorldStates(data
);
7873 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7874 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7875 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7876 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7877 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7878 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7879 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7880 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7881 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7882 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7883 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7884 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7885 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7886 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7887 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7888 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7889 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7890 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7891 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7892 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7893 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7894 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7895 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7896 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7897 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7898 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7899 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7900 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7901 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7902 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7903 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7904 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7908 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7909 bg
->FillInitialWorldStates(data
);
7912 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7913 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7914 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7915 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7916 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7917 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7918 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7919 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7920 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7921 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7922 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7923 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7924 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7925 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7926 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7927 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7928 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7929 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7930 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7931 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7932 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7933 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7934 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7935 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7936 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7937 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7938 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7939 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7940 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7941 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7942 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7943 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7944 // and some more ... unknown
7947 case 3483: // Hellfire Peninsula
7948 data
<< uint32(0x9ba) << uint32(0x1); // 10
7949 data
<< uint32(0x9b9) << uint32(0x1); // 11
7950 data
<< uint32(0x9b5) << uint32(0x0); // 12
7951 data
<< uint32(0x9b4) << uint32(0x1); // 13
7952 data
<< uint32(0x9b3) << uint32(0x0); // 14
7953 data
<< uint32(0x9b2) << uint32(0x0); // 15
7954 data
<< uint32(0x9b1) << uint32(0x1); // 16
7955 data
<< uint32(0x9b0) << uint32(0x0); // 17
7956 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7957 data
<< uint32(0x9ac) << uint32(0x0); // 19
7958 data
<< uint32(0x9a8) << uint32(0x0); // 20
7959 data
<< uint32(0x9a7) << uint32(0x0); // 21
7960 data
<< uint32(0x9a6) << uint32(0x1); // 22
7962 case 3519: // Terokkar Forest
7963 data
<< uint32(0xa41) << uint32(0x0); // 10
7964 data
<< uint32(0xa40) << uint32(0x14); // 11
7965 data
<< uint32(0xa3f) << uint32(0x0); // 12
7966 data
<< uint32(0xa3e) << uint32(0x0); // 13
7967 data
<< uint32(0xa3d) << uint32(0x5); // 14
7968 data
<< uint32(0xa3c) << uint32(0x0); // 15
7969 data
<< uint32(0xa87) << uint32(0x0); // 16
7970 data
<< uint32(0xa86) << uint32(0x0); // 17
7971 data
<< uint32(0xa85) << uint32(0x0); // 18
7972 data
<< uint32(0xa84) << uint32(0x0); // 19
7973 data
<< uint32(0xa83) << uint32(0x0); // 20
7974 data
<< uint32(0xa82) << uint32(0x0); // 21
7975 data
<< uint32(0xa81) << uint32(0x0); // 22
7976 data
<< uint32(0xa80) << uint32(0x0); // 23
7977 data
<< uint32(0xa7e) << uint32(0x0); // 24
7978 data
<< uint32(0xa7d) << uint32(0x0); // 25
7979 data
<< uint32(0xa7c) << uint32(0x0); // 26
7980 data
<< uint32(0xa7b) << uint32(0x0); // 27
7981 data
<< uint32(0xa7a) << uint32(0x0); // 28
7982 data
<< uint32(0xa79) << uint32(0x0); // 29
7983 data
<< uint32(0x9d0) << uint32(0x5); // 30
7984 data
<< uint32(0x9ce) << uint32(0x0); // 31
7985 data
<< uint32(0x9cd) << uint32(0x0); // 32
7986 data
<< uint32(0x9cc) << uint32(0x0); // 33
7987 data
<< uint32(0xa88) << uint32(0x0); // 34
7988 data
<< uint32(0xad0) << uint32(0x0); // 35
7989 data
<< uint32(0xacf) << uint32(0x1); // 36
7991 case 3521: // Zangarmarsh
7992 data
<< uint32(0x9e1) << uint32(0x0); // 10
7993 data
<< uint32(0x9e0) << uint32(0x0); // 11
7994 data
<< uint32(0x9df) << uint32(0x0); // 12
7995 data
<< uint32(0xa5d) << uint32(0x1); // 13
7996 data
<< uint32(0xa5c) << uint32(0x0); // 14
7997 data
<< uint32(0xa5b) << uint32(0x1); // 15
7998 data
<< uint32(0xa5a) << uint32(0x0); // 16
7999 data
<< uint32(0xa59) << uint32(0x1); // 17
8000 data
<< uint32(0xa58) << uint32(0x0); // 18
8001 data
<< uint32(0xa57) << uint32(0x0); // 19
8002 data
<< uint32(0xa56) << uint32(0x0); // 20
8003 data
<< uint32(0xa55) << uint32(0x1); // 21
8004 data
<< uint32(0xa54) << uint32(0x0); // 22
8005 data
<< uint32(0x9e7) << uint32(0x0); // 23
8006 data
<< uint32(0x9e6) << uint32(0x0); // 24
8007 data
<< uint32(0x9e5) << uint32(0x0); // 25
8008 data
<< uint32(0xa00) << uint32(0x0); // 26
8009 data
<< uint32(0x9ff) << uint32(0x1); // 27
8010 data
<< uint32(0x9fe) << uint32(0x0); // 28
8011 data
<< uint32(0x9fd) << uint32(0x0); // 29
8012 data
<< uint32(0x9fc) << uint32(0x1); // 30
8013 data
<< uint32(0x9fb) << uint32(0x0); // 31
8014 data
<< uint32(0xa62) << uint32(0x0); // 32
8015 data
<< uint32(0xa61) << uint32(0x1); // 33
8016 data
<< uint32(0xa60) << uint32(0x1); // 34
8017 data
<< uint32(0xa5f) << uint32(0x0); // 35
8019 case 3698: // Nagrand Arena
8020 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8021 bg
->FillInitialWorldStates(data
);
8024 data
<< uint32(0xa0f) << uint32(0x0); // 7
8025 data
<< uint32(0xa10) << uint32(0x0); // 8
8026 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8029 case 3702: // Blade's Edge Arena
8030 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8031 bg
->FillInitialWorldStates(data
);
8034 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8035 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8036 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8039 case 3968: // Ruins of Lordaeron
8040 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8041 bg
->FillInitialWorldStates(data
);
8044 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8045 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8046 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8049 case 3703: // Shattrath City
8052 data
<< uint32(0x914) << uint32(0x0); // 7
8053 data
<< uint32(0x913) << uint32(0x0); // 8
8054 data
<< uint32(0x912) << uint32(0x0); // 9
8055 data
<< uint32(0x915) << uint32(0x0); // 10
8058 GetSession()->SendPacket(&data
);
8061 uint32
Player::GetXPRestBonus(uint32 xp
)
8063 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8065 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8068 SetRestBonus( GetRestBonus() - rested_bonus
);
8070 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8071 return rested_bonus
;
8074 void Player::SetBindPoint(uint64 guid
)
8076 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8077 data
<< uint64(guid
);
8078 GetSession()->SendPacket( &data
);
8081 void Player::SendTalentWipeConfirm(uint64 guid
)
8083 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8084 data
<< uint64(guid
);
8085 data
<< uint32(resetTalentsCost());
8086 GetSession()->SendPacket( &data
);
8089 void Player::SendPetSkillWipeConfirm()
8091 Pet
* pet
= GetPet();
8094 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8095 data
<< pet
->GetGUID();
8096 data
<< uint32(pet
->resetTalentsCost());
8097 GetSession()->SendPacket( &data
);
8100 /*********************************************************/
8101 /*** STORAGE SYSTEM ***/
8102 /*********************************************************/
8104 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8109 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8111 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8115 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8116 else if(charges
<= 1)
8118 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8119 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8124 void Player::SetSheath( uint32 sheathed
)
8128 case SHEATH_STATE_UNARMED
: // no prepared weapon
8129 SetVirtualItemSlot(0,NULL
);
8130 SetVirtualItemSlot(1,NULL
);
8131 SetVirtualItemSlot(2,NULL
);
8133 case SHEATH_STATE_MELEE
: // prepared melee weapon
8135 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8136 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8137 SetVirtualItemSlot(2,NULL
);
8139 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8140 SetVirtualItemSlot(0,NULL
);
8141 SetVirtualItemSlot(1,NULL
);
8142 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8145 SetVirtualItemSlot(0,NULL
);
8146 SetVirtualItemSlot(1,NULL
);
8147 SetVirtualItemSlot(2,NULL
);
8150 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
8153 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8155 uint8 pClass
= getClass();
8158 slots
[0] = NULL_SLOT
;
8159 slots
[1] = NULL_SLOT
;
8160 slots
[2] = NULL_SLOT
;
8161 slots
[3] = NULL_SLOT
;
8162 switch( proto
->InventoryType
)
8165 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8168 slots
[0] = EQUIPMENT_SLOT_NECK
;
8170 case INVTYPE_SHOULDERS
:
8171 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8174 slots
[0] = EQUIPMENT_SLOT_BODY
;
8177 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8180 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8183 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8186 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8189 slots
[0] = EQUIPMENT_SLOT_FEET
;
8191 case INVTYPE_WRISTS
:
8192 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8195 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8197 case INVTYPE_FINGER
:
8198 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8199 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8201 case INVTYPE_TRINKET
:
8202 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8203 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8206 slots
[0] = EQUIPMENT_SLOT_BACK
;
8208 case INVTYPE_WEAPON
:
8210 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8212 // suggest offhand slot only if know dual wielding
8213 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8215 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8218 case INVTYPE_SHIELD
:
8219 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8221 case INVTYPE_RANGED
:
8222 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8224 case INVTYPE_2HWEAPON
:
8225 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8226 if (CanDualWield() && CanTitanGrip())
8227 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8229 case INVTYPE_TABARD
:
8230 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8232 case INVTYPE_WEAPONMAINHAND
:
8233 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8235 case INVTYPE_WEAPONOFFHAND
:
8236 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8238 case INVTYPE_HOLDABLE
:
8239 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8241 case INVTYPE_THROWN
:
8242 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8244 case INVTYPE_RANGEDRIGHT
:
8245 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8248 slots
[0] = INVENTORY_SLOT_BAG_1
;
8249 slots
[1] = INVENTORY_SLOT_BAG_2
;
8250 slots
[2] = INVENTORY_SLOT_BAG_3
;
8251 slots
[3] = INVENTORY_SLOT_BAG_4
;
8255 switch(proto
->SubClass
)
8257 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8258 if (pClass
== CLASS_PALADIN
)
8259 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8261 case ITEM_SUBCLASS_ARMOR_IDOL
:
8262 if (pClass
== CLASS_DRUID
)
8263 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8265 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8266 if (pClass
== CLASS_SHAMAN
)
8267 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8269 case ITEM_SUBCLASS_ARMOR_MISC
:
8270 if (pClass
== CLASS_WARLOCK
)
8271 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8273 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8274 if (pClass
== CLASS_DEATH_KNIGHT
)
8275 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8284 if( slot
!= NULL_SLOT
)
8286 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8288 for (int i
= 0; i
< 4; i
++)
8290 if ( slots
[i
] == slot
)
8297 // search free slot at first
8298 for (int i
= 0; i
< 4; i
++)
8300 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8302 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8303 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8308 // if not found free and can swap return first appropriate from used
8309 for (int i
= 0; i
< 4; i
++)
8311 if ( slots
[i
] != NULL_SLOT
&& swap
)
8320 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8323 uint32 tempcount
= 0;
8325 uint8 res
= EQUIP_ERR_OK
;
8327 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8329 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8330 if( pItem
&& pItem
->GetEntry() == item
)
8332 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8333 if(ires
==EQUIP_ERR_OK
)
8335 tempcount
+= pItem
->GetCount();
8336 if( tempcount
>= count
)
8337 return EQUIP_ERR_OK
;
8343 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8345 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8346 if( pItem
&& pItem
->GetEntry() == item
)
8348 tempcount
+= pItem
->GetCount();
8349 if( tempcount
>= count
)
8350 return EQUIP_ERR_OK
;
8353 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8355 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8356 if( pItem
&& pItem
->GetEntry() == item
)
8358 tempcount
+= pItem
->GetCount();
8359 if( tempcount
>= count
)
8360 return EQUIP_ERR_OK
;
8364 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8366 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8369 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8371 pItem
= GetItemByPos( i
, j
);
8372 if( pItem
&& pItem
->GetEntry() == item
)
8374 tempcount
+= pItem
->GetCount();
8375 if( tempcount
>= count
)
8376 return EQUIP_ERR_OK
;
8382 // not found req. item count and have unequippable items
8386 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8389 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8391 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8392 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8393 count
+= pItem
->GetCount();
8395 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8397 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8398 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8399 count
+= pItem
->GetCount();
8401 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8403 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8405 count
+= pBag
->GetItemCount(item
,skipItem
);
8408 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8410 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8412 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8413 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8414 count
+= pItem
->GetGemCountWithID(item
);
8420 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8422 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8423 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8424 count
+= pItem
->GetCount();
8426 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8428 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8430 count
+= pBag
->GetItemCount(item
,skipItem
);
8433 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8435 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8437 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8438 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8439 count
+= pItem
->GetGemCountWithID(item
);
8447 Item
* Player::GetItemByGuid( uint64 guid
) const
8449 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8451 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8452 if( pItem
&& pItem
->GetGUID() == guid
)
8455 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8457 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8458 if( pItem
&& pItem
->GetGUID() == guid
)
8462 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8464 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8467 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8469 Item
* pItem
= pBag
->GetItemByPos( j
);
8470 if( pItem
&& pItem
->GetGUID() == guid
)
8475 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8477 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8480 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8482 Item
* pItem
= pBag
->GetItemByPos( j
);
8483 if( pItem
&& pItem
->GetGUID() == guid
)
8492 Item
* Player::GetItemByPos( uint16 pos
) const
8494 uint8 bag
= pos
>> 8;
8495 uint8 slot
= pos
& 255;
8496 return GetItemByPos( bag
, slot
);
8499 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8501 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8502 return m_items
[slot
];
8503 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8504 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8506 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8508 return pBag
->GetItemByPos(slot
);
8513 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8518 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8519 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8520 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8521 default: return NULL
;
8524 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8525 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8531 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8537 Item
* Player::GetShield(bool useable
) const
8539 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8540 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8546 if( item
->IsBroken())
8552 uint32
Player::GetAttackBySlot( uint8 slot
)
8556 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8557 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8558 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8559 default: return MAX_ATTACK
;
8563 bool Player::HasBankBagSlot( uint8 slot
) const
8565 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8566 if( slot
< maxslot
)
8571 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8573 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8575 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8577 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8579 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8584 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8586 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8588 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8593 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8595 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8597 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8599 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8604 bool Player::IsBagPos( uint16 pos
)
8606 uint8 bag
= pos
>> 8;
8607 uint8 slot
= pos
& 255;
8608 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8610 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8615 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8621 if (bag
== INVENTORY_SLOT_BAG_0
)
8623 // any post selected
8624 if (slot
== NULL_SLOT
)
8628 if (slot
< EQUIPMENT_SLOT_END
)
8632 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8636 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8640 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8644 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8648 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8654 // bag content slots
8655 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8657 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8661 // any post selected
8662 if (slot
== NULL_SLOT
)
8665 return slot
< pBag
->GetBagSize();
8668 // bank bag content slots
8669 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8671 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8675 // any post selected
8676 if (slot
== NULL_SLOT
)
8679 return slot
< pBag
->GetBagSize();
8687 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8689 uint32 tempcount
= 0;
8690 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8692 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8693 if( pItem
&& pItem
->GetEntry() == item
)
8695 tempcount
+= pItem
->GetCount();
8696 if( tempcount
>= count
)
8700 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8702 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8703 if( pItem
&& pItem
->GetEntry() == item
)
8705 tempcount
+= pItem
->GetCount();
8706 if( tempcount
>= count
)
8710 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8712 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8714 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8716 Item
* pItem
= GetItemByPos( i
, j
);
8717 if( pItem
&& pItem
->GetEntry() == item
)
8719 tempcount
+= pItem
->GetCount();
8720 if( tempcount
>= count
)
8729 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8731 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8732 if( pItem
&& pItem
->GetEntry() == item
)
8734 tempcount
+= pItem
->GetCount();
8735 if( tempcount
>= count
)
8739 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8741 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8743 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8745 Item
* pItem
= GetItemByPos( i
, j
);
8746 if( pItem
&& pItem
->GetEntry() == item
)
8748 tempcount
+= pItem
->GetCount();
8749 if( tempcount
>= count
)
8760 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8762 uint32 tempcount
= 0;
8763 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8765 if(i
==int(except_slot
))
8768 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8769 if( pItem
&& pItem
->GetEntry() == item
)
8771 tempcount
+= pItem
->GetCount();
8772 if( tempcount
>= count
)
8777 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8778 if (pProto
&& pProto
->GemProperties
)
8780 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8782 if(i
==int(except_slot
))
8785 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8786 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8788 tempcount
+= pItem
->GetGemCountWithID(item
);
8789 if( tempcount
>= count
)
8798 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8800 uint32 tempcount
= 0;
8801 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8803 if(i
==int(except_slot
))
8806 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8810 ItemPrototype
const *pProto
= pItem
->GetProto();
8814 if (pProto
->ItemLimitCategory
== limitCategory
)
8816 tempcount
+= pItem
->GetCount();
8817 if( tempcount
>= count
)
8821 if( pProto
->Socket
[0].Color
)
8823 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8824 if( tempcount
>= count
)
8832 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8834 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8838 *no_space_count
= count
;
8839 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8843 if(pProto
->MaxCount
<= 0)
8844 return EQUIP_ERR_OK
;
8846 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8848 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8851 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8852 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8855 return EQUIP_ERR_OK
;
8858 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8861 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8863 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8864 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8867 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8869 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8870 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8873 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8875 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8877 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8879 pItem
= GetItemByPos( i
, j
);
8880 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8888 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8890 Item
* pItem2
= GetItemByPos( bag
, slot
);
8892 // ignore move item (this slot will be empty at move)
8893 if(pItem2
==pSrcItem
)
8898 // empty specific slot - check item fit to slot
8899 if( !pItem2
|| swap
)
8901 if( bag
== INVENTORY_SLOT_BAG_0
)
8904 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8905 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8907 // vanitypet case (not use, vanity pets stored as spells)
8908 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8909 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8911 // currencytoken case (disabled until proper implement)
8912 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8913 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8915 // guestbag case (disabled until proper implement)
8916 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8917 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8920 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8921 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8925 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8927 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8929 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8931 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8933 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8934 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8937 // non empty stack with space
8938 need_space
= pProto
->GetMaxStackSize();
8940 // non empty slot, check item type
8944 if(pItem2
->GetEntry() != pProto
->ItemId
)
8945 return EQUIP_ERR_ITEM_CANT_STACK
;
8948 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8949 return EQUIP_ERR_ITEM_CANT_STACK
;
8951 // free stack space or infinity
8952 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8955 if(need_space
> count
)
8958 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8959 if(!newPosition
.isContainedIn(dest
))
8961 dest
.push_back(newPosition
);
8962 count
-= need_space
;
8964 return EQUIP_ERR_OK
;
8967 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
8969 // skip specific bag already processed in first called _CanStoreItem_InBag
8971 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8973 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8975 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8977 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8979 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8981 // specialized bag mode or non-specilized
8982 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8983 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8985 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8986 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8988 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8990 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8994 Item
* pItem2
= GetItemByPos( bag
, j
);
8996 // ignore move item (this slot will be empty at move)
8997 if(pItem2
==pSrcItem
)
9000 // if merge skip empty, if !merge skip non-empty
9001 if((pItem2
!=NULL
)!=merge
)
9006 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9008 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9009 if(need_space
> count
)
9012 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9013 if(!newPosition
.isContainedIn(dest
))
9015 dest
.push_back(newPosition
);
9016 count
-= need_space
;
9019 return EQUIP_ERR_OK
;
9025 uint32 need_space
= pProto
->GetMaxStackSize();
9026 if(need_space
> count
)
9029 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9030 if(!newPosition
.isContainedIn(dest
))
9032 dest
.push_back(newPosition
);
9033 count
-= need_space
;
9036 return EQUIP_ERR_OK
;
9040 return EQUIP_ERR_OK
;
9043 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
9045 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
9047 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9048 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9051 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9053 // ignore move item (this slot will be empty at move)
9054 if(pItem2
==pSrcItem
)
9057 // if merge skip empty, if !merge skip non-empty
9058 if((pItem2
!=NULL
)!=merge
)
9063 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9065 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9066 if(need_space
> count
)
9068 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9069 if(!newPosition
.isContainedIn(dest
))
9071 dest
.push_back(newPosition
);
9072 count
-= need_space
;
9075 return EQUIP_ERR_OK
;
9081 uint32 need_space
= pProto
->GetMaxStackSize();
9082 if(need_space
> count
)
9085 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9086 if(!newPosition
.isContainedIn(dest
))
9088 dest
.push_back(newPosition
);
9089 count
-= need_space
;
9092 return EQUIP_ERR_OK
;
9096 return EQUIP_ERR_OK
;
9099 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9101 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9103 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
9107 *no_space_count
= count
;
9108 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9111 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
9114 *no_space_count
= count
;
9115 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9118 // check count of items (skip for auto move for same player from bank)
9119 uint32 no_similar_count
= 0; // can't store this amount similar items
9120 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9121 if(res
!=EQUIP_ERR_OK
)
9123 if(count
==no_similar_count
)
9126 *no_space_count
= no_similar_count
;
9129 count
-= no_similar_count
;
9133 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9135 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9136 if(res
!=EQUIP_ERR_OK
)
9139 *no_space_count
= count
+ no_similar_count
;
9145 if(no_similar_count
==0)
9146 return EQUIP_ERR_OK
;
9149 *no_space_count
= count
+ no_similar_count
;
9150 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9154 // not specific slot or have space for partly store only in specific slot
9157 if( bag
!= NULL_BAG
)
9159 // search stack in bag for merge to
9160 if( pProto
->Stackable
!= 1 )
9162 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9164 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9165 if(res
!=EQUIP_ERR_OK
)
9168 *no_space_count
= count
+ no_similar_count
;
9174 if(no_similar_count
==0)
9175 return EQUIP_ERR_OK
;
9178 *no_space_count
= count
+ no_similar_count
;
9179 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9182 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9183 if(res
!=EQUIP_ERR_OK
)
9186 *no_space_count
= count
+ no_similar_count
;
9192 if(no_similar_count
==0)
9193 return EQUIP_ERR_OK
;
9196 *no_space_count
= count
+ no_similar_count
;
9197 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9200 else // equipped bag
9202 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9203 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9204 if(res
!=EQUIP_ERR_OK
)
9205 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9207 if(res
!=EQUIP_ERR_OK
)
9210 *no_space_count
= count
+ no_similar_count
;
9216 if(no_similar_count
==0)
9217 return EQUIP_ERR_OK
;
9220 *no_space_count
= count
+ no_similar_count
;
9221 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9226 // search free slot in bag for place to
9227 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9229 // search free slot - keyring case
9230 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9232 uint32 keyringSize
= GetMaxKeyringSize();
9233 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9234 if(res
!=EQUIP_ERR_OK
)
9237 *no_space_count
= count
+ no_similar_count
;
9243 if(no_similar_count
==0)
9244 return EQUIP_ERR_OK
;
9247 *no_space_count
= count
+ no_similar_count
;
9248 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9252 // Vanity pet case skipped as not used
9254 /* until proper implementation
9255 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9257 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9258 if(res!=EQUIP_ERR_OK)
9261 *no_space_count = count + no_similar_count;
9267 if(no_similar_count==0)
9268 return EQUIP_ERR_OK;
9271 *no_space_count = count + no_similar_count;
9272 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9276 /* until proper implementation
9277 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9279 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9280 if(res!=EQUIP_ERR_OK)
9283 *no_space_count = count + no_similar_count;
9289 if(no_similar_count==0)
9290 return EQUIP_ERR_OK;
9293 *no_space_count = count + no_similar_count;
9294 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9299 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,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
;
9317 else // equipped bag
9319 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9320 if(res
!=EQUIP_ERR_OK
)
9321 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9323 if(res
!=EQUIP_ERR_OK
)
9326 *no_space_count
= count
+ no_similar_count
;
9332 if(no_similar_count
==0)
9333 return EQUIP_ERR_OK
;
9336 *no_space_count
= count
+ no_similar_count
;
9337 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9342 // not specific bag or have space for partly store only in specific bag
9344 // search stack for merge to
9345 if( pProto
->Stackable
!= 1 )
9347 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9348 if(res
!=EQUIP_ERR_OK
)
9351 *no_space_count
= count
+ no_similar_count
;
9357 if(no_similar_count
==0)
9358 return EQUIP_ERR_OK
;
9361 *no_space_count
= count
+ no_similar_count
;
9362 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9365 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9366 if(res
!=EQUIP_ERR_OK
)
9369 *no_space_count
= count
+ no_similar_count
;
9375 if(no_similar_count
==0)
9376 return EQUIP_ERR_OK
;
9379 *no_space_count
= count
+ no_similar_count
;
9380 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9383 if( pProto
->BagFamily
)
9385 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9387 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9388 if(res
!=EQUIP_ERR_OK
)
9393 if(no_similar_count
==0)
9394 return EQUIP_ERR_OK
;
9397 *no_space_count
= count
+ no_similar_count
;
9398 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9403 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9405 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9406 if(res
!=EQUIP_ERR_OK
)
9411 if(no_similar_count
==0)
9412 return EQUIP_ERR_OK
;
9415 *no_space_count
= count
+ no_similar_count
;
9416 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9421 // search free slot - special bag case
9422 if( pProto
->BagFamily
)
9424 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9426 uint32 keyringSize
= GetMaxKeyringSize();
9427 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9428 if(res
!=EQUIP_ERR_OK
)
9431 *no_space_count
= count
+ no_similar_count
;
9437 if(no_similar_count
==0)
9438 return EQUIP_ERR_OK
;
9441 *no_space_count
= count
+ no_similar_count
;
9442 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9446 // Vanity pet case skipped as not used
9448 /* until proper implementation
9449 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9451 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9452 if(res!=EQUIP_ERR_OK)
9455 *no_space_count = count + no_similar_count;
9461 if(no_similar_count==0)
9462 return EQUIP_ERR_OK;
9465 *no_space_count = count + no_similar_count;
9466 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9470 /* until proper implementation
9471 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9473 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9474 if(res!=EQUIP_ERR_OK)
9477 *no_space_count = count + no_similar_count;
9483 if(no_similar_count==0)
9484 return EQUIP_ERR_OK;
9487 *no_space_count = count + no_similar_count;
9488 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9493 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9495 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9496 if(res
!=EQUIP_ERR_OK
)
9501 if(no_similar_count
==0)
9502 return EQUIP_ERR_OK
;
9505 *no_space_count
= count
+ no_similar_count
;
9506 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9512 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9513 if(res
!=EQUIP_ERR_OK
)
9516 *no_space_count
= count
+ no_similar_count
;
9522 if(no_similar_count
==0)
9523 return EQUIP_ERR_OK
;
9526 *no_space_count
= count
+ no_similar_count
;
9527 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9530 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9532 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9533 if(res
!=EQUIP_ERR_OK
)
9538 if(no_similar_count
==0)
9539 return EQUIP_ERR_OK
;
9542 *no_space_count
= count
+ no_similar_count
;
9543 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9548 *no_space_count
= count
+ no_similar_count
;
9550 return EQUIP_ERR_INVENTORY_FULL
;
9553 //////////////////////////////////////////////////////////////////////////
9554 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9559 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9560 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9561 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9562 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9563 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9565 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9566 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9567 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9568 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9569 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9571 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9573 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9575 if (pItem2
&& !pItem2
->IsInTrade())
9577 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9581 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9583 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9585 if (pItem2
&& !pItem2
->IsInTrade())
9587 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9591 // Vanity pet case skipped as not used
9593 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9595 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9597 if (pItem2
&& !pItem2
->IsInTrade())
9599 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9603 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9605 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9607 if (pItem2
&& !pItem2
->IsInTrade())
9609 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9613 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9615 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9617 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9619 pItem2
= GetItemByPos( i
, j
);
9620 if (pItem2
&& !pItem2
->IsInTrade())
9622 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9628 // check free space for all items
9629 for (int k
=0;k
<count
;k
++)
9631 Item
*pItem
= pItems
[k
];
9634 if (!pItem
) continue;
9636 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9637 ItemPrototype
const *pProto
= pItem
->GetProto();
9641 return EQUIP_ERR_ITEM_NOT_FOUND
;
9644 if(pItem
->IsBindedNotWith(GetGUID()))
9645 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9648 ItemPrototype
const *pBagProto
;
9650 // item is 'one item only'
9651 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9652 if(res
!= EQUIP_ERR_OK
)
9655 // search stack for merge to
9656 if( pProto
->Stackable
!= 1 )
9658 bool b_found
= false;
9660 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9662 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9663 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9665 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9670 if (b_found
) continue;
9672 // Vanity pet case skipped as not used
9674 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9676 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9677 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9679 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9684 if (b_found
) continue;
9686 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9688 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9689 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9691 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9696 if (b_found
) continue;
9698 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9700 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9701 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9703 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9708 if (b_found
) continue;
9710 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9712 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9715 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9717 pItem2
= GetItemByPos( t
, j
);
9718 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9720 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9727 if (b_found
) continue;
9731 if( pProto
->BagFamily
)
9733 bool b_found
= false;
9734 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9736 uint32 keyringSize
= GetMaxKeyringSize();
9737 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9739 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9741 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9748 if (b_found
) continue;
9750 // Vanity pet case skipped as not used
9752 /* until proper implementation
9753 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9755 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9757 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9759 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9766 if (b_found) continue;
9768 /* until proper implementation
9769 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9771 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9773 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9775 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9782 if (b_found) continue;
9785 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9787 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9790 pBagProto
= pBag
->GetProto();
9792 // not plain container check
9793 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9794 ItemCanGoIntoBag(pProto
,pBagProto
) )
9796 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9798 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9800 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9808 if (b_found
) continue;
9812 bool b_found
= false;
9813 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9815 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9817 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9822 if (b_found
) continue;
9824 // search free slot in bags
9825 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9827 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9830 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9832 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9834 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9842 // no free slot found?
9844 return EQUIP_ERR_INVENTORY_FULL
;
9847 return EQUIP_ERR_OK
;
9850 //////////////////////////////////////////////////////////////////////////
9851 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9854 Item
*pItem
= Item::CreateItem( item
, 1, this );
9857 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9862 return EQUIP_ERR_ITEM_NOT_FOUND
;
9865 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9870 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9871 ItemPrototype
const *pProto
= pItem
->GetProto();
9874 if(pItem
->IsBindedNotWith(GetGUID()))
9875 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9877 // check count of items (skip for auto move for same player from bank)
9878 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9879 if(res
!= EQUIP_ERR_OK
)
9882 // check this only in game
9885 // May be here should be more stronger checks; STUNNED checked
9886 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9887 if (hasUnitState(UNIT_STAT_STUNNED
))
9888 return EQUIP_ERR_YOU_ARE_STUNNED
;
9890 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9892 // - in-progress arenas
9893 if( !pProto
->CanChangeEquipStateInCombat() )
9896 return EQUIP_ERR_NOT_IN_COMBAT
;
9898 if(BattleGround
* bg
= GetBattleGround())
9899 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9900 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9903 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9904 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9906 if(IsNonMeleeSpellCasted(false))
9907 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9910 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9911 if( eslot
== NULL_SLOT
)
9912 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9914 uint8 msg
= CanUseItem( pItem
, not_loading
);
9915 if( msg
!= EQUIP_ERR_OK
)
9917 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9918 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9920 // if swap ignore item (equipped also)
9921 if(uint8 res
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9924 // check unique-equipped special item classes
9925 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9927 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9929 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9931 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9933 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
9935 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9936 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9938 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9945 uint32 type
= pProto
->InventoryType
;
9947 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9949 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9952 return EQUIP_ERR_CANT_DUAL_WIELD
;
9954 else if (type
== INVTYPE_2HWEAPON
)
9956 if(!CanDualWield() || !CanTitanGrip())
9957 return EQUIP_ERR_CANT_DUAL_WIELD
;
9961 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9964 // equip two-hand weapon case (with possible unequip 2 items)
9965 if( type
== INVTYPE_2HWEAPON
)
9967 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9969 if (!CanTitanGrip())
9970 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9972 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9973 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9975 if (!CanTitanGrip())
9977 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9978 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9979 ItemPosCountVec off_dest
;
9980 if( offItem
&& (!not_loading
||
9981 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9982 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9983 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9986 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9987 return EQUIP_ERR_OK
;
9991 return EQUIP_ERR_ITEM_NOT_FOUND
;
9993 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9996 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9998 // Applied only to equipped items and bank bags
9999 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
10000 return EQUIP_ERR_OK
;
10002 Item
* pItem
= GetItemByPos(pos
);
10004 // Applied only to existed equipped item
10006 return EQUIP_ERR_OK
;
10008 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10010 ItemPrototype
const *pProto
= pItem
->GetProto();
10012 return EQUIP_ERR_ITEM_NOT_FOUND
;
10014 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10016 // - in-progress arenas
10017 if( !pProto
->CanChangeEquipStateInCombat() )
10020 return EQUIP_ERR_NOT_IN_COMBAT
;
10022 if(BattleGround
* bg
= GetBattleGround())
10023 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10024 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10027 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10028 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10030 return EQUIP_ERR_OK
;
10033 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10036 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10038 uint32 count
= pItem
->GetCount();
10040 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10041 ItemPrototype
const *pProto
= pItem
->GetProto();
10043 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10045 if( pItem
->IsBindedNotWith(GetGUID()) )
10046 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10048 // check count of items (skip for auto move for same player from bank)
10049 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10050 if(res
!= EQUIP_ERR_OK
)
10053 // in specific slot
10054 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10056 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10058 if (!pItem
->IsBag())
10059 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10061 Bag
*pBag
= (Bag
*)pItem
;
10062 if( !HasBankBagSlot( slot
) )
10063 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10065 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10069 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10070 if(res
!=EQUIP_ERR_OK
)
10074 return EQUIP_ERR_OK
;
10077 // not specific slot or have space for partly store only in specific slot
10080 if( bag
!= NULL_BAG
)
10082 if( pProto
->InventoryType
== INVTYPE_BAG
)
10084 Bag
*pBag
= (Bag
*)pItem
;
10085 if( pBag
&& !pBag
->IsEmpty() )
10086 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10089 // search stack in bag for merge to
10090 if( pProto
->Stackable
!= 1 )
10092 if( bag
== INVENTORY_SLOT_BAG_0
)
10094 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10095 if(res
!=EQUIP_ERR_OK
)
10099 return EQUIP_ERR_OK
;
10103 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10104 if(res
!=EQUIP_ERR_OK
)
10105 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10107 if(res
!=EQUIP_ERR_OK
)
10111 return EQUIP_ERR_OK
;
10115 // search free slot in bag
10116 if( bag
== INVENTORY_SLOT_BAG_0
)
10118 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10119 if(res
!=EQUIP_ERR_OK
)
10123 return EQUIP_ERR_OK
;
10127 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
10128 if(res
!=EQUIP_ERR_OK
)
10129 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
10131 if(res
!=EQUIP_ERR_OK
)
10135 return EQUIP_ERR_OK
;
10139 // not specific bag or have space for partly store only in specific bag
10141 // search stack for merge to
10142 if( pProto
->Stackable
!= 1 )
10145 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10146 if(res
!=EQUIP_ERR_OK
)
10150 return EQUIP_ERR_OK
;
10153 if( pProto
->BagFamily
)
10155 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10157 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10158 if(res
!=EQUIP_ERR_OK
)
10162 return EQUIP_ERR_OK
;
10166 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10168 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10169 if(res
!=EQUIP_ERR_OK
)
10173 return EQUIP_ERR_OK
;
10177 // search free place in special bag
10178 if( pProto
->BagFamily
)
10180 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10182 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10183 if(res
!=EQUIP_ERR_OK
)
10187 return EQUIP_ERR_OK
;
10191 // search free space
10192 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10193 if(res
!=EQUIP_ERR_OK
)
10197 return EQUIP_ERR_OK
;
10199 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10201 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10202 if(res
!=EQUIP_ERR_OK
)
10206 return EQUIP_ERR_OK
;
10208 return EQUIP_ERR_BANK_FULL
;
10211 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10215 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10216 if( !isAlive() && not_loading
)
10217 return EQUIP_ERR_YOU_ARE_DEAD
;
10218 //if( isStunned() )
10219 // return EQUIP_ERR_YOU_ARE_STUNNED;
10220 ItemPrototype
const *pProto
= pItem
->GetProto();
10223 if( pItem
->IsBindedNotWith(GetGUID()) )
10224 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10225 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10226 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10227 if( pItem
->GetSkill() != 0 )
10229 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10230 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10232 if( pProto
->RequiredSkill
!= 0 )
10234 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10235 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10236 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10237 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10239 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10240 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10241 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10242 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10243 if( getLevel() < pProto
->RequiredLevel
)
10244 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10245 return EQUIP_ERR_OK
;
10248 return EQUIP_ERR_ITEM_NOT_FOUND
;
10251 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10253 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10257 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10259 if( pProto
->RequiredSkill
!= 0 )
10261 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10263 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10266 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10268 if( getLevel() < pProto
->RequiredLevel
)
10275 uint8
Player::CanUseAmmo( uint32 item
) const
10277 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10279 return EQUIP_ERR_YOU_ARE_DEAD
;
10280 //if( isStunned() )
10281 // return EQUIP_ERR_YOU_ARE_STUNNED;
10282 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10285 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10286 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10287 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10288 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10289 if( pProto
->RequiredSkill
!= 0 )
10291 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10292 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10293 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10294 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10296 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10297 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10298 /*if( GetReputation() < pProto->RequiredReputation )
10299 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10301 if( getLevel() < pProto
->RequiredLevel
)
10302 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10304 // Requires No Ammo
10305 if(GetDummyAura(46699))
10306 return EQUIP_ERR_BAG_FULL6
;
10308 return EQUIP_ERR_OK
;
10310 return EQUIP_ERR_ITEM_NOT_FOUND
;
10313 void Player::SetAmmo( uint32 item
)
10319 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10325 uint8 msg
= CanUseAmmo( item
);
10326 if( msg
!= EQUIP_ERR_OK
)
10328 SendEquipError( msg
, NULL
, NULL
);
10333 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10335 _ApplyAmmoBonuses();
10338 void Player::RemoveAmmo()
10340 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10344 if(CanModifyStats())
10345 UpdateDamagePhysical(RANGED_ATTACK
);
10348 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10349 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10352 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10353 count
+= itr
->count
;
10355 Item
*pItem
= Item::CreateItem( item
, count
, this );
10358 ItemAddedQuestCheck( item
, count
);
10359 if(randomPropertyId
)
10360 pItem
->SetItemRandomProperties(randomPropertyId
);
10361 pItem
= StoreItem( dest
, pItem
, update
);
10366 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10371 Item
* lastItem
= pItem
;
10373 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10375 uint16 pos
= itr
->pos
;
10376 uint32 count
= itr
->count
;
10380 if(itr
== dest
.end())
10382 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10386 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10392 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10393 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10398 uint8 bag
= pos
>> 8;
10399 uint8 slot
= pos
& 255;
10401 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10403 Item
*pItem2
= GetItemByPos( bag
, slot
);
10408 pItem
= pItem
->CloneItem(count
,this);
10410 pItem
->SetCount(count
);
10415 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10416 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10417 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10418 pItem
->SetBinding( true );
10420 if( bag
== INVENTORY_SLOT_BAG_0
)
10422 m_items
[slot
] = pItem
;
10423 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10424 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10425 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10427 pItem
->SetSlot( slot
);
10428 pItem
->SetContainer( NULL
);
10430 if( IsInWorld() && update
)
10432 pItem
->AddToWorld();
10433 pItem
->SendUpdateToPlayer( this );
10436 pItem
->SetState(ITEM_CHANGED
, this);
10440 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10443 pBag
->StoreItem( slot
, pItem
, update
);
10444 if( IsInWorld() && update
)
10446 pItem
->AddToWorld();
10447 pItem
->SendUpdateToPlayer( this );
10449 pItem
->SetState(ITEM_CHANGED
, this);
10450 pBag
->SetState(ITEM_CHANGED
, this);
10454 AddEnchantmentDurations(pItem
);
10455 AddItemDurations(pItem
);
10461 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10462 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10463 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10464 pItem2
->SetBinding( true );
10466 pItem2
->SetCount( pItem2
->GetCount() + count
);
10467 if( IsInWorld() && update
)
10468 pItem2
->SendUpdateToPlayer( this );
10472 // delete item (it not in any slot currently)
10473 if( IsInWorld() && update
)
10475 pItem
->RemoveFromWorld();
10476 pItem
->DestroyForPlayer( this );
10479 RemoveEnchantmentDurations(pItem
);
10480 RemoveItemDurations(pItem
);
10482 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10483 pItem
->SetState(ITEM_REMOVED
, this);
10485 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10486 AddEnchantmentDurations(pItem2
);
10488 pItem2
->SetState(ITEM_CHANGED
, this);
10494 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10496 Item
*pItem
= Item::CreateItem( item
, 1, this );
10499 ItemAddedQuestCheck( item
, 1 );
10500 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10507 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10511 AddEnchantmentDurations(pItem
);
10512 AddItemDurations(pItem
);
10514 uint8 bag
= pos
>> 8;
10515 uint8 slot
= pos
& 255;
10517 Item
*pItem2
= GetItemByPos( bag
, slot
);
10521 VisualizeItem( slot
, pItem
);
10525 ItemPrototype
const *pProto
= pItem
->GetProto();
10527 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10528 if(pProto
&& pProto
->ItemSet
)
10529 AddItemsSetItem(this,pItem
);
10531 _ApplyItemMods(pItem
, slot
, true);
10533 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10535 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10537 if (getClass() == CLASS_ROGUE
)
10538 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10540 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10543 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10546 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10548 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10549 data
<< uint64(GetGUID());
10551 data
<< uint32(cooldownSpell
);
10553 GetSession()->SendPacket(&data
);
10558 if( IsInWorld() && update
)
10560 pItem
->AddToWorld();
10561 pItem
->SendUpdateToPlayer( this );
10564 ApplyEquipCooldown(pItem
);
10566 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10567 UpdateExpertise(BASE_ATTACK
);
10568 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10569 UpdateExpertise(OFF_ATTACK
);
10573 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10574 if( IsInWorld() && update
)
10575 pItem2
->SendUpdateToPlayer( this );
10577 // delete item (it not in any slot currently)
10578 //pItem->DeleteFromDB();
10579 if( IsInWorld() && update
)
10581 pItem
->RemoveFromWorld();
10582 pItem
->DestroyForPlayer( this );
10585 RemoveEnchantmentDurations(pItem
);
10586 RemoveItemDurations(pItem
);
10588 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10589 pItem
->SetState(ITEM_REMOVED
, this);
10590 pItem2
->SetState(ITEM_CHANGED
, this);
10592 ApplyEquipCooldown(pItem2
);
10601 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10605 AddEnchantmentDurations(pItem
);
10606 AddItemDurations(pItem
);
10608 uint8 slot
= pos
& 255;
10609 VisualizeItem( slot
, pItem
);
10613 pItem
->AddToWorld();
10614 pItem
->SendUpdateToPlayer( this );
10619 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10621 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10622 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10623 // entry // Size: 1
10624 // inspected enchantments // Size: 6
10626 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10627 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10632 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10634 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10635 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10637 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10638 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10640 // Use SetInt16Value to prevent set high part to FFFF for negative value
10641 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10642 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10646 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10648 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10649 SetUInt32Value(VisibleBase
+ 0, 0);
10651 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10652 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10654 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10655 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10659 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10664 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10665 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10666 pItem
->SetBinding( true );
10668 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10670 m_items
[slot
] = pItem
;
10671 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10672 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10673 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10674 pItem
->SetSlot( slot
);
10675 pItem
->SetContainer( NULL
);
10677 if( slot
< EQUIPMENT_SLOT_END
)
10678 SetVisibleItemSlot(slot
,pItem
);
10680 pItem
->SetState(ITEM_CHANGED
, this);
10683 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10685 // note: removeitem does not actually change the item
10686 // it only takes the item out of storage temporarily
10687 // note2: if removeitem is to be used for delinking
10688 // the item must be removed from the player's updatequeue
10690 Item
*pItem
= GetItemByPos( bag
, slot
);
10693 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10695 RemoveEnchantmentDurations(pItem
);
10696 RemoveItemDurations(pItem
);
10698 if( bag
== INVENTORY_SLOT_BAG_0
)
10700 if ( slot
< INVENTORY_SLOT_BAG_END
)
10702 ItemPrototype
const *pProto
= pItem
->GetProto();
10703 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10705 if(pProto
&& pProto
->ItemSet
)
10706 RemoveItemsSetItem(this,pProto
);
10708 _ApplyItemMods(pItem
, slot
, false);
10710 // remove item dependent auras and casts (only weapon and armor slots)
10711 if(slot
< EQUIPMENT_SLOT_END
)
10712 RemoveItemDependentAurasAndCasts(pItem
);
10714 // remove held enchantments
10715 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10717 if (pItem
->GetItemSuffixFactor())
10719 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10720 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10724 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10725 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10730 m_items
[slot
] = NULL
;
10731 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10733 if ( slot
< EQUIPMENT_SLOT_END
)
10734 SetVisibleItemSlot(slot
,NULL
);
10738 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10740 pBag
->RemoveItem(slot
, update
);
10742 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10743 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10744 pItem
->SetSlot( NULL_SLOT
);
10745 if( IsInWorld() && update
)
10746 pItem
->SendUpdateToPlayer( this );
10748 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10749 UpdateExpertise(BASE_ATTACK
);
10750 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10751 UpdateExpertise(OFF_ATTACK
);
10755 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10756 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10758 if(Item
* it
= GetItemByPos(bag
,slot
))
10760 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10761 RemoveItem( bag
,slot
,update
);
10762 it
->RemoveFromUpdateQueueOf(this);
10763 if(it
->IsInWorld())
10765 it
->RemoveFromWorld();
10766 it
->DestroyForPlayer( this );
10771 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10772 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10774 // update quest counters
10775 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10778 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10780 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10781 if(pLastItem
==pItem
)
10783 // update owner for last item (this can be original item with wrong owner
10784 if(pLastItem
->GetOwnerGUID() != GetGUID())
10785 pLastItem
->SetOwnerGUID(GetGUID());
10787 // if this original item then it need create record in inventory
10788 // in case trade we already have item in other player inventory
10789 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10793 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10795 Item
*pItem
= GetItemByPos( bag
, slot
);
10798 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10800 // start from destroy contained items (only equipped bag can have its)
10801 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10803 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10804 DestroyItem(slot
,i
,update
);
10807 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10808 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10810 RemoveEnchantmentDurations(pItem
);
10811 RemoveItemDurations(pItem
);
10813 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10815 if( bag
== INVENTORY_SLOT_BAG_0
)
10817 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10819 // equipment and equipped bags can have applied bonuses
10820 if ( slot
< INVENTORY_SLOT_BAG_END
)
10822 ItemPrototype
const *pProto
= pItem
->GetProto();
10824 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10825 if(pProto
&& pProto
->ItemSet
)
10826 RemoveItemsSetItem(this,pProto
);
10828 _ApplyItemMods(pItem
, slot
, false);
10831 if ( slot
< EQUIPMENT_SLOT_END
)
10833 // remove item dependent auras and casts (only weapon and armor slots)
10834 RemoveItemDependentAurasAndCasts(pItem
);
10836 // equipment visual show
10837 SetVisibleItemSlot(slot
,NULL
);
10840 m_items
[slot
] = NULL
;
10842 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10843 pBag
->RemoveItem(slot
, update
);
10845 if( IsInWorld() && update
)
10847 pItem
->RemoveFromWorld();
10848 pItem
->DestroyForPlayer(this);
10851 //pItem->SetOwnerGUID(0);
10852 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10853 pItem
->SetSlot( NULL_SLOT
);
10854 pItem
->SetState(ITEM_REMOVED
, this);
10858 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10860 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10862 ItemPrototype
const *pProto
;
10863 uint32 remcount
= 0;
10866 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10868 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10869 if( pItem
&& pItem
->GetEntry() == item
)
10871 if( pItem
->GetCount() + remcount
<= count
)
10873 // all items in inventory can unequipped
10874 remcount
+= pItem
->GetCount();
10875 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10877 if(remcount
>=count
)
10882 pProto
= pItem
->GetProto();
10883 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10884 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10885 if( IsInWorld() & update
)
10886 pItem
->SendUpdateToPlayer( this );
10887 pItem
->SetState(ITEM_CHANGED
, this);
10892 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10894 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10895 if( pItem
&& pItem
->GetEntry() == item
)
10897 if( pItem
->GetCount() + remcount
<= count
)
10899 // all keys can be unequipped
10900 remcount
+= pItem
->GetCount();
10901 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10903 if(remcount
>=count
)
10908 pProto
= pItem
->GetProto();
10909 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10910 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10911 if( IsInWorld() & update
)
10912 pItem
->SendUpdateToPlayer( this );
10913 pItem
->SetState(ITEM_CHANGED
, this);
10919 // in inventory bags
10920 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10922 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10924 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10926 pItem
= pBag
->GetItemByPos(j
);
10927 if( pItem
&& pItem
->GetEntry() == item
)
10929 // all items in bags can be unequipped
10930 if( pItem
->GetCount() + remcount
<= count
)
10932 remcount
+= pItem
->GetCount();
10933 DestroyItem( i
, j
, update
);
10935 if(remcount
>=count
)
10940 pProto
= pItem
->GetProto();
10941 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10942 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10943 if( IsInWorld() && update
)
10944 pItem
->SendUpdateToPlayer( this );
10945 pItem
->SetState(ITEM_CHANGED
, this);
10953 // in equipment and bag list
10954 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10956 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10957 if( pItem
&& pItem
->GetEntry() == item
)
10959 if( pItem
->GetCount() + remcount
<= count
)
10961 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10963 remcount
+= pItem
->GetCount();
10964 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10966 if(remcount
>=count
)
10972 pProto
= pItem
->GetProto();
10973 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10974 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10975 if( IsInWorld() & update
)
10976 pItem
->SendUpdateToPlayer( this );
10977 pItem
->SetState(ITEM_CHANGED
, this);
10984 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10986 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10989 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10991 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10992 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10993 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10995 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10997 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10998 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10999 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11002 // in inventory bags
11003 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11005 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11008 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11010 Item
* pItem
= pBag
->GetItemByPos(j
);
11011 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11012 DestroyItem( i
, j
, update
);
11017 // in equipment and bag list
11018 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11020 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11021 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11022 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11026 void Player::DestroyConjuredItems( bool update
)
11028 // used when entering arena
11029 // destroys all conjured items
11030 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11033 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11035 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11036 if( pItem
&& pItem
->GetProto() &&
11037 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11038 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11039 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11042 // in inventory bags
11043 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11045 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11048 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11050 Item
* pItem
= pBag
->GetItemByPos(j
);
11051 if( pItem
&& pItem
->GetProto() &&
11052 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11053 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11054 DestroyItem( i
, j
, update
);
11059 // in equipment and bag list
11060 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11062 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11063 if( pItem
&& pItem
->GetProto() &&
11064 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11065 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11066 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11070 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11075 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11077 if( pItem
->GetCount() <= count
)
11079 count
-= pItem
->GetCount();
11081 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11085 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11086 pItem
->SetCount( pItem
->GetCount() - count
);
11088 if( IsInWorld() & update
)
11089 pItem
->SendUpdateToPlayer( this );
11090 pItem
->SetState(ITEM_CHANGED
, this);
11094 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11096 uint8 srcbag
= src
>> 8;
11097 uint8 srcslot
= src
& 255;
11099 uint8 dstbag
= dst
>> 8;
11100 uint8 dstslot
= dst
& 255;
11102 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11105 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11109 // not let split all items (can be only at cheating)
11110 if(pSrcItem
->GetCount() == count
)
11112 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11116 // not let split more existed items (can be only at cheating)
11117 if(pSrcItem
->GetCount() < count
)
11119 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11123 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11125 //best error message found for attempting to split while looting
11126 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11130 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11131 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11134 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11138 if( IsInventoryPos( dst
) )
11140 // change item amount before check (for unique max count check)
11141 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11143 ItemPosCountVec dest
;
11144 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11145 if( msg
!= EQUIP_ERR_OK
)
11148 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11149 SendEquipError( msg
, pSrcItem
, NULL
);
11154 pSrcItem
->SendUpdateToPlayer( this );
11155 pSrcItem
->SetState(ITEM_CHANGED
, this);
11156 StoreItem( dest
, pNewItem
, true);
11158 else if( IsBankPos ( dst
) )
11160 // change item amount before check (for unique max count check)
11161 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11163 ItemPosCountVec dest
;
11164 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11165 if( msg
!= EQUIP_ERR_OK
)
11168 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11169 SendEquipError( msg
, pSrcItem
, NULL
);
11174 pSrcItem
->SendUpdateToPlayer( this );
11175 pSrcItem
->SetState(ITEM_CHANGED
, this);
11176 BankItem( dest
, pNewItem
, true);
11178 else if( IsEquipmentPos ( dst
) )
11180 // change item amount before check (for unique max count check), provide space for splitted items
11181 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11184 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11185 if( msg
!= EQUIP_ERR_OK
)
11188 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11189 SendEquipError( msg
, pSrcItem
, NULL
);
11194 pSrcItem
->SendUpdateToPlayer( this );
11195 pSrcItem
->SetState(ITEM_CHANGED
, this);
11196 EquipItem( dest
, pNewItem
, true);
11197 AutoUnequipOffhandIfNeed();
11201 void Player::SwapItem( uint16 src
, uint16 dst
)
11203 uint8 srcbag
= src
>> 8;
11204 uint8 srcslot
= src
& 255;
11206 uint8 dstbag
= dst
>> 8;
11207 uint8 dstslot
= dst
& 255;
11209 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11210 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11215 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11219 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11225 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11227 //best error message found for attempting to swap while looting
11228 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11232 // check unequip potability for equipped items and bank bags
11233 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11235 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11236 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
11237 if(msg
!= EQUIP_ERR_OK
)
11239 SendEquipError( msg
, pSrcItem
, pDstItem
);
11244 // prevent put equipped/bank bag in self
11245 if( IsBagPos ( src
) && srcslot
== dstbag
)
11247 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11255 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11257 //best error message found for attempting to swap while looting
11258 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11262 // check unequip potability for equipped items and bank bags
11263 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11265 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11266 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
11267 if(msg
!= EQUIP_ERR_OK
)
11269 SendEquipError( msg
, pSrcItem
, pDstItem
);
11275 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11276 // or swap empty bag with another empty or not empty bag (with items exchange)
11281 if( IsInventoryPos( dst
) )
11283 ItemPosCountVec dest
;
11284 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11285 if( msg
!= EQUIP_ERR_OK
)
11287 SendEquipError( msg
, pSrcItem
, NULL
);
11291 RemoveItem(srcbag
, srcslot
, true);
11292 StoreItem( dest
, pSrcItem
, true);
11294 else if( IsBankPos ( dst
) )
11296 ItemPosCountVec dest
;
11297 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11298 if( msg
!= EQUIP_ERR_OK
)
11300 SendEquipError( msg
, pSrcItem
, NULL
);
11304 RemoveItem(srcbag
, srcslot
, true);
11305 BankItem( dest
, pSrcItem
, true);
11307 else if( IsEquipmentPos ( dst
) )
11310 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11311 if( msg
!= EQUIP_ERR_OK
)
11313 SendEquipError( msg
, pSrcItem
, NULL
);
11317 RemoveItem(srcbag
, srcslot
, true);
11318 EquipItem( dest
, pSrcItem
, true);
11319 AutoUnequipOffhandIfNeed();
11325 // attempt merge to / fill target item
11326 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11329 ItemPosCountVec sDest
;
11331 if( IsInventoryPos( dst
) )
11332 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11333 else if( IsBankPos ( dst
) )
11334 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11335 else if( IsEquipmentPos ( dst
) )
11336 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11340 // can be merge/fill
11341 if(msg
== EQUIP_ERR_OK
)
11343 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11345 RemoveItem(srcbag
, srcslot
, true);
11347 if( IsInventoryPos( dst
) )
11348 StoreItem( sDest
, pSrcItem
, true);
11349 else if( IsBankPos ( dst
) )
11350 BankItem( sDest
, pSrcItem
, true);
11351 else if( IsEquipmentPos ( dst
) )
11353 EquipItem( eDest
, pSrcItem
, true);
11354 AutoUnequipOffhandIfNeed();
11359 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11360 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11361 pSrcItem
->SetState(ITEM_CHANGED
, this);
11362 pDstItem
->SetState(ITEM_CHANGED
, this);
11365 pSrcItem
->SendUpdateToPlayer( this );
11366 pDstItem
->SendUpdateToPlayer( this );
11373 // impossible merge/fill, do real swap
11376 // check src->dest move possibility
11377 ItemPosCountVec sDest
;
11379 if( IsInventoryPos( dst
) )
11380 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11381 else if( IsBankPos( dst
) )
11382 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11383 else if( IsEquipmentPos( dst
) )
11385 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11386 if( msg
== EQUIP_ERR_OK
)
11387 msg
= CanUnequipItem( eDest
, true );
11390 if( msg
!= EQUIP_ERR_OK
)
11392 SendEquipError( msg
, pSrcItem
, pDstItem
);
11396 // check dest->src move possibility
11397 ItemPosCountVec sDest2
;
11399 if( IsInventoryPos( src
) )
11400 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11401 else if( IsBankPos( src
) )
11402 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11403 else if( IsEquipmentPos( src
) )
11405 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11406 if( msg
== EQUIP_ERR_OK
)
11407 msg
= CanUnequipItem( eDest2
, true);
11410 if( msg
!= EQUIP_ERR_OK
)
11412 SendEquipError( msg
, pDstItem
, pSrcItem
);
11416 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11417 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11419 Bag
* emptyBag
= NULL
;
11420 Bag
* fullBag
= NULL
;
11421 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11423 emptyBag
= (Bag
*)pSrcItem
;
11424 fullBag
= (Bag
*)pDstItem
;
11426 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11428 emptyBag
= (Bag
*)pDstItem
;
11429 fullBag
= (Bag
*)pSrcItem
;
11432 // bag swap (with items exchange) case
11433 if(emptyBag
&& fullBag
)
11435 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11439 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11441 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11445 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11446 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11448 // one from items not go to empry target bag
11449 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11457 if (count
> emptyBag
->GetBagSize())
11459 // too small targeted bag
11460 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11465 count
= 0; // will pos in new bag
11466 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11468 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11472 fullBag
->RemoveItem(i
, true);
11473 emptyBag
->StoreItem(count
, bagItem
, true);
11474 bagItem
->SetState(ITEM_CHANGED
, this);
11481 // now do moves, remove...
11482 RemoveItem(dstbag
, dstslot
, false);
11483 RemoveItem(srcbag
, srcslot
, false);
11486 if( IsInventoryPos( dst
) )
11487 StoreItem(sDest
, pSrcItem
, true);
11488 else if( IsBankPos( dst
) )
11489 BankItem(sDest
, pSrcItem
, true);
11490 else if( IsEquipmentPos( dst
) )
11491 EquipItem(eDest
, pSrcItem
, true);
11494 if( IsInventoryPos( src
) )
11495 StoreItem(sDest2
, pDstItem
, true);
11496 else if( IsBankPos( src
) )
11497 BankItem(sDest2
, pDstItem
, true);
11498 else if( IsEquipmentPos( src
) )
11499 EquipItem(eDest2
, pDstItem
, true);
11501 AutoUnequipOffhandIfNeed();
11504 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11508 uint32 slot
= m_currentBuybackSlot
;
11509 // if current back slot non-empty search oldest or free
11512 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11513 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11515 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11524 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11526 if(oldest_time
> i_time
)
11528 oldest_time
= i_time
;
11534 slot
= oldest_slot
;
11537 RemoveItemFromBuyBackSlot( slot
, true );
11538 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11540 m_items
[slot
] = pItem
;
11541 time_t base
= time(NULL
);
11542 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11543 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11545 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11546 ItemPrototype
const *pProto
= pItem
->GetProto();
11548 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11550 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11551 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11553 // move to next (for non filled list is move most optimized choice)
11554 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11555 ++m_currentBuybackSlot
;
11559 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11561 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11562 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11563 return m_items
[slot
];
11567 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11569 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11570 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11572 Item
*pItem
= m_items
[slot
];
11575 pItem
->RemoveFromWorld();
11576 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11579 m_items
[slot
] = NULL
;
11581 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11582 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11583 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11584 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11586 // if current backslot is filled set to now free slot
11587 if(m_items
[m_currentBuybackSlot
])
11588 m_currentBuybackSlot
= slot
;
11592 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11594 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11595 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11596 data
<< uint8(msg
);
11600 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11601 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11602 data
<< uint8(0); // not 0 there...
11604 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11609 if(ItemPrototype
const* proto
= pItem
->GetProto())
11610 level
= proto
->RequiredLevel
;
11612 data
<< uint32(level
); // new 2.4.0
11615 GetSession()->SendPacket(&data
);
11618 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11620 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11621 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11622 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11623 data
<< uint32(item
);
11625 data
<< uint32(param
);
11626 data
<< uint8(msg
);
11627 GetSession()->SendPacket(&data
);
11630 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11632 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11633 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11634 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11635 data
<< uint64(guid
);
11637 data
<< uint32(param
);
11638 data
<< uint8(msg
);
11639 GetSession()->SendPacket(&data
);
11642 void Player::ClearTrade()
11645 acceptTrade
= false;
11646 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11647 tradeItems
[i
] = NULL_SLOT
;
11650 void Player::TradeCancel(bool sendback
)
11654 // send yellow "Trade canceled" message to both traders
11658 ws
->SendCancelTrade();
11659 ws
= pTrader
->GetSession();
11660 if(!ws
->PlayerLogout())
11661 ws
->SendCancelTrade();
11665 pTrader
->ClearTrade();
11666 // prevent loss of reference
11667 pTrader
->pTrader
= NULL
;
11672 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11674 if(m_itemDuration
.empty())
11677 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11679 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11682 ++itr
; // current element can be erased in UpdateDuration
11684 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11685 item
->UpdateDuration(this,time
);
11689 void Player::UpdateEnchantTime(uint32 time
)
11691 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11695 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11697 next
= m_enchantDuration
.erase(itr
);
11699 else if(itr
->leftduration
<= time
)
11701 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11702 itr
->item
->ClearEnchantment(itr
->slot
);
11703 next
= m_enchantDuration
.erase(itr
);
11705 else if(itr
->leftduration
> time
)
11707 itr
->leftduration
-= time
;
11713 void Player::AddEnchantmentDurations(Item
*item
)
11715 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11717 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11720 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11722 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11726 void Player::RemoveEnchantmentDurations(Item
*item
)
11728 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11730 if(itr
->item
== item
)
11732 // save duration in item
11733 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11734 itr
= m_enchantDuration
.erase(itr
);
11741 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11743 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11744 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11747 if(itr
->slot
==slot
)
11749 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11751 // remove from stats
11752 ApplyEnchantment(itr
->item
,slot
,false,false);
11754 itr
->item
->ClearEnchantment(slot
);
11756 // remove from update list
11757 next
= m_enchantDuration
.erase(itr
);
11763 // remove enchants from inventory items
11764 // NOTE: no need to remove these from stats, since these aren't equipped
11766 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11768 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11769 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11770 pItem
->ClearEnchantment(slot
);
11773 // in inventory bags
11774 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11776 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11779 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11781 Item
* pItem
= pBag
->GetItemByPos(j
);
11782 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11783 pItem
->ClearEnchantment(slot
);
11789 // duration == 0 will remove item enchant
11790 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11795 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11798 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11800 if(itr
->item
== item
&& itr
->slot
== slot
)
11802 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11803 m_enchantDuration
.erase(itr
);
11807 if(item
&& duration
> 0 )
11809 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11810 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11814 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11816 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11817 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11820 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11825 if(!item
->IsEquipped())
11828 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11831 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11835 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11839 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11842 for (int s
=0; s
<3; s
++)
11844 uint32 enchant_display_type
= pEnchant
->type
[s
];
11845 uint32 enchant_amount
= pEnchant
->amount
[s
];
11846 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11848 switch(enchant_display_type
)
11850 case ITEM_ENCHANTMENT_TYPE_NONE
:
11852 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11853 // processed in Player::CastItemCombatSpell
11855 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11856 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11857 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11858 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11859 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11860 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11861 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11863 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11864 if(enchant_spell_id
)
11868 int32 basepoints
= 0;
11869 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11870 if (item
->GetItemRandomPropertyId())
11872 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11875 // Search enchant_amount
11876 for (int k
=0; k
<3; k
++)
11878 if(item_rand
->enchant_id
[k
] == enchant_id
)
11880 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11886 // Cast custom spell vs all equal basepoints getted from enchant_amount
11888 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11890 CastSpell(this,enchant_spell_id
,true,item
);
11893 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11896 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11897 if (!enchant_amount
)
11899 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11902 for (int k
=0; k
<3; k
++)
11904 if(item_rand
->enchant_id
[k
] == enchant_id
)
11906 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11913 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11915 case ITEM_ENCHANTMENT_TYPE_STAT
:
11917 if (!enchant_amount
)
11919 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11920 if(item_rand_suffix
)
11922 for (int k
=0; k
<3; k
++)
11924 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11926 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11933 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11934 switch (enchant_spell_id
)
11936 case ITEM_MOD_AGILITY
:
11937 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11938 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11939 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11941 case ITEM_MOD_STRENGTH
:
11942 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11943 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11944 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11946 case ITEM_MOD_INTELLECT
:
11947 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11948 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11949 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11951 case ITEM_MOD_SPIRIT
:
11952 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11953 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11954 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11956 case ITEM_MOD_STAMINA
:
11957 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11958 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11959 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11961 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11962 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11963 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11965 case ITEM_MOD_DODGE_RATING
:
11966 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11967 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11969 case ITEM_MOD_PARRY_RATING
:
11970 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11971 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11973 case ITEM_MOD_BLOCK_RATING
:
11974 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11975 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11977 case ITEM_MOD_HIT_MELEE_RATING
:
11978 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11979 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11981 case ITEM_MOD_HIT_RANGED_RATING
:
11982 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11983 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11985 case ITEM_MOD_HIT_SPELL_RATING
:
11986 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11987 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11989 case ITEM_MOD_CRIT_MELEE_RATING
:
11990 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11991 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11993 case ITEM_MOD_CRIT_RANGED_RATING
:
11994 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11995 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11997 case ITEM_MOD_CRIT_SPELL_RATING
:
11998 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11999 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
12001 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12003 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12004 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12006 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12007 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12009 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12010 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12012 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12013 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12015 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12016 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12018 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12019 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12021 // case ITEM_MOD_HASTE_MELEE_RATING:
12022 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12024 // case ITEM_MOD_HASTE_RANGED_RATING:
12025 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12027 case ITEM_MOD_HASTE_SPELL_RATING
:
12028 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12030 case ITEM_MOD_HIT_RATING
:
12031 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12032 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12033 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12034 sLog
.outDebug("+ %u HIT", enchant_amount
);
12036 case ITEM_MOD_CRIT_RATING
:
12037 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12038 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12039 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12040 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
12042 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12043 // case ITEM_MOD_HIT_TAKEN_RATING:
12044 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12045 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12046 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12048 // case ITEM_MOD_CRIT_TAKEN_RATING:
12049 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12050 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12051 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12053 case ITEM_MOD_RESILIENCE_RATING
:
12054 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
12055 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
12056 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
12057 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
12059 case ITEM_MOD_HASTE_RATING
:
12060 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
12061 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
12062 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12063 sLog
.outDebug("+ %u HASTE", enchant_amount
);
12065 case ITEM_MOD_EXPERTISE_RATING
:
12066 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12067 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12069 case ITEM_MOD_ATTACK_POWER
:
12070 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12071 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12072 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12074 case ITEM_MOD_RANGED_ATTACK_POWER
:
12075 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12076 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12078 case ITEM_MOD_FERAL_ATTACK_POWER
:
12079 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
12080 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12082 case ITEM_MOD_SPELL_HEALING_DONE
:
12083 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12084 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
12086 case ITEM_MOD_SPELL_DAMAGE_DONE
:
12087 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12088 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
12090 case ITEM_MOD_MANA_REGENERATION
:
12091 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12092 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12094 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12095 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12096 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12098 case ITEM_MOD_SPELL_POWER
:
12099 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12100 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12101 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12108 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12110 if(getClass() == CLASS_SHAMAN
)
12112 float addValue
= 0.0f
;
12113 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12115 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12116 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12118 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12120 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12121 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12126 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12127 // processed in Player::CastItemUseSpell
12129 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12133 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12135 } /*switch(enchant_display_type)*/
12138 // visualize enchantment at player and equipped items
12139 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
12141 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
12142 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
12150 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12152 AddEnchantmentDuration(item
,slot
,duration
);
12156 // duration == 0 will remove EnchantDuration
12157 AddEnchantmentDuration(item
,slot
,0);
12162 void Player::SendEnchantmentDurations()
12164 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
12166 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
12170 void Player::SendItemDurations()
12172 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
12174 (*itr
)->SendTimeUpdate(this);
12178 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12180 if(!item
) // prevent crash
12183 // last check 2.0.10
12184 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12185 data
<< GetGUID(); // player GUID
12186 data
<< uint32(received
); // 0=looted, 1=from npc
12187 data
<< uint32(created
); // 0=received, 1=created
12188 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12189 data
<< (uint8
)item
->GetBagSlot(); // bagslot
12190 // item slot, but when added to stack: 0xFFFFFFFF
12191 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
12192 data
<< uint32(item
->GetEntry()); // item id
12193 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12194 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12195 data
<< uint32(count
); // count of items
12196 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
12198 if (broadcast
&& GetGroup())
12199 GetGroup()->BroadcastPacket(&data
);
12201 GetSession()->SendPacket(&data
);
12204 /*********************************************************/
12205 /*** QUEST SYSTEM ***/
12206 /*********************************************************/
12208 void Player::PrepareQuestMenu( uint64 guid
)
12211 QuestRelations
* pObjectQR
;
12212 QuestRelations
* pObjectQIR
;
12213 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12216 pObject
= (Object
*)pCreature
;
12217 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12218 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12222 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12225 pObject
= (Object
*)pGameObject
;
12226 pObjectQR
= &objmgr
.mGOQuestRelations
;
12227 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12233 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12236 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12238 uint32 quest_id
= i
->second
;
12239 QuestStatus status
= GetQuestStatus( quest_id
);
12240 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12241 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12242 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12243 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
12244 else if (status
== QUEST_STATUS_AVAILABLE
)
12245 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12248 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12250 uint32 quest_id
= i
->second
;
12251 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12252 if(!pQuest
) continue;
12254 QuestStatus status
= GetQuestStatus( quest_id
);
12256 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12257 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12258 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12259 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12263 void Player::SendPreparedQuest( uint64 guid
)
12265 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12266 if( questMenu
.Empty() )
12269 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12271 uint32 status
= qmi0
.m_qIcon
;
12273 // single element case
12274 if ( questMenu
.MenuItemCount() == 1 )
12276 // Auto open -- maybe also should verify there is no greeting
12277 uint32 quest_id
= qmi0
.m_qId
;
12278 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12281 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12282 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12283 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12284 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12285 // Send completable on repeatable quest if player don't have quest
12286 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12287 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12289 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12292 // multiply entries
12298 std::string title
= "";
12299 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12302 uint32 textid
= pCreature
->GetNpcTextId();
12303 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
12306 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12307 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12312 qe
= gossiptext
->Options
[0].Emotes
[0];
12314 if(!gossiptext
->Options
[0].Text_0
.empty())
12316 title
= gossiptext
->Options
[0].Text_0
;
12318 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12321 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12324 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12325 title
= nl
->Text_0
[0][loc_idx
];
12331 title
= gossiptext
->Options
[0].Text_1
;
12333 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12336 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12339 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12340 title
= nl
->Text_1
[0][loc_idx
];
12346 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12350 bool Player::IsActiveQuest( uint32 quest_id
) const
12352 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12354 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12357 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12360 QuestRelations
* pObjectQR
;
12361 QuestRelations
* pObjectQIR
;
12363 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12366 pObject
= (Object
*)pCreature
;
12367 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12368 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12372 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12375 pObject
= (Object
*)pGameObject
;
12376 pObjectQR
= &objmgr
.mGOQuestRelations
;
12377 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12383 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12384 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12386 if (itr
->second
== nextQuestID
)
12387 return objmgr
.GetQuestTemplate(nextQuestID
);
12393 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12395 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12396 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12397 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12398 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12400 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12406 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12408 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12409 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12410 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12411 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12412 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12413 && SatisfyQuestDay( pQuest
, msg
);
12416 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12418 if( !SatisfyQuestLog( msg
) )
12421 uint32 srcitem
= pQuest
->GetSrcItemId();
12424 uint32 count
= pQuest
->GetSrcItemCount();
12425 ItemPosCountVec dest
;
12426 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12428 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12429 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12431 else if( msg
!= EQUIP_ERR_OK
)
12433 SendEquipError( msg
, NULL
, NULL
);
12440 bool Player::CanCompleteQuest( uint32 quest_id
)
12444 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12445 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12446 return false; // not allow re-complete quest
12448 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12453 // auto complete quest
12454 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12457 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12460 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12462 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12464 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12469 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12471 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12473 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12476 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12481 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12484 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12487 if ( qInfo
->GetRewOrReqMoney() < 0 )
12489 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12493 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12494 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12503 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12505 // Solve problem that player don't have the quest and try complete it.
12506 // if repeatable she must be able to complete event if player don't have it.
12507 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12508 if( !CanTakeQuest(pQuest
, false) )
12511 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12512 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12513 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12516 if( !CanRewardQuest(pQuest
, false) )
12522 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12524 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12525 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12528 // daily quest can't be rewarded (25 daily quest already completed)
12529 if(!SatisfyQuestDay(pQuest
,true))
12532 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12533 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12536 // prevent receive reward with quest items in bank
12537 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12539 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12541 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12542 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12545 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12551 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12552 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12558 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12560 // prevent receive reward with quest items in bank or for not completed quest
12561 if(!CanRewardQuest(pQuest
,msg
))
12564 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12566 if( pQuest
->RewChoiceItemId
[reward
] )
12568 ItemPosCountVec dest
;
12569 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12570 if( res
!= EQUIP_ERR_OK
)
12572 SendEquipError( res
, NULL
, NULL
);
12578 if ( pQuest
->GetRewItemsCount() > 0 )
12580 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12582 if( pQuest
->RewItemId
[i
] )
12584 ItemPosCountVec dest
;
12585 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12586 if( res
!= EQUIP_ERR_OK
)
12588 SendEquipError( res
, NULL
, NULL
);
12598 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12600 uint16 log_slot
= FindQuestSlot( 0 );
12601 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12603 uint32 quest_id
= pQuest
->GetQuestId();
12605 // if not exist then created with set uState==NEW and rewarded=false
12606 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12608 // check for repeatable quests status reset
12609 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12610 questStatusData
.m_explored
= false;
12612 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12614 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12615 questStatusData
.m_itemcount
[i
] = 0;
12618 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12620 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12621 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12624 GiveQuestSourceItem( pQuest
);
12625 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12627 if( pQuest
->GetRepObjectiveFaction() )
12628 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12631 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12633 uint32 limittime
= pQuest
->GetLimitTime();
12635 // shared timed quest
12636 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12637 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12639 AddTimedQuest( quest_id
);
12640 questStatusData
.m_timer
= limittime
* 1000;
12641 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12644 questStatusData
.m_timer
= 0;
12646 SetQuestSlot(log_slot
, quest_id
, qtime
);
12648 if (questStatusData
.uState
!= QUEST_NEW
)
12649 questStatusData
.uState
= QUEST_CHANGED
;
12651 //starting initial quest script
12652 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12653 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12655 UpdateForQuestsGO();
12658 void Player::CompleteQuest( uint32 quest_id
)
12662 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12664 uint16 log_slot
= FindQuestSlot( quest_id
);
12665 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12666 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12668 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12670 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12671 RewardQuest(qInfo
,0,this,false);
12673 SendQuestComplete( quest_id
);
12678 void Player::IncompleteQuest( uint32 quest_id
)
12682 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12684 uint16 log_slot
= FindQuestSlot( quest_id
);
12685 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12686 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12690 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12692 uint32 quest_id
= pQuest
->GetQuestId();
12694 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12696 if ( pQuest
->ReqItemId
[i
] )
12697 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12700 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12701 // SetTimedQuest( 0 );
12702 m_timedquests
.erase(pQuest
->GetQuestId());
12704 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12706 if( pQuest
->RewChoiceItemId
[reward
] )
12708 ItemPosCountVec dest
;
12709 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12711 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12712 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12717 if ( pQuest
->GetRewItemsCount() > 0 )
12719 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12721 if( pQuest
->RewItemId
[i
] )
12723 ItemPosCountVec dest
;
12724 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12726 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12727 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12733 RewardReputation( pQuest
);
12735 if( pQuest
->GetRewSpellCast() > 0 )
12736 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12737 else if( pQuest
->GetRewSpell() > 0)
12738 CastSpell( this, pQuest
->GetRewSpell(), true);
12740 uint16 log_slot
= FindQuestSlot( quest_id
);
12741 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12742 SetQuestSlot(log_slot
,0);
12744 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12746 // Not give XP in case already completed once repeatable quest
12747 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12749 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12750 GiveXP( XP
, NULL
);
12752 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12754 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12755 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12758 if(pQuest
->GetRewHonorableKills())
12759 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12762 if(pQuest
->GetCharTitleId())
12764 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12765 SetTitle(titleEntry
);
12768 if(pQuest
->GetBonusTalents())
12770 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12771 InitTalentForLevel();
12774 // Send reward mail
12775 if(pQuest
->GetRewMailTemplateId())
12777 MailMessageType mailType
;
12778 uint32 senderGuidOrEntry
;
12779 switch(questGiver
->GetTypeId())
12782 mailType
= MAIL_CREATURE
;
12783 senderGuidOrEntry
= questGiver
->GetEntry();
12785 case TYPEID_GAMEOBJECT
:
12786 mailType
= MAIL_GAMEOBJECT
;
12787 senderGuidOrEntry
= questGiver
->GetEntry();
12790 mailType
= MAIL_ITEM
;
12791 senderGuidOrEntry
= questGiver
->GetEntry();
12793 case TYPEID_PLAYER
:
12794 mailType
= MAIL_NORMAL
;
12795 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12798 mailType
= MAIL_NORMAL
;
12799 senderGuidOrEntry
= GetGUIDLow();
12803 Loot questMailLoot
;
12805 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12808 MailItemsInfo mi
; // item list preparing
12810 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12811 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12813 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12815 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12817 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12818 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12823 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12826 if(pQuest
->IsDaily())
12828 SetDailyQuestStatus(quest_id
);
12829 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12832 if ( !pQuest
->IsRepeatable() )
12833 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12835 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12837 q_status
.m_rewarded
= true;
12840 SendQuestReward( pQuest
, XP
, questGiver
);
12842 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12844 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12847 void Player::FailQuest( uint32 quest_id
)
12851 IncompleteQuest( quest_id
);
12853 uint16 log_slot
= FindQuestSlot( quest_id
);
12854 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12856 SetQuestSlotTimer(log_slot
, 1 );
12857 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12859 SendQuestFailed( quest_id
);
12863 void Player::FailTimedQuest( uint32 quest_id
)
12867 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12869 q_status
.m_timer
= 0;
12870 if (q_status
.uState
!= QUEST_NEW
)
12871 q_status
.uState
= QUEST_CHANGED
;
12873 IncompleteQuest( quest_id
);
12875 uint16 log_slot
= FindQuestSlot( quest_id
);
12876 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12878 SetQuestSlotTimer(log_slot
, 1 );
12879 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12881 SendQuestTimerFailed( quest_id
);
12885 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12887 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12888 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12890 // skip zone zoneOrSort and 0 case skillOrClass
12891 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12894 int32 questSort
= -zoneOrSort
;
12895 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12897 // check class sort cases in zoneOrSort
12898 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12901 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12906 if( skillOrClass
< 0 )
12908 uint8 reqClass
= -int32(skillOrClass
);
12909 if(getClass() != reqClass
)
12912 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12917 else if( skillOrClass
> 0 )
12919 uint32 reqSkill
= skillOrClass
;
12920 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12923 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12931 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12933 if( getLevel() < qInfo
->GetMinLevel() )
12936 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12942 bool Player::SatisfyQuestLog( bool msg
)
12945 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12950 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12951 GetSession()->SendPacket( &data
);
12952 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12957 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12959 // No previous quest (might be first quest in a series)
12960 if( qInfo
->prevQuests
.empty())
12963 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12965 uint32 prevId
= abs(*iter
);
12967 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12968 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12970 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12972 // If any of the positive previous quests completed, return true
12973 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12975 // skip one-from-all exclusive group
12976 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12979 // each-from-all exclusive group ( < 0)
12980 // can be start if only all quests in prev quest exclusive group completed and rewarded
12981 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12982 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12984 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12986 for(; iter
!= end
; ++iter
)
12988 uint32 exclude_Id
= iter
->second
;
12990 // skip checked quest id, only state of other quests in group is interesting
12991 if(exclude_Id
== prevId
)
12994 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12996 // alternative quest from group also must be completed and rewarded(reported)
12997 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
13000 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13006 // If any of the negative previous quests active, return true
13007 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13008 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
13010 // skip one-from-all exclusive group
13011 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13014 // each-from-all exclusive group ( < 0)
13015 // can be start if only all quests in prev quest exclusive group active
13016 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13017 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13019 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13021 for(; iter
!= end
; ++iter
)
13023 uint32 exclude_Id
= iter
->second
;
13025 // skip checked quest id, only state of other quests in group is interesting
13026 if(exclude_Id
== prevId
)
13029 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13031 // alternative quest from group also must be active
13032 if( i_exstatus
== mQuestStatus
.end() ||
13033 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13034 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13037 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13046 // Has only positive prev. quests in non-rewarded state
13047 // and negative prev. quests in non-active state
13049 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13054 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13056 uint32 reqraces
= qInfo
->GetRequiredRaces();
13057 if ( reqraces
== 0 )
13059 if( (reqraces
& getRaceMask()) == 0 )
13062 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13068 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13070 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13071 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13074 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13078 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13079 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13082 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13089 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13091 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13092 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13095 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13101 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
13103 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
13106 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13112 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13114 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13115 if(qInfo
->GetExclusiveGroup() <= 0)
13118 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13119 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13121 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13123 for(; iter
!= end
; ++iter
)
13125 uint32 exclude_Id
= iter
->second
;
13127 // skip checked quest id, only state of other quests in group is interesting
13128 if(exclude_Id
== qInfo
->GetQuestId())
13131 // not allow have daily quest if daily quest from exclusive group already recently completed
13132 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13133 if( !SatisfyQuestDay(Nquest
, false) )
13136 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13140 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13142 // alternative quest already started or completed
13143 if( i_exstatus
!= mQuestStatus
.end()
13144 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13147 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13154 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13156 if(!qInfo
->GetNextQuestInChain())
13159 // next quest in chain already started or completed
13160 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13161 if( itr
!= mQuestStatus
.end()
13162 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13165 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13169 // check for all quests further up the chain
13170 // only necessary if there are quest chains with more than one quest that can be skipped
13171 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13175 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13177 // No previous quest in chain
13178 if( qInfo
->prevChainQuests
.empty())
13181 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13183 uint32 prevId
= *iter
;
13185 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13187 if( i_prevstatus
!= mQuestStatus
.end() )
13189 // If any of the previous quests in chain active, return false
13190 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13191 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13194 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13199 // check for all quests further down the chain
13200 // only necessary if there are quest chains with more than one quest that can be skipped
13201 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13205 // No previous quest in chain active
13209 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13211 if(!qInfo
->IsDaily())
13214 bool have_slot
= false;
13215 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13217 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13218 if(qInfo
->GetQuestId()==id
)
13228 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13235 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13237 uint32 srcitem
= pQuest
->GetSrcItemId();
13240 uint32 count
= pQuest
->GetSrcItemCount();
13244 ItemPosCountVec dest
;
13245 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13246 if( msg
== EQUIP_ERR_OK
)
13248 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13249 SendNewItem(item
, count
, true, false);
13252 // player already have max amount required item, just report success
13253 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13256 SendEquipError( msg
, NULL
, NULL
);
13263 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13265 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13268 uint32 srcitem
= qInfo
->GetSrcItemId();
13271 uint32 count
= qInfo
->GetSrcItemCount();
13275 // exist one case when destroy source quest item not possible:
13276 // non un-equippable item (equipped non-empty bag, for example)
13277 uint8 res
= CanUnequipItems(srcitem
,count
);
13278 if(res
!= EQUIP_ERR_OK
)
13281 SendEquipError( res
, NULL
, NULL
);
13285 DestroyItemCount(srcitem
, count
, true, true);
13291 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13293 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13296 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13297 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13298 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13299 && !qInfo
->IsRepeatable() )
13300 return itr
->second
.m_rewarded
;
13307 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13311 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13312 if( itr
!= mQuestStatus
.end() )
13313 return itr
->second
.m_status
;
13315 return QUEST_STATUS_NONE
;
13318 bool Player::CanShareQuest(uint32 quest_id
) const
13320 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13321 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13323 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13324 if( itr
!= mQuestStatus
.end() )
13325 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13330 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13332 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13335 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13337 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13338 m_timedquests
.erase(qInfo
->GetQuestId());
13341 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13343 q_status
.m_status
= status
;
13344 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13347 UpdateForQuestsGO();
13350 // not used in MaNGOS, but used in scripting code
13351 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13353 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13357 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13358 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13359 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13364 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13366 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13368 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13370 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13371 if( reqitemcount
!= 0 )
13373 uint32 quest_id
= pQuest
->GetQuestId();
13374 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13376 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13377 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13383 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13385 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13386 if ( GetQuestSlotQuestId(i
) == quest_id
)
13389 return MAX_QUEST_LOG_SIZE
;
13392 void Player::AreaExploredOrEventHappens( uint32 questId
)
13396 uint16 log_slot
= FindQuestSlot( questId
);
13397 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13399 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13401 if(!q_status
.m_explored
)
13403 q_status
.m_explored
= true;
13404 if (q_status
.uState
!= QUEST_NEW
)
13405 q_status
.uState
= QUEST_CHANGED
;
13408 if( CanCompleteQuest( questId
) )
13409 CompleteQuest( questId
);
13413 //not used in mangosd, function for external script library
13414 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13416 if( Group
*pGroup
= GetGroup() )
13418 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13420 Player
*pGroupGuy
= itr
->getSource();
13422 // for any leave or dead (with not released body) group member at appropriate distance
13423 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13424 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13428 AreaExploredOrEventHappens(questId
);
13431 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13433 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13435 uint32 questid
= GetQuestSlotQuestId(i
);
13436 if ( questid
== 0 )
13439 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13441 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13444 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13445 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13448 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13450 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13451 if ( reqitem
== entry
)
13453 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13454 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13455 if ( curitemcount
< reqitemcount
)
13457 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13458 q_status
.m_itemcount
[j
] += additemcount
;
13459 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13461 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13463 if ( CanCompleteQuest( questid
) )
13464 CompleteQuest( questid
);
13469 UpdateForQuestsGO();
13470 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13473 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13475 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13477 uint32 questid
= GetQuestSlotQuestId(i
);
13480 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13483 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13486 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13488 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13489 if ( reqitem
== entry
)
13491 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13493 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13494 uint32 curitemcount
;
13495 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13496 curitemcount
= q_status
.m_itemcount
[j
];
13498 curitemcount
= GetItemCount(entry
,true);
13499 if ( curitemcount
< reqitemcount
+ count
)
13501 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13502 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13503 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13505 IncompleteQuest( questid
);
13511 UpdateForQuestsGO();
13514 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13516 uint32 addkillcount
= 1;
13517 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13518 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13520 uint32 questid
= GetQuestSlotQuestId(i
);
13524 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13527 // just if !ingroup || !noraidgroup || raidgroup
13528 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13529 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13531 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13533 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13535 // skip GO activate objective or none
13536 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13539 // skip Cast at creature objective
13540 if(qInfo
->ReqSpell
[j
] !=0 )
13543 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13545 if ( reqkill
== entry
)
13547 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13548 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13549 if ( curkillcount
< reqkillcount
)
13551 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13552 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13554 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13556 if ( CanCompleteQuest( questid
) )
13557 CompleteQuest( questid
);
13559 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13568 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13570 bool isCreature
= IS_CREATURE_GUID(guid
);
13572 uint32 addCastCount
= 1;
13573 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13575 uint32 questid
= GetQuestSlotQuestId(i
);
13579 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13583 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13585 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13587 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13589 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13591 // skip kill creature objective (0) or wrong spell casts
13592 if(qInfo
->ReqSpell
[j
] != spell_id
)
13595 uint32 reqTarget
= 0;
13599 // creature activate objectives
13600 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13601 // checked at quest_template loading
13602 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13606 // GO activate objective
13607 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13608 // checked at quest_template loading
13609 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13612 // other not this creature/GO related objectives
13613 if( reqTarget
!= entry
)
13616 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13617 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13618 if ( curCastCount
< reqCastCount
)
13620 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13621 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13623 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13626 if ( CanCompleteQuest( questid
) )
13627 CompleteQuest( questid
);
13629 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13637 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13639 uint32 addTalkCount
= 1;
13640 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13642 uint32 questid
= GetQuestSlotQuestId(i
);
13646 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13650 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13652 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13654 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13656 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13658 // skip spell casts and Gameobject objectives
13659 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13662 uint32 reqTarget
= 0;
13664 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13665 // checked at quest_template loading
13666 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13670 if ( reqTarget
== entry
)
13672 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13673 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13674 if ( curTalkCount
< reqTalkCount
)
13676 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13677 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13679 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13681 if ( CanCompleteQuest( questid
) )
13682 CompleteQuest( questid
);
13684 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13693 void Player::MoneyChanged( uint32 count
)
13695 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13697 uint32 questid
= GetQuestSlotQuestId(i
);
13701 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13702 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13704 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13706 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13708 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13710 if ( CanCompleteQuest( questid
) )
13711 CompleteQuest( questid
);
13714 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13716 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13717 IncompleteQuest( questid
);
13723 bool Player::HasQuestForItem( uint32 itemid
) const
13725 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13727 uint32 questid
= GetQuestSlotQuestId(i
);
13728 if ( questid
== 0 )
13731 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13732 if(qs_itr
== mQuestStatus
.end())
13735 QuestStatusData
const& q_status
= qs_itr
->second
;
13737 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13739 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13743 // hide quest if player is in raid-group and quest is no raid quest
13744 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13747 // There should be no mixed ReqItem/ReqSource drop
13748 // This part for ReqItem drop
13749 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13751 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13754 // This part - for ReqSource
13755 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13757 // examined item is a source item
13758 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13760 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13762 // total count of created ReqItems and SourceItems is less than ReqItemCount
13763 if(qinfo
->ReqItemId
[idx
] != 0 &&
13764 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13767 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13768 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13770 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13773 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13774 else if(qinfo
->ReqSpell
[idx
] != 0)
13776 // not casted and need more reagents/item for use.
13777 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13787 void Player::SendQuestComplete( uint32 quest_id
)
13791 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13792 data
<< uint32(quest_id
);
13793 GetSession()->SendPacket( &data
);
13794 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13798 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13800 uint32 questid
= pQuest
->GetQuestId();
13801 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13802 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13803 data
<< uint32(questid
);
13805 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13807 data
<< uint32(XP
);
13808 data
<< uint32(pQuest
->GetRewOrReqMoney());
13813 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13816 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13817 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13818 GetSession()->SendPacket( &data
);
13820 if (pQuest
->GetQuestCompleteScript() != 0)
13821 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13824 void Player::SendQuestFailed( uint32 quest_id
)
13828 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13830 data
<< uint32(0); // failed reason (4 for inventory is full)
13831 GetSession()->SendPacket( &data
);
13832 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13836 void Player::SendQuestTimerFailed( uint32 quest_id
)
13840 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13842 GetSession()->SendPacket( &data
);
13843 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13847 void Player::SendCanTakeQuestResponse( uint32 msg
)
13849 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13850 data
<< uint32(msg
);
13851 GetSession()->SendPacket( &data
);
13852 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13855 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13859 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13860 data
<< uint64(pPlayer
->GetGUID());
13861 data
<< uint8(msg
); // valid values: 0-8
13862 GetSession()->SendPacket( &data
);
13863 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13867 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13869 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13870 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13871 //data << pQuest->ReqItemId[item_idx];
13873 GetSession()->SendPacket( &data
);
13876 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13878 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13880 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13882 // client expected gameobject template id in form (id|0x80000000)
13883 entry
= (-entry
) | 0x80000000;
13885 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13886 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13887 data
<< uint32(pQuest
->GetQuestId());
13888 data
<< uint32(entry
);
13889 data
<< uint32(old_count
+ add_count
);
13890 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13891 data
<< uint64(guid
);
13892 GetSession()->SendPacket(&data
);
13894 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13895 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13896 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13899 /*********************************************************/
13900 /*** LOAD SYSTEM ***/
13901 /*********************************************************/
13903 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13905 bool delete_result
= true;
13908 // 0 1 2 3 4 5 6 7 8 9
13909 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13910 if(!result
) return false;
13912 else delete_result
= false;
13914 Field
*fields
= result
->Fetch();
13916 if(!LoadValues( fields
[1].GetString()))
13918 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13919 if(delete_result
) delete result
;
13923 // overwrite possible wrong/corrupted guid
13924 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13926 m_name
= fields
[2].GetCppString();
13928 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13929 SetMapId(fields
[6].GetUInt32());
13930 // the instance id is not needed at character enum
13932 m_Played_time
[0] = fields
[7].GetUInt32();
13933 m_Played_time
[1] = fields
[8].GetUInt32();
13935 m_atLoginFlags
= fields
[9].GetUInt32();
13937 // I don't see these used anywhere ..
13940 _LoadBoundInstances();*/
13942 if (delete_result
) delete result
;
13944 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13947 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13948 m_deathState
= DEAD
;
13953 void Player::_LoadDeclinedNames(QueryResult
* result
)
13959 delete m_declinedname
;
13961 m_declinedname
= new DeclinedName
;
13962 Field
*fields
= result
->Fetch();
13963 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13964 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13969 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13971 // arenateamid, played_week, played_season, personal_rating
13972 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13978 Field
*fields
= result
->Fetch();
13980 uint32 arenateamid
= fields
[0].GetUInt32();
13981 uint32 played_week
= fields
[1].GetUInt32();
13982 uint32 played_season
= fields
[2].GetUInt32();
13983 uint32 personal_rating
= fields
[3].GetUInt32();
13985 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13988 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13991 uint8 arenaSlot
= aTeam
->GetSlot();
13993 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13994 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13995 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13996 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13997 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13998 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
14000 }while (result
->NextRow());
14004 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14006 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14010 Field
*fields
= result
->Fetch();
14012 x
= fields
[0].GetFloat();
14013 y
= fields
[1].GetFloat();
14014 z
= fields
[2].GetFloat();
14015 o
= fields
[3].GetFloat();
14016 mapid
= fields
[4].GetUInt32();
14017 in_flight
= !fields
[5].GetCppString().empty();
14023 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
14025 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
14029 Field
*fields
= result
->Fetch();
14031 data
= StrSplit(fields
[0].GetCppString(), " ");
14038 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
14040 if(index
>= data
.size())
14043 return (uint32
)atoi(data
[index
].c_str());
14046 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
14049 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
14050 memcpy(&result
, &temp
, sizeof(result
));
14055 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
14058 if(!LoadValuesArrayFromDB(data
,guid
))
14061 return GetUInt32ValueFromArray(data
,index
);
14064 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
14067 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
14068 memcpy(&result
, &temp
, sizeof(result
));
14073 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14075 //// 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 34 35 36 37 38 39 40
14076 //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,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
14077 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14081 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14085 Field
*fields
= result
->Fetch();
14087 uint32 dbAccountId
= fields
[1].GetUInt32();
14089 // check if the character's account in the db and the logged in account match.
14090 // player should be able to load/delete character only with correct account!
14091 if( dbAccountId
!= GetSession()->GetAccountId() )
14093 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14098 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14100 m_name
= fields
[3].GetCppString();
14102 // check name limitations
14103 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
14106 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14110 if(!LoadValues( fields
[2].GetString()))
14112 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
14117 // overwrite possible wrong/corrupted guid
14118 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14120 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14121 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14123 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
14124 SetVisibleItemSlot(slot
,NULL
);
14128 delete m_items
[slot
];
14129 m_items
[slot
] = NULL
;
14133 // update money limits
14134 if(GetMoney() > MAX_MONEY_AMOUNT
)
14135 SetMoney(MAX_MONEY_AMOUNT
);
14137 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14140 m_race
= fields
[4].GetUInt8();
14141 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14142 //Other way is to saves m_team into characters table.
14143 setFactionForRace(m_race
);
14146 m_class
= fields
[5].GetUInt8();
14148 // load home bind and check in same time class/race pair, it used later for restore broken positions
14149 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14152 InitPrimaryProffesions(); // to max set before any spell loaded
14154 // init saved position, and fix it later if problematic
14155 uint32 transGUID
= fields
[24].GetUInt32();
14156 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
14157 SetMapId(fields
[9].GetUInt32());
14158 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
14160 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14162 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14164 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
14165 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
14166 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
14168 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14170 // check arena teams integrity
14171 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14173 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14177 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
14178 if(at
->HaveMember(GetGUID()))
14181 // arena team not exist or not member, cleanup fields
14182 for(int j
=0; j
< 6; ++j
)
14183 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
14186 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14188 if(!IsPositionValid())
14190 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());
14191 RelocateToHomebind();
14195 m_movementInfo
.t_x
= 0.0f
;
14196 m_movementInfo
.t_y
= 0.0f
;
14197 m_movementInfo
.t_z
= 0.0f
;
14198 m_movementInfo
.t_o
= 0.0f
;
14201 uint32 bgid
= fields
[34].GetUInt32();
14202 uint32 bgteam
= fields
[35].GetUInt32();
14204 if(bgid
) //saved in BattleGround
14206 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
14208 // check entry point and fix to homebind if need
14209 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
14210 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
14211 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
14213 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
);
14215 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
14217 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14218 uint32 queueSlot
= AddBattleGroundQueueId(bgQueueTypeId
);
14220 SetBattleGroundId(currentBg
->GetInstanceID());
14223 //join player to battleground group
14224 currentBg
->PlayerRelogin(this);
14225 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
14227 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14231 Relocate(GetBattleGroundEntryPoint());
14232 //RemoveArenaAuras(true);
14237 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14238 // if server restart after player save in BG or area
14239 // player can have current coordinates in to BG/Arean map, fix this
14240 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14242 // return to BG master
14243 SetMapId(fields
[36].GetUInt32());
14244 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
14246 // check entry point and fix to homebind if need
14247 mapEntry
= sMapStore
.LookupEntry(GetMapId());
14248 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
14249 RelocateToHomebind();
14253 if (transGUID
!= 0)
14255 m_movementInfo
.t_x
= fields
[20].GetFloat();
14256 m_movementInfo
.t_y
= fields
[21].GetFloat();
14257 m_movementInfo
.t_z
= fields
[22].GetFloat();
14258 m_movementInfo
.t_o
= fields
[23].GetFloat();
14260 if( !MaNGOS::IsValidMapCoord(
14261 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14262 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
14263 // transport size limited
14264 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
14266 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14267 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14268 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
14270 RelocateToHomebind();
14272 m_movementInfo
.t_x
= 0.0f
;
14273 m_movementInfo
.t_y
= 0.0f
;
14274 m_movementInfo
.t_z
= 0.0f
;
14275 m_movementInfo
.t_o
= 0.0f
;
14281 if (transGUID
!= 0)
14283 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
14285 if( (*iter
)->GetGUIDLow() == transGUID
)
14287 m_transport
= *iter
;
14288 m_transport
->AddPassenger(this);
14289 SetMapId(m_transport
->GetMapId());
14296 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14299 RelocateToHomebind();
14301 m_movementInfo
.t_x
= 0.0f
;
14302 m_movementInfo
.t_y
= 0.0f
;
14303 m_movementInfo
.t_z
= 0.0f
;
14304 m_movementInfo
.t_o
= 0.0f
;
14310 // NOW player must have valid map
14311 // load the player's map here if it's not already loaded
14312 Map
*map
= GetMap();
14314 // since the player may not be bound to the map yet, make sure subsequent
14315 // getmap calls won't create new maps
14316 SetInstanceId(map
->GetInstanceId());
14318 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14319 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14321 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14323 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14325 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());
14328 SaveRecallPosition();
14330 time_t now
= time(NULL
);
14331 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14333 // since last logout (in seconds)
14334 uint64 time_diff
= uint64(now
- logoutTime
);
14336 // set value, including drunk invisibility detection
14337 // calculate sobering. after 15 minutes logged out, the player will be sober again
14339 if(time_diff
> 15*MINUTE
)
14342 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14343 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14344 SetDrunkValue(newDrunkenValue
);
14346 m_rest_bonus
= fields
[15].GetFloat();
14347 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14348 float bubble0
= 0.031;
14349 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14350 float bubble1
= 0.125;
14352 if((int32
)fields
[16].GetUInt32() > 0)
14354 float bubble
= fields
[17].GetUInt32() > 0
14355 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14356 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14358 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14361 m_cinematic
= fields
[12].GetUInt32();
14362 m_Played_time
[0]= fields
[13].GetUInt32();
14363 m_Played_time
[1]= fields
[14].GetUInt32();
14365 m_resetTalentsCost
= fields
[18].GetUInt32();
14366 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14368 // reserve some flags
14369 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14371 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14372 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14374 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14376 uint32 extraflags
= fields
[25].GetUInt32();
14378 m_stableSlots
= fields
[26].GetUInt32();
14379 if(m_stableSlots
> 4)
14381 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14385 m_atLoginFlags
= fields
[27].GetUInt32();
14388 // Update Honor kills data
14389 m_lastHonorUpdateTime
= logoutTime
;
14390 UpdateHonorFields();
14392 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14393 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14394 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14396 std::string taxi_nodes
= fields
[31].GetCppString();
14400 // clear channel spell data (if saved at channel spell casting)
14401 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14402 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14404 // clear charm/summon related fields
14411 // reset some aura modifiers before aura apply
14412 SetFarSightGUID(0);
14413 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14414 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14418 // make sure the unit is considered out of combat for proper loading
14421 // make sure the unit is considered not in duel for proper loading
14422 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14423 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14425 // remember loaded power/health values to restore after stats initialization and modifier applying
14426 uint32 savedHealth
= GetHealth();
14427 uint32 savedPower
[MAX_POWERS
];
14428 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14429 savedPower
[i
] = GetPower(Powers(i
));
14431 // reset stats before loading any modifiers
14432 InitStatsForLevel();
14433 InitTaxiNodesForLevel();
14434 InitGlyphsForLevel();
14437 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14439 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14442 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14445 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14446 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14447 m_deathState
= DEAD
;
14449 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14451 // after spell load, learn rewarded spell if need also
14452 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14453 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14455 // after spell and quest load
14456 InitTalentForLevel();
14457 learnDefaultSpells();
14459 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14461 // must be before inventory (some items required reputation check)
14462 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14464 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14466 // update items with duration and realtime
14467 UpdateItemDuration(time_diff
, true);
14469 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14471 // unread mails and next delivery time, actual mails not loaded
14472 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14474 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14476 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14477 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14478 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14480 if(!HasTitle(curTitle
))
14481 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14484 // Not finish taxi flight path
14485 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14487 // problems with taxi path loading
14488 TaxiNodesEntry
const* nodeEntry
= NULL
;
14489 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14490 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14492 if(!nodeEntry
) // don't know taxi start node, to homebind
14494 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14495 RelocateToHomebind();
14496 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14498 else // have start node, to it
14500 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14501 SetMapId(nodeEntry
->map_id
);
14502 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14503 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14505 m_taxi
.ClearTaxiDestinations();
14507 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14509 // save source node as recall coord to prevent recall and fall from sky
14510 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14511 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14512 m_recallMap
= nodeEntry
->map_id
;
14513 m_recallX
= nodeEntry
->x
;
14514 m_recallY
= nodeEntry
->y
;
14515 m_recallZ
= nodeEntry
->z
;
14517 // flight will started later
14520 // has to be called after last Relocate() in Player::LoadFromDB
14521 SetFallInformation(0, GetPositionZ());
14523 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14525 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14526 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14528 RemoveAllAurasOnDeath();
14530 //apply all stat bonuses from items and auras
14531 SetCanModifyStats(true);
14534 // restore remembered power/health values (but not more max values)
14535 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14536 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14537 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14539 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14543 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14545 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14548 case 0: break; // disable
14549 case 1: SetGameMaster(true); break; // enable
14550 case 2: // save state
14551 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14552 SetGameMaster(true);
14556 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14559 case 0: SetGMVisible(false); break; // invisible
14560 case 1: break; // visible
14561 case 2: // save state
14562 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14563 SetGMVisible(false);
14567 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14570 case 0: break; // disable
14571 case 1: SetAcceptTicket(true); break; // enable
14572 case 2: // save state
14573 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14574 SetAcceptTicket(true);
14578 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14581 case 0: break; // disable
14582 case 1: SetGMChat(true); break; // enable
14583 case 2: // save state
14584 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14589 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14592 case 0: break; // disable
14593 case 1: SetAcceptWhispers(true); break; // enable
14594 case 2: // save state
14595 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14596 SetAcceptWhispers(true);
14601 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14603 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14604 m_achievementMgr
.CheckAllAchievementCriteria();
14608 bool Player::isAllowedToLoot(Creature
* creature
)
14610 if(Player
* recipient
= creature
->GetLootRecipient())
14612 if (recipient
== this)
14614 if( Group
* otherGroup
= recipient
->GetGroup())
14616 Group
* thisGroup
= GetGroup();
14619 return thisGroup
== otherGroup
;
14624 // prevent other players from looting if the recipient got disconnected
14625 return !creature
->hasLootRecipient();
14628 void Player::_LoadActions(QueryResult
*result
)
14630 m_actionButtons
.clear();
14632 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14638 Field
*fields
= result
->Fetch();
14640 uint8 button
= fields
[0].GetUInt8();
14642 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
14644 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14646 while( result
->NextRow() );
14652 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14655 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14656 m_modAuras
[i
].clear();
14658 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14664 Field
*fields
= result
->Fetch();
14665 uint64 caster_guid
= fields
[0].GetUInt64();
14666 uint32 spellid
= fields
[1].GetUInt32();
14667 uint32 effindex
= fields
[2].GetUInt32();
14668 uint32 stackcount
= fields
[3].GetUInt32();
14669 int32 damage
= (int32
)fields
[4].GetUInt32();
14670 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14671 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14672 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14674 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14677 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14683 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14687 // negative effects should continue counting down after logout
14688 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14690 if(remaintime
<= int32(timediff
))
14693 remaintime
-= timediff
;
14696 // prevent wrong values of remaincharges
14697 if(spellproto
->procCharges
)
14699 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14700 remaincharges
= spellproto
->procCharges
;
14705 //do not load single target auras (unless they were cast by the player)
14706 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14709 for(uint32 i
=0; i
<stackcount
; i
++)
14711 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14713 damage
= aura
->GetModifier()->m_amount
;
14714 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14716 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14719 while( result
->NextRow() );
14724 if(m_class
== CLASS_WARRIOR
)
14725 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14728 void Player::_LoadGlyphAuras()
14730 for (uint8 i
= 0; i
<= MAX_GLYPH_SLOT_INDEX
; ++i
)
14732 if (uint32 glyph
= GetGlyph(i
))
14734 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14736 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14738 if(gp
->TypeFlags
== gs
->TypeFlags
)
14740 CastSpell(this, gp
->SpellId
, true);
14744 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14747 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14750 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14752 // On any error remove glyph
14758 void Player::LoadCorpse()
14762 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14766 if(Corpse
*corpse
= GetCorpse())
14768 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14772 //Prevent Dead Player login without corpse
14773 ResurrectPlayer(0.5f
);
14778 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14780 //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());
14781 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14782 //NOTE: the "order by `bag`" is important because it makes sure
14783 //the bagMap is filled before items in the bags are loaded
14784 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14785 //expected to be equipped before offhand items (TODO: fixme)
14787 uint32 zone
= GetZoneId();
14791 std::list
<Item
*> problematicItems
;
14793 // prevent items from being added to the queue when stored
14794 m_itemUpdateQueueBlocked
= true;
14797 Field
*fields
= result
->Fetch();
14798 uint32 bag_guid
= fields
[1].GetUInt32();
14799 uint8 slot
= fields
[2].GetUInt8();
14800 uint32 item_guid
= fields
[3].GetUInt32();
14801 uint32 item_id
= fields
[4].GetUInt32();
14803 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14807 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14808 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14809 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14813 Item
*item
= NewItemOrBag(proto
);
14815 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14817 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14818 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14819 item
->FSetState(ITEM_REMOVED
);
14820 item
->SaveToDB(); // it also deletes item object !
14824 // not allow have in alive state item limited to another map/zone
14825 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14827 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14828 item
->FSetState(ITEM_REMOVED
);
14829 item
->SaveToDB(); // it also deletes item object !
14833 // "Conjured items disappear if you are logged out for more than 15 minutes"
14834 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14836 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14837 item
->FSetState(ITEM_REMOVED
);
14838 item
->SaveToDB(); // it also deletes item object !
14842 bool success
= true;
14846 // the item is not in a bag
14847 item
->SetContainer( NULL
);
14848 item
->SetSlot(slot
);
14850 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14852 ItemPosCountVec dest
;
14853 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14854 item
= StoreItem(dest
, item
, true);
14858 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14861 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14862 QuickEquipItem(dest
, item
);
14866 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14868 ItemPosCountVec dest
;
14869 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14870 item
= BankItem(dest
, item
, true);
14877 // store bags that may contain items in them
14878 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14879 bagMap
[item_guid
] = (Bag
*)item
;
14884 item
->SetSlot(NULL_SLOT
);
14885 // the item is in a bag, find the bag
14886 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14887 if(itr
!= bagMap
.end())
14888 itr
->second
->StoreItem(slot
, item
, true );
14893 // item's state may have changed after stored
14895 item
->SetState(ITEM_UNCHANGED
, this);
14898 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
);
14899 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14900 problematicItems
.push_back(item
);
14902 } while (result
->NextRow());
14905 m_itemUpdateQueueBlocked
= false;
14907 // send by mail problematic items
14908 while(!problematicItems
.empty())
14911 MailItemsInfo mi
; // item list preparing
14913 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14915 Item
* item
= problematicItems
.front();
14916 problematicItems
.pop_front();
14918 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14921 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14923 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14927 _ApplyAllItemMods();
14930 // load mailed item which should receive current player
14931 void Player::_LoadMailedItems(Mail
*mail
)
14933 // data needs to be at first place for Item::LoadFromDB
14934 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
);
14940 Field
*fields
= result
->Fetch();
14941 uint32 item_guid_low
= fields
[1].GetUInt32();
14942 uint32 item_template
= fields
[2].GetUInt32();
14944 mail
->AddItem(item_guid_low
, item_template
);
14946 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14950 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
);
14951 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14952 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14956 Item
*item
= NewItemOrBag(proto
);
14958 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14960 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14961 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14962 item
->FSetState(ITEM_REMOVED
);
14963 item
->SaveToDB(); // it also deletes item object !
14968 } while (result
->NextRow());
14973 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14975 //set a count of unread mails
14976 //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);
14979 Field
*fieldMail
= resultUnread
->Fetch();
14980 unReadMails
= fieldMail
[0].GetUInt8();
14981 delete resultUnread
;
14984 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14985 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14986 if (resultDelivery
)
14988 Field
*fieldMail
= resultDelivery
->Fetch();
14989 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14990 delete resultDelivery
;
14994 void Player::_LoadMail()
14997 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14998 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());
15003 Field
*fields
= result
->Fetch();
15004 Mail
*m
= new Mail
;
15005 m
->messageID
= fields
[0].GetUInt32();
15006 m
->messageType
= fields
[1].GetUInt8();
15007 m
->sender
= fields
[2].GetUInt32();
15008 m
->receiver
= fields
[3].GetUInt32();
15009 m
->subject
= fields
[4].GetCppString();
15010 m
->itemTextId
= fields
[5].GetUInt32();
15011 bool has_items
= fields
[6].GetBool();
15012 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15013 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15014 m
->money
= fields
[9].GetUInt32();
15015 m
->COD
= fields
[10].GetUInt32();
15016 m
->checked
= fields
[11].GetUInt32();
15017 m
->stationery
= fields
[12].GetUInt8();
15018 m
->mailTemplateId
= fields
[13].GetInt16();
15020 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15022 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15023 m
->mailTemplateId
= 0;
15026 m
->state
= MAIL_STATE_UNCHANGED
;
15029 _LoadMailedItems(m
);
15031 m_mail
.push_back(m
);
15032 } while( result
->NextRow() );
15035 m_mailsLoaded
= true;
15038 void Player::LoadPet()
15040 //fixme: the pet should still be loaded if the player is not in world
15041 // just not added to the map
15044 Pet
*pet
= new Pet
;
15045 if(!pet
->LoadPetFromDB(this,0,0,true))
15050 void Player::_LoadQuestStatus(QueryResult
*result
)
15052 mQuestStatus
.clear();
15056 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15057 //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());
15063 Field
*fields
= result
->Fetch();
15065 uint32 quest_id
= fields
[0].GetUInt32();
15066 // used to be new, no delete?
15067 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15071 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15073 uint32 qstatus
= fields
[1].GetUInt32();
15074 if(qstatus
< MAX_QUEST_STATUS
)
15075 questStatusData
.m_status
= QuestStatus(qstatus
);
15078 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15079 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15082 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15083 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15085 time_t quest_time
= time_t(fields
[4].GetUInt64());
15087 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15089 AddTimedQuest( quest_id
);
15091 if (quest_time
<= sWorld
.GetGameTime())
15092 questStatusData
.m_timer
= 1;
15094 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
15099 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15100 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15101 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15102 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15103 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15104 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15105 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15106 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15108 questStatusData
.uState
= QUEST_UNCHANGED
;
15110 // add to quest log
15111 if( slot
< MAX_QUEST_LOG_SIZE
&&
15112 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
15113 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
15114 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
15116 SetQuestSlot(slot
,quest_id
,quest_time
);
15118 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15119 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
15121 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15122 if(questStatusData
.m_creatureOrGOcount
[idx
])
15123 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
15128 if(questStatusData
.m_rewarded
)
15130 // learn rewarded spell if unknown
15131 learnQuestRewardedSpells(pQuest
);
15133 // set rewarded title if any
15134 if(pQuest
->GetCharTitleId())
15136 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15137 SetTitle(titleEntry
);
15140 if(pQuest
->GetBonusTalents())
15141 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
15144 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15147 while( result
->NextRow() );
15152 // clear quest log tail
15153 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15157 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15159 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15160 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15162 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15166 uint32 quest_daily_idx
= 0;
15170 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15172 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15176 Field
*fields
= result
->Fetch();
15178 uint32 quest_id
= fields
[0].GetUInt32();
15180 // save _any_ from daily quest times (it must be after last reset anyway)
15181 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15183 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15187 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15190 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15192 while( result
->NextRow() );
15197 m_DailyQuestChanged
= false;
15200 void Player::_LoadReputation(QueryResult
*result
)
15202 m_factions
.clear();
15204 // Set initial reputations (so everything is nifty before DB data load)
15205 SetInitialFactions();
15207 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15213 Field
*fields
= result
->Fetch();
15215 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
15216 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
15218 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
15220 // update standing to current
15221 faction
->Standing
= int32(fields
[1].GetUInt32());
15223 uint32 dbFactionFlags
= fields
[2].GetUInt32();
15225 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
15226 SetFactionVisible(faction
); // have internal checks for forced invisibility
15228 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
15229 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
15231 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
15232 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15233 else // DB not at war
15235 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15236 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
15237 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15240 // set atWar for hostile
15241 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
15242 SetFactionAtWar(faction
,true);
15244 // reset changed flag if values similar to saved in DB
15245 if(faction
->Flags
==dbFactionFlags
)
15246 faction
->Changed
= false;
15249 while( result
->NextRow() );
15255 void Player::_LoadSpells(QueryResult
*result
)
15257 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15263 Field
*fields
= result
->Fetch();
15265 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
15267 while( result
->NextRow() );
15273 void Player::_LoadTutorials(QueryResult
*result
)
15275 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15281 Field
*fields
= result
->Fetch();
15283 for (int iI
=0; iI
<8; iI
++)
15284 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
15286 while( result
->NextRow() );
15291 m_TutorialsChanged
= false;
15294 void Player::_LoadGroup(QueryResult
*result
)
15296 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15299 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
15301 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
15304 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15305 SetGroup(group
, subgroup
);
15306 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
15308 // the group leader may change the instance difficulty while the player is offline
15309 SetDifficulty(group
->GetDifficulty());
15315 void Player::_LoadBoundInstances(QueryResult
*result
)
15317 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15318 m_boundInstances
[i
].clear();
15320 Group
*group
= GetGroup();
15322 //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));
15327 Field
*fields
= result
->Fetch();
15328 bool perm
= fields
[1].GetBool();
15329 uint32 mapId
= fields
[2].GetUInt32();
15330 uint32 instanceId
= fields
[0].GetUInt32();
15331 uint8 difficulty
= fields
[3].GetUInt8();
15332 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15333 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15334 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15335 // and in that case it is not used
15339 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
);
15340 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15344 // since non permanent binds are always solo bind, they can always be reset
15345 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15346 if(save
) BindToInstance(save
, perm
, true);
15347 } while(result
->NextRow());
15352 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15354 // some instances only have one difficulty
15355 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15356 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15358 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15359 if(itr
!= m_boundInstances
[difficulty
].end())
15360 return &itr
->second
;
15365 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15367 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15368 UnbindInstance(itr
, difficulty
, unload
);
15371 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15373 if(itr
!= m_boundInstances
[difficulty
].end())
15375 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15376 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15377 m_boundInstances
[difficulty
].erase(itr
++);
15381 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15385 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15388 // update the save when the group kills a boss
15389 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15390 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());
15393 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15395 if(bind
.save
!= save
)
15397 if(bind
.save
) bind
.save
->RemovePlayer(this);
15398 save
->AddPlayer(this);
15401 if(permanent
) save
->SetCanReset(false);
15404 bind
.perm
= permanent
;
15405 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());
15412 void Player::SendRaidInfo()
15414 uint32 counter
= 0;
15416 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15418 size_t p_counter
= data
.wpos();
15419 data
<< uint32(counter
); // placeholder
15421 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15423 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15425 if(itr
->second
.perm
)
15427 InstanceSave
*save
= itr
->second
.save
;
15428 data
<< uint32(save
->GetMapId());
15429 data
<< uint32(save
->GetResetTime() - time(NULL
));
15430 data
<< uint32(save
->GetInstanceId());
15431 data
<< uint32(save
->GetDifficulty());
15436 data
.put
<uint32
>(p_counter
,counter
);
15437 GetSession()->SendPacket(&data
);
15441 - called on every successful teleportation to a map
15443 void Player::SendSavedInstances()
15445 bool hasBeenSaved
= false;
15448 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15450 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15452 if(itr
->second
.perm
) // only permanent binds are sent
15454 hasBeenSaved
= true;
15460 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15461 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15462 data
<< uint32(hasBeenSaved
);
15463 GetSession()->SendPacket(&data
);
15468 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15470 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15472 if(itr
->second
.perm
)
15474 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15475 data
<< uint32(itr
->second
.save
->GetMapId());
15476 GetSession()->SendPacket(&data
);
15482 /// convert the player's binds to the group
15483 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15485 bool has_binds
= false;
15486 bool has_solo
= false;
15488 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15489 assert(player_guid
);
15491 // copy all binds to the group, when changing leader it's assumed the character
15492 // will not have any solo binds
15496 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15498 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15501 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15502 // permanent binds are not removed
15503 if(!itr
->second
.perm
)
15505 player
->UnbindInstance(itr
, i
, true); // increments itr
15514 // if the player's not online we don't know what binds it has
15515 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
));
15516 // the following should not get executed when changing leaders
15517 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15520 bool Player::_LoadHomeBind(QueryResult
*result
)
15522 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15525 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15530 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15533 Field
*fields
= result
->Fetch();
15534 m_homebindMapId
= fields
[0].GetUInt32();
15535 m_homebindZoneId
= fields
[1].GetUInt16();
15536 m_homebindX
= fields
[2].GetFloat();
15537 m_homebindY
= fields
[3].GetFloat();
15538 m_homebindZ
= fields
[4].GetFloat();
15541 // accept saved data only for valid position (and non instanceable)
15542 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15543 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
15548 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15553 m_homebindMapId
= info
->mapId
;
15554 m_homebindZoneId
= info
->zoneId
;
15555 m_homebindX
= info
->positionX
;
15556 m_homebindY
= info
->positionY
;
15557 m_homebindZ
= info
->positionZ
;
15559 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
);
15562 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15563 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15568 /*********************************************************/
15569 /*** SAVE SYSTEM ***/
15570 /*********************************************************/
15572 void Player::SaveToDB()
15574 // delay auto save at any saves (manual, in code, or autosave)
15575 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15577 // first save/honor gain after midnight will also update the player's honor fields
15578 UpdateHonorFields();
15580 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15581 //save, far from tavern/city
15582 //save, but in tavern/city
15583 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15586 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15587 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15588 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15589 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15590 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15591 uint32 tmp_displayid
= GetDisplayId();
15593 // Set player sit state to standing on save, also stealth and shifted form
15594 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15595 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15596 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15597 SetDisplayId(GetNativeDisplayId());
15599 bool inworld
= IsInWorld();
15601 CharacterDatabase
.BeginTransaction();
15603 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15605 std::string sql_name
= m_name
;
15606 CharacterDatabase
.escape_string(sql_name
);
15608 std::ostringstream ss
;
15609 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15610 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15611 "taximask, online, cinematic, "
15612 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15613 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15614 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15615 << GetGUIDLow() << ", "
15616 << GetSession()->GetAccountId() << ", '"
15617 << sql_name
<< "', "
15619 << m_class
<< ", ";
15621 if(!IsBeingTeleported())
15623 ss
<< GetMapId() << ", "
15624 << (uint32
)GetDifficulty() << ", "
15625 << finiteAlways(GetPositionX()) << ", "
15626 << finiteAlways(GetPositionY()) << ", "
15627 << finiteAlways(GetPositionZ()) << ", "
15628 << finiteAlways(GetOrientation()) << ", '";
15632 ss
<< GetTeleportDest().mapid
<< ", "
15633 << (uint32
)GetDifficulty() << ", "
15634 << finiteAlways(GetTeleportDest().x
) << ", "
15635 << finiteAlways(GetTeleportDest().y
) << ", "
15636 << finiteAlways(GetTeleportDest().z
) << ", "
15637 << finiteAlways(GetTeleportDest().o
) << ", '";
15641 for( i
= 0; i
< m_valuesCount
; i
++ )
15643 ss
<< GetUInt32Value(i
) << " ";
15648 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15651 ss
<< (inworld
? 1 : 0);
15657 ss
<< m_Played_time
[0];
15659 ss
<< m_Played_time
[1];
15662 ss
<< finiteAlways(m_rest_bonus
);
15664 ss
<< (uint64
)time(NULL
);
15666 ss
<< is_save_resting
;
15668 ss
<< m_resetTalentsCost
;
15670 ss
<< (uint64
)m_resetTalentsTime
;
15673 ss
<< finiteAlways(m_movementInfo
.t_x
);
15675 ss
<< finiteAlways(m_movementInfo
.t_y
);
15677 ss
<< finiteAlways(m_movementInfo
.t_z
);
15679 ss
<< finiteAlways(m_movementInfo
.t_o
);
15682 ss
<< m_transport
->GetGUIDLow();
15687 ss
<< m_ExtraFlags
;
15690 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15693 ss
<< uint32(m_atLoginFlags
);
15699 ss
<< (uint64
)m_deathExpireTime
;
15702 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15704 ss
<< GetBattleGroundId();
15708 ss
<< m_bgEntryPoint
.mapid
<< ", "
15709 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15710 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15711 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15712 << finiteAlways(m_bgEntryPoint
.o
);
15715 CharacterDatabase
.Execute( ss
.str().c_str() );
15717 if(m_mailsUpdated
) //save mails only when needed
15721 _SaveQuestStatus();
15722 _SaveDailyQuestStatus();
15725 _SaveSpellCooldowns();
15730 CharacterDatabase
.CommitTransaction();
15732 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15733 SetDisplayId(tmp_displayid
);
15734 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15735 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15736 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15737 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15739 // save pet (hunter pet level and experience and all type pets health/mana).
15740 if(Pet
* pet
= GetPet())
15741 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15742 m_achievementMgr
.SaveToDB();
15745 // fast save function for item/money cheating preventing - save only inventory and money state
15746 void Player::SaveInventoryAndGoldToDB()
15749 //money is in data field
15750 SaveDataFieldToDB();
15753 void Player::_SaveActions()
15755 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15757 switch (itr
->second
.uState
)
15759 case ACTIONBUTTON_NEW
:
15760 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15761 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15762 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15765 case ACTIONBUTTON_CHANGED
:
15766 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15767 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15768 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15771 case ACTIONBUTTON_DELETED
:
15772 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15773 m_actionButtons
.erase(itr
++);
15782 void Player::_SaveAuras()
15784 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15786 AuraMap
const& auras
= GetAuras();
15791 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15792 uint32 stackCounter
= 1;
15794 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15796 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15798 AuraMap::const_iterator itr2
= itr
;
15799 // save previous spellEffectPair to db
15801 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15803 //skip all auras from spells that are passive or need a shapeshift
15804 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15806 //do not save single target auras (unless they were cast by the player)
15807 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15810 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15811 for (i
= 0; i
< 3; i
++)
15812 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15813 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15818 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15819 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15820 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()));
15825 if(itr
== auras
.end())
15829 if (lastEffectPair
== itr
->first
)
15833 lastEffectPair
= itr
->first
;
15839 void Player::_SaveInventory()
15841 // force items in buyback slots to new state
15842 // and remove those that aren't already
15843 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15845 Item
*item
= m_items
[i
];
15846 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15847 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15848 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15849 m_items
[i
]->FSetState(ITEM_NEW
);
15852 // update enchantment durations
15853 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15855 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15859 if (m_itemUpdateQueue
.empty()) return;
15861 // do not save if the update queue is corrupt
15862 bool error
= false;
15863 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15865 Item
*item
= m_itemUpdateQueue
[i
];
15866 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15867 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15871 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());
15874 else if (test
!= item
)
15876 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());
15883 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15884 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15888 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15890 Item
*item
= m_itemUpdateQueue
[i
];
15891 if(!item
) continue;
15893 Bag
*container
= item
->GetContainer();
15894 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15896 switch(item
->GetState())
15899 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());
15902 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());
15905 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15907 case ITEM_UNCHANGED
:
15911 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15913 m_itemUpdateQueue
.clear();
15916 void Player::_SaveMail()
15918 if (!m_mailsLoaded
)
15921 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15924 if (m
->state
== MAIL_STATE_CHANGED
)
15926 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'",
15927 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15928 if(m
->removedItems
.size())
15930 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15931 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15932 m
->removedItems
.clear();
15934 m
->state
= MAIL_STATE_UNCHANGED
;
15936 else if (m
->state
== MAIL_STATE_DELETED
)
15939 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15940 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15942 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15943 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15944 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15948 //deallocate deleted mails...
15949 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15951 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15956 itr
= m_mail
.begin();
15962 m_mailsUpdated
= false;
15965 void Player::_SaveQuestStatus()
15967 // we don't need transactions here.
15968 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15970 switch (i
->second
.uState
)
15973 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15974 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15975 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]);
15977 case QUEST_CHANGED
:
15978 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' ",
15979 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
);
15981 case QUEST_UNCHANGED
:
15984 i
->second
.uState
= QUEST_UNCHANGED
;
15988 void Player::_SaveDailyQuestStatus()
15990 if(!m_DailyQuestChanged
)
15993 m_DailyQuestChanged
= false;
15995 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15997 // we don't need transactions here.
15998 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15999 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
16000 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
16001 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
16002 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
16005 void Player::_SaveReputation()
16007 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
16009 if (itr
->second
.Changed
)
16011 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
16012 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
);
16013 itr
->second
.Changed
= false;
16018 void Player::_SaveSpells()
16020 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
16022 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
16023 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
16025 // add only changed/new not dependent spells
16026 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
16027 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);
16029 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16031 delete itr
->second
;
16032 m_spells
.erase(itr
++);
16036 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
16043 void Player::_SaveTutorials()
16045 if(!m_TutorialsChanged
)
16049 // it's better than rebuilding indexes multiple times
16050 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
16053 Rows
= result
->Fetch()[0].GetUInt32();
16059 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'",
16060 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
);
16064 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]);
16067 m_TutorialsChanged
= false;
16070 void Player::outDebugValues() const
16072 if(!sLog
.IsOutDebug()) // optimize disabled debug output
16075 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
16076 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
16077 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
16078 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
16079 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
16080 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
16081 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
16082 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
16083 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
16084 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
16085 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
16086 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
16089 /*********************************************************/
16090 /*** FLOOD FILTER SYSTEM ***/
16091 /*********************************************************/
16093 void Player::UpdateSpeakTime()
16095 // ignore chat spam protection for GMs in any mode
16096 if(GetSession()->GetSecurity() > SEC_PLAYER
)
16099 time_t current
= time (NULL
);
16100 if(m_speakTime
> current
)
16102 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
16107 if(m_speakCount
>= max_count
)
16109 // prevent overwrite mute time, if message send just before mutes set, for example.
16110 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
16111 if(GetSession()->m_muteTime
< new_mute
)
16112 GetSession()->m_muteTime
= new_mute
;
16120 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
16123 bool Player::CanSpeak() const
16125 return GetSession()->m_muteTime
<= time (NULL
);
16128 /*********************************************************/
16129 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16130 /*********************************************************/
16132 void Player::SendAttackSwingNotInRange()
16134 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16135 GetSession()->SendPacket( &data
);
16138 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16140 std::ostringstream ss
;
16141 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16142 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16143 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16144 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16145 sLog
.outDebug(ss
.str().c_str());
16146 CharacterDatabase
.Execute(ss
.str().c_str());
16149 void Player::SaveDataFieldToDB()
16151 std::ostringstream ss
;
16152 ss
<<"UPDATE characters SET data='";
16154 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
16156 ss
<< GetUInt32Value(i
) << " ";
16158 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16160 CharacterDatabase
.Execute(ss
.str().c_str());
16163 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16165 std::ostringstream ss2
;
16166 ss2
<<"UPDATE characters SET data='";
16168 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16170 ss2
<<tokens
[i
]<<" ";
16172 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16174 return CharacterDatabase
.Execute(ss2
.str().c_str());
16177 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16180 snprintf(buf
,11,"%u",value
);
16182 if(index
>= tokens
.size())
16185 tokens
[index
] = buf
;
16188 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16191 if(!LoadValuesArrayFromDB(tokens
,guid
))
16194 if(index
>= tokens
.size())
16198 snprintf(buf
,11,"%u",value
);
16199 tokens
[index
] = buf
;
16201 SaveValuesArrayInDB(tokens
,guid
);
16204 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16207 memcpy(&temp
, &value
, sizeof(value
));
16208 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16211 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16214 if(!LoadValuesArrayFromDB(tokens
, guid
))
16217 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
16218 uint8 race
= unit_bytes0
& 0xFF;
16219 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
16221 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
16225 unit_bytes0
&= ~(0xFF << 16);
16226 unit_bytes0
|= (gender
<< 16);
16227 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
16229 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16230 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16232 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
16234 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
16235 player_bytes2
&= ~0xFF;
16236 player_bytes2
|= facialHair
;
16237 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
16239 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
16240 player_bytes3
&= ~0xFF;
16241 player_bytes3
|= gender
;
16242 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
16244 SaveValuesArrayInDB(tokens
, guid
);
16247 void Player::SendAttackSwingNotStanding()
16249 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
16250 GetSession()->SendPacket( &data
);
16253 void Player::SendAttackSwingDeadTarget()
16255 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16256 GetSession()->SendPacket( &data
);
16259 void Player::SendAttackSwingCantAttack()
16261 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16262 GetSession()->SendPacket( &data
);
16265 void Player::SendAttackSwingCancelAttack()
16267 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16268 GetSession()->SendPacket( &data
);
16271 void Player::SendAttackSwingBadFacingAttack()
16273 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16274 GetSession()->SendPacket( &data
);
16277 void Player::SendAutoRepeatCancel()
16279 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
16280 data
.append(GetPackGUID()); // may be it's target guid
16281 GetSession()->SendPacket( &data
);
16284 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
16286 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
16289 GetSession()->SendPacket( &data
);
16291 SendMessageToSet( &data
, true );
16294 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16296 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16298 data
<< Experience
;
16299 GetSession()->SendPacket(&data
);
16302 void Player::SendDungeonDifficulty(bool IsInGroup
)
16304 uint8 val
= 0x00000001;
16305 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16306 data
<< (uint32
)GetDifficulty();
16307 data
<< uint32(val
);
16308 data
<< uint32(IsInGroup
);
16309 GetSession()->SendPacket(&data
);
16312 void Player::SendResetFailedNotify(uint32 mapid
)
16314 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16315 data
<< uint32(mapid
);
16316 GetSession()->SendPacket(&data
);
16319 /// Reset all solo instances and optionally send a message on success for each
16320 void Player::ResetInstances(uint8 method
)
16322 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16324 // we assume that when the difficulty changes, all instances that can be reset will be
16325 uint8 dif
= GetDifficulty();
16327 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
16329 InstanceSave
*p
= itr
->second
.save
;
16330 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16331 if(!entry
|| !p
->CanReset())
16337 if(method
== INSTANCE_RESET_ALL
)
16339 // the "reset all instances" method can only reset normal maps
16340 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16347 // if the map is loaded, reset it
16348 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16349 if(map
&& map
->IsDungeon())
16350 ((InstanceMap
*)map
)->Reset(method
);
16352 // since this is a solo instance there should not be any players inside
16353 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16354 SendResetInstanceSuccess(p
->GetMapId());
16357 m_boundInstances
[dif
].erase(itr
++);
16359 // the following should remove the instance save from the manager and delete it as well
16360 p
->RemovePlayer(this);
16364 void Player::SendResetInstanceSuccess(uint32 MapId
)
16366 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16368 GetSession()->SendPacket(&data
);
16371 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16373 // TODO: find what other fail reasons there are besides players in the instance
16374 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16377 GetSession()->SendPacket(&data
);
16380 /*********************************************************/
16381 /*** Update timers ***/
16382 /*********************************************************/
16384 ///checks the 15 afk reports per 5 minutes limit
16385 void Player::UpdateAfkReport(time_t currTime
)
16387 if(m_bgAfkReportedTimer
<= currTime
)
16389 m_bgAfkReportedCount
= 0;
16390 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16394 void Player::UpdateContestedPvP(uint32 diff
)
16396 if(!m_contestedPvPTimer
||isInCombat())
16398 if(m_contestedPvPTimer
<= diff
)
16400 ResetContestedPvP();
16403 m_contestedPvPTimer
-= diff
;
16406 void Player::UpdatePvPFlag(time_t currTime
)
16410 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16416 void Player::UpdateDuelFlag(time_t currTime
)
16418 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16421 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16422 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16424 duel
->startTimer
= 0;
16425 duel
->startTime
= currTime
;
16426 duel
->opponent
->duel
->startTimer
= 0;
16427 duel
->opponent
->duel
->startTime
= currTime
;
16430 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16435 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16437 //returning of reagents only for players, so best done here
16438 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16439 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16443 for(uint32 i
= 0; i
< 7; ++i
)
16445 if(spellInfo
->Reagent
[i
] > 0)
16447 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16448 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16449 if( msg
== EQUIP_ERR_OK
)
16451 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16453 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16458 m_temporaryUnsummonedPetNumber
= 0;
16461 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16464 // only if current pet in slot
16465 switch(pet
->getPetType())
16471 m_guardianPets
.erase(pet
->GetGUID());
16474 if(GetPetGUID() == pet
->GetGUID())
16483 switch(pet
->GetEntry())
16485 //warlock pets except imp are removed(?) when logging out
16490 mode
= PET_SAVE_NOT_IN_SLOT
;
16495 pet
->SavePetToDB(mode
);
16497 pet
->CleanupsBeforeDelete();
16498 pet
->AddObjectToRemoveList();
16499 pet
->m_removed
= true;
16501 if(pet
->isControlled())
16503 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16506 GetSession()->SendPacket(&data
);
16509 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16513 void Player::RemoveMiniPet()
16515 if(Pet
* pet
= GetMiniPet())
16517 pet
->Remove(PET_SAVE_AS_DELETED
);
16522 Pet
* Player::GetMiniPet()
16526 return ObjectAccessor::GetPet(m_miniPet
);
16529 void Player::RemoveGuardians()
16531 while(!m_guardianPets
.empty())
16533 uint64 guid
= *m_guardianPets
.begin();
16534 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16535 pet
->Remove(PET_SAVE_AS_DELETED
);
16537 m_guardianPets
.erase(guid
);
16541 bool Player::HasGuardianWithEntry(uint32 entry
)
16543 // pet guid middle part is entry (and creature also)
16544 // and in guardian list must be guardians with same entry _always_
16545 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16546 if(GUID_ENPART(*itr
)==entry
)
16552 void Player::Uncharm()
16554 Unit
* charm
= GetCharm();
16558 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16559 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16562 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16564 *data
<< (uint8
)msgtype
;
16565 *data
<< (uint32
)language
;
16566 *data
<< (uint64
)GetGUID();
16567 *data
<< (uint32
)language
; //language 2.1.0 ?
16568 *data
<< (uint64
)GetGUID();
16569 *data
<< (uint32
)(text
.length()+1);
16571 *data
<< (uint8
)chatTag();
16574 void Player::Say(const std::string
& text
, const uint32 language
)
16576 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16577 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16578 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16581 void Player::Yell(const std::string
& text
, const uint32 language
)
16583 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16584 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16585 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16588 void Player::TextEmote(const std::string
& text
)
16590 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16591 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16592 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16595 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16597 if (language
!= LANG_ADDON
) // if not addon data
16598 language
= LANG_UNIVERSAL
; // whispers should always be readable
16600 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16602 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16603 if(!rPlayer
->isDND() || isGameMaster())
16605 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16606 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16607 rPlayer
->GetSession()->SendPacket(&data
);
16609 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16610 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16611 GetSession()->SendPacket(&data
);
16615 // announce to player that player he is whispering to is dnd and cannot receive his message
16616 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16619 if(!isAcceptWhispers())
16621 SetAcceptWhispers(true);
16622 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16625 // announce to player that player he is whispering to is afk
16626 if(rPlayer
->isAFK())
16627 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16629 // if player whisper someone, auto turn of dnd to be able to receive an answer
16630 if(isDND() && !rPlayer
->isGameMaster())
16634 void Player::PetSpellInitialize()
16636 Pet
* pet
= GetPet();
16641 sLog
.outDebug("Pet Spells Groups");
16643 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16645 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16646 data
<< uint64(pet
->GetGUID());
16647 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16649 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16652 for(uint32 i
= 0; i
< 10; i
++)
16654 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16657 size_t spellsCountPos
= data
.wpos();
16661 data
<< uint8(addlist
); // placeholder
16663 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16666 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16668 if(itr
->second
->state
== PETSPELL_REMOVED
)
16671 data
<< uint16(itr
->first
);
16672 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16677 data
.put
<uint8
>(spellsCountPos
, addlist
);
16679 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16680 data
<< uint8(cooldownsCount
);
16682 time_t curTime
= time(NULL
);
16684 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16686 time_t cooldown
= 0;
16688 if(itr
->second
> curTime
)
16689 cooldown
= (itr
->second
- curTime
) * 1000;
16691 data
<< uint16(itr
->first
); // spellid
16692 data
<< uint16(0); // spell category?
16693 data
<< uint32(itr
->second
); // cooldown
16694 data
<< uint32(0); // category cooldown
16697 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16699 time_t cooldown
= 0;
16701 if(itr
->second
> curTime
)
16702 cooldown
= (itr
->second
- curTime
) * 1000;
16704 data
<< uint16(itr
->first
); // spellid
16705 data
<< uint16(0); // spell category?
16706 data
<< uint32(0); // cooldown
16707 data
<< uint32(itr
->second
); // category cooldown
16710 GetSession()->SendPacket(&data
);
16713 void Player::PossessSpellInitialize()
16715 Unit
* charm
= GetCharm();
16720 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16724 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16729 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16732 data
<< uint64(charm
->GetGUID());
16733 data
<< uint32(0x00000000);
16735 data
<< uint8(0) << uint8(0) << uint16(0);
16737 for(uint32 i
= 0; i
< 10; i
++) //40
16739 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16742 data
<< uint8(addlist
); //1
16745 data
<< uint8(count
); // cooldowns count
16747 GetSession()->SendPacket(&data
);
16750 void Player::CharmSpellInitialize()
16752 Unit
* charm
= GetCharm();
16757 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16760 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16766 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16768 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16770 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16772 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16774 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16780 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16782 data
<< uint64(charm
->GetGUID());
16783 data
<< uint32(0x00000000);
16785 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16786 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16788 data
<< uint8(0) << uint8(0);
16791 for(uint32 i
= 0; i
< 10; i
++) //40
16793 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16796 data
<< uint8(addlist
); //1
16800 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16802 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16803 if(cspell
->spellId
)
16805 data
<< uint16(cspell
->spellId
);
16806 data
<< uint16(cspell
->active
);
16812 data
<< uint8(count
); // cooldowns count
16814 GetSession()->SendPacket(&data
);
16817 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16819 if (!mod
|| !spellInfo
)
16822 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16824 // prevent apply to any spell except spell that trigger expire
16827 if(mod
->lastAffected
!= spell
)
16830 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16834 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16837 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16839 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16841 for(int eff
=0;eff
<96;++eff
)
16845 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16846 else _mask2
= uint64(1) << (eff
-64);
16847 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16850 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16852 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16853 val
+= (*itr
)->value
;
16855 val
+= apply
? mod
->value
: -(mod
->value
);
16856 WorldPacket
data(Opcode
, (1+1+4));
16857 data
<< uint8(eff
);
16858 data
<< uint8(mod
->op
);
16859 data
<< int32(val
);
16860 SendDirectMessage(&data
);
16865 m_spellMods
[mod
->op
].push_back(mod
);
16868 if (mod
->charges
== -1)
16869 --m_SpellModRemoveCount
;
16870 m_spellMods
[mod
->op
].remove(mod
);
16875 void Player::RemoveSpellMods(Spell
const* spell
)
16877 if(!spell
|| (m_SpellModRemoveCount
== 0))
16880 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16882 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16884 SpellModifier
*mod
= *itr
;
16887 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16889 RemoveAurasDueToSpell(mod
->spellId
);
16890 if (m_spellMods
[i
].empty())
16893 itr
= m_spellMods
[i
].begin();
16899 // send Proficiency
16900 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16902 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16903 data
<< pr1
<< pr2
;
16904 GetSession()->SendPacket (&data
);
16907 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16909 QueryResult
*result
= NULL
;
16911 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16913 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16916 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.
16917 { // and SendPetitionQueryOpcode reads data from the DB
16918 Field
*fields
= result
->Fetch();
16919 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16920 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16922 // send update if charter owner in game
16923 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16925 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16927 } while ( result
->NextRow() );
16932 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16934 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16937 CharacterDatabase
.BeginTransaction();
16940 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16941 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16945 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16946 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16948 CharacterDatabase
.CommitTransaction();
16951 void Player::LeaveAllArenaTeams(uint64 guid
)
16953 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
));
16959 Field
*fields
= result
->Fetch();
16960 uint32 at_id
= fields
[0].GetUInt32();
16963 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16965 at
->DelMember(guid
);
16967 } while (result
->NextRow());
16972 void Player::SetRestBonus (float rest_bonus_new
)
16974 // Prevent resting on max level
16975 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16976 rest_bonus_new
= 0;
16978 if(rest_bonus_new
< 0)
16979 rest_bonus_new
= 0;
16981 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16983 if(rest_bonus_new
> rest_bonus_max
)
16984 m_rest_bonus
= rest_bonus_max
;
16986 m_rest_bonus
= rest_bonus_new
;
16988 // update data for client
16989 if(m_rest_bonus
>10)
16990 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16991 else if(m_rest_bonus
<=1)
16992 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16995 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16998 void Player::HandleStealthedUnitsDetection()
17000 std::list
<Unit
*> stealthedUnits
;
17002 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17004 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
17005 cell
.SetNoCreate();
17007 MaNGOS::AnyStealthedCheck u_check
;
17008 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
17010 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
17011 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
17013 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
17014 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
17015 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
17017 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
17021 i
= stealthedUnits
.erase(i
);
17025 if ((*i
)->isVisibleForOrDetect(this,true))
17028 (*i
)->SendUpdateToPlayer(this);
17029 m_clientGUIDs
.insert((*i
)->GetGUID());
17031 #ifdef MANGOS_DEBUG
17032 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17033 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
17036 // target aura duration for caster show only if target exist at caster client
17037 // send data at target visibility change (adding to client)
17038 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
17039 SendAurasForTarget(*i
);
17041 i
= stealthedUnits
.erase(i
);
17049 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
17051 if(nodes
.size() < 2)
17054 // not let cheating with start flight mounted
17057 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17058 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
17059 GetSession()->SendPacket(&data
);
17063 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17065 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17066 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
17067 GetSession()->SendPacket(&data
);
17071 // 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
17072 if(GetSession()->isLogingOut() ||
17073 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
17074 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
17075 IsNonMeleeSpellCasted(false) ||
17078 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17079 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17080 GetSession()->SendPacket(&data
);
17084 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
17087 uint32 sourcenode
= nodes
[0];
17089 // starting node too far away (cheat?)
17090 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
17091 if( !node
|| node
->map_id
!= GetMapId() ||
17092 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
17093 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
17094 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
17095 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
17097 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17098 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17099 GetSession()->SendPacket(&data
);
17103 // Prepare to flight start now
17105 // stop combat at start taxi flight if any
17108 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17111 // clean not finished taxi path if any
17112 m_taxi
.ClearTaxiDestinations();
17114 // 0 element current node
17115 m_taxi
.AddTaxiDestination(sourcenode
);
17117 // fill destinations path tail
17118 uint32 sourcepath
= 0;
17119 uint32 totalcost
= 0;
17121 uint32 prevnode
= sourcenode
;
17122 uint32 lastnode
= 0;
17124 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17128 lastnode
= nodes
[i
];
17129 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17133 m_taxi
.ClearTaxiDestinations();
17139 if(prevnode
== sourcenode
)
17142 m_taxi
.AddTaxiDestination(lastnode
);
17144 prevnode
= lastnode
;
17147 if(!mount_id
) // if not provide then attempt use default.
17148 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
17150 if (mount_id
== 0 || sourcepath
== 0)
17152 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17153 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17154 GetSession()->SendPacket(&data
);
17155 m_taxi
.ClearTaxiDestinations();
17159 uint32 money
= GetMoney();
17163 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17166 if(money
< totalcost
)
17168 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17169 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17170 GetSession()->SendPacket(&data
);
17171 m_taxi
.ClearTaxiDestinations();
17175 //Checks and preparations done, DO FLIGHT
17176 ModifyMoney(-(int32
)totalcost
);
17178 // prevent stealth flight
17179 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17181 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17182 data
<< uint32(ERR_TAXIOK
);
17183 GetSession()->SendPacket(&data
);
17185 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17187 GetSession()->SendDoFlight(mount_id
, sourcepath
);
17192 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17194 // last check 2.0.10
17195 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17197 data
<< uint8(0x0); // flags (0x1, 0x2)
17198 time_t curTime
= time(NULL
);
17199 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17201 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
17203 uint32 unSpellId
= itr
->first
;
17204 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17211 // Not send cooldown for this spells
17212 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17215 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17218 data
<< unTimeMs
; // in m.secs
17219 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
17222 GetSession()->SendPacket(&data
);
17225 void Player::InitDataForForm(bool reapplyMods
)
17227 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17228 if(ssEntry
&& ssEntry
->attackSpeed
)
17230 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17231 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17232 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17235 SetRegularAttackTime();
17241 if(getPowerType()!=POWER_ENERGY
)
17242 setPowerType(POWER_ENERGY
);
17246 case FORM_DIREBEAR
:
17248 if(getPowerType()!=POWER_RAGE
)
17249 setPowerType(POWER_RAGE
);
17252 default: // 0, for example
17254 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17255 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17256 setPowerType(Powers(cEntry
->powerType
));
17261 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17263 UpdateEquipSpellsAtFormChange();
17265 UpdateAttackPowerAndDamage();
17266 UpdateAttackPowerAndDamage(true);
17269 // Return true is the bought item has a max count to force refresh of window by caller
17270 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
17272 // cheating attempt
17273 if(count
< 1) count
= 1;
17278 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17281 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17285 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17288 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17289 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17293 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17294 if(!vItems
|| vItems
->Empty())
17296 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17300 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17301 if(vendor_slot
>= vItems
->GetItemCount())
17303 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17307 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17309 // check current item amount if it limited
17310 if( crItem
->maxcount
!= 0 )
17312 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17314 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17319 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17321 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17325 if(crItem
->ExtendedCost
)
17327 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17330 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17334 // honor points price
17335 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17337 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17341 // arena points price
17342 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17344 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17349 for (uint8 i
= 0; i
< 5; ++i
)
17351 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17353 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17358 // check for personal arena rating requirement
17359 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17361 // probably not the proper equip err
17362 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17367 uint32 price
= pProto
->BuyPrice
* count
;
17369 // reputation discount
17370 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17372 if( GetMoney() < price
)
17374 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17378 uint8 bag
= 0; // init for case invalid bagGUID
17380 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17383 if( bagguid
== GetGUID() )
17385 bag
= INVENTORY_SLOT_BAG_0
;
17389 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17391 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17394 if( bagguid
== pBag
->GetGUID() )
17404 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17406 ItemPosCountVec dest
;
17407 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17408 if( msg
!= EQUIP_ERR_OK
)
17410 SendEquipError( msg
, NULL
, NULL
);
17414 ModifyMoney( -(int32
)price
);
17415 if(crItem
->ExtendedCost
) // case for new honor system
17417 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17418 if(iece
->reqhonorpoints
)
17419 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17420 if(iece
->reqarenapoints
)
17421 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17422 for (uint8 i
= 0; i
< 5; ++i
)
17424 if(iece
->reqitem
[i
])
17425 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17429 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17431 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17433 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17434 data
<< pCreature
->GetGUID();
17435 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17436 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17437 data
<< (uint32
)count
;
17438 GetSession()->SendPacket(&data
);
17440 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17443 else if( IsEquipmentPos( bag
, slot
) )
17445 if(pProto
->BuyCount
* count
!= 1)
17447 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17452 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17453 if( msg
!= EQUIP_ERR_OK
)
17455 SendEquipError( msg
, NULL
, NULL
);
17459 ModifyMoney( -(int32
)price
);
17460 if(crItem
->ExtendedCost
) // case for new honor system
17462 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17463 if(iece
->reqhonorpoints
)
17464 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17465 if(iece
->reqarenapoints
)
17466 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17467 for (uint8 i
= 0; i
< 5; ++i
)
17469 if(iece
->reqitem
[i
])
17470 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17474 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17476 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17478 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17479 data
<< pCreature
->GetGUID();
17480 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17481 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17482 data
<< (uint32
)count
;
17483 GetSession()->SendPacket(&data
);
17485 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17487 AutoUnequipOffhandIfNeed();
17492 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17496 return crItem
->maxcount
!=0;
17499 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17501 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17502 // the personal rating of the arena team must match the required limit as well
17503 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17504 uint32 max_personal_rating
= 0;
17505 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17507 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17509 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17510 uint32 t_rating
= at
->GetRating();
17511 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17512 if(max_personal_rating
< p_rating
)
17513 max_personal_rating
= p_rating
;
17516 return max_personal_rating
;
17519 void Player::UpdateHomebindTime(uint32 time
)
17521 // GMs never get homebind timer online
17522 if (m_InstanceValid
|| isGameMaster())
17524 if(m_HomebindTimer
) // instance valid, but timer not reset
17527 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17530 GetSession()->SendPacket(&data
);
17532 // instance is valid, reset homebind timer
17533 m_HomebindTimer
= 0;
17535 else if (m_HomebindTimer
> 0)
17537 if (time
>= m_HomebindTimer
)
17539 // teleport to homebind location
17540 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17543 m_HomebindTimer
-= time
;
17547 // instance is invalid, start homebind timer
17548 m_HomebindTimer
= 60000;
17549 // send message to player
17550 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17551 data
<< m_HomebindTimer
;
17553 GetSession()->SendPacket(&data
);
17554 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17558 void Player::UpdatePvP(bool state
, bool ovrride
)
17560 if(!state
|| ovrride
)
17563 if(Pet
* pet
= GetPet())
17564 pet
->SetPvP(state
);
17565 if(Unit
* charmed
= GetCharm())
17566 charmed
->SetPvP(state
);
17568 pvpInfo
.endTimer
= 0;
17572 if(pvpInfo
.endTimer
!= 0)
17573 pvpInfo
.endTimer
= time(NULL
);
17578 if(Pet
* pet
= GetPet())
17579 pet
->SetPvP(state
);
17580 if(Unit
* charmed
= GetCharm())
17581 charmed
->SetPvP(state
);
17586 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17590 sc
.itemid
= itemid
;
17591 m_spellCooldowns
[spellid
] = sc
;
17594 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
17596 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
17599 // Get spell cooldown
17600 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
17602 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
17606 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
17608 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17609 data
<< spellInfo
->Id
;
17611 SendDirectMessage(&data
);
17613 //slot to be excluded while counting
17614 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17616 if(!enchantmentcondition
)
17619 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17624 uint8 curcount
[4] = {0, 0, 0, 0};
17626 //counting current equipped gem colors
17627 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17631 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17632 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17634 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17636 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17640 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17644 uint32 gemid
= enchantEntry
->GemID
;
17648 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17652 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17656 uint8 GemColor
= gemProperty
->color
;
17658 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17660 if(tmpcolormask
& GemColor
)
17667 bool activate
= true;
17669 for(int i
= 0; i
< 5; i
++)
17671 if(!Condition
->Color
[i
])
17674 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17676 // if have <CompareColor> use them as count, else use <value> from Condition
17677 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17679 switch(Condition
->Comparator
[i
])
17681 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17682 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17684 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17685 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17687 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17688 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17693 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");
17698 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17700 //cycle all equipped items
17701 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17703 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17704 if(slot
== exceptslot
)
17707 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17709 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17712 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17714 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17718 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17722 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17725 //was enchant active with/without item?
17726 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17727 //should it now be?
17728 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17730 // ignore item gem conditions
17731 //if state changed, (dis)apply enchant
17732 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17739 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17740 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17742 //cycle all equipped items
17743 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17745 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17746 if(slot
== exceptslot
)
17749 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17751 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17754 //cycle all (gem)enchants
17755 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17757 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17758 if(!enchant_id
) //if no enchant go to next enchant(slot)
17761 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17765 //only metagems to be (de)activated, so only enchants with condition
17766 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17768 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17773 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17775 if(BattleGround
*bg
= GetBattleGround())
17777 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
17779 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17781 // call after remove to be sure that player resurrected for correct cast
17783 CastSpell(this, 26013, true); // Deserter
17787 bool Player::CanJoinToBattleground() const
17789 // check Deserter debuff
17790 if(GetDummyAura(26013))
17796 bool Player::CanReportAfkDueToLimit()
17798 // a player can complain about 15 people per 5 minutes
17799 if(m_bgAfkReportedCount
>= 15)
17801 ++m_bgAfkReportedCount
;
17805 ///This player has been blamed to be inactive in a battleground
17806 void Player::ReportedAfkBy(Player
* reporter
)
17808 BattleGround
*bg
= GetBattleGround();
17809 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17812 // check if player has 'Idle' or 'Inactive' debuff
17813 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17815 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17816 // 3 players have to complain to apply debuff
17817 if(m_bgAfkReporter
.size() >= 3)
17819 // cast 'Idle' spell
17820 CastSpell(this, 43680, true);
17821 m_bgAfkReporter
.clear();
17826 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17828 // gamemaster in GM mode see all, including ghosts
17829 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17832 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17833 if (InBattleGround())
17835 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17840 // Live player see live player or dead player with not realized corpse
17841 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17843 return isAlive() || m_deathTimer
> 0;
17846 // Ghost see other friendly ghosts, that's for sure
17847 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17850 // Dead player see live players near own corpse
17853 Corpse
*corpse
= pl
->GetCorpse();
17856 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17857 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17862 // and not see any other
17866 bool Player::IsVisibleGloballyFor( Player
* u
) const
17871 // Always can see self
17875 // Visible units, always are visible for all players
17876 if (GetVisibility() == VISIBILITY_ON
)
17879 // GMs are visible for higher gms (or players are visible for gms)
17880 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17881 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17883 // non faction visibility non-breakable for non-GMs
17884 if (GetVisibility() == VISIBILITY_OFF
)
17887 // non-gm stealth/invisibility not hide from global player lists
17891 void Player::UpdateVisibilityOf(WorldObject
* target
)
17893 if(HaveAtClient(target
))
17895 if(!target
->isVisibleForInState(this,true))
17897 target
->DestroyForPlayer(this);
17898 m_clientGUIDs
.erase(target
->GetGUID());
17900 #ifdef MANGOS_DEBUG
17901 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17902 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17908 if(target
->isVisibleForInState(this,false))
17910 target
->SendUpdateToPlayer(this);
17911 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17912 m_clientGUIDs
.insert(target
->GetGUID());
17914 #ifdef MANGOS_DEBUG
17915 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17916 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17919 // target aura duration for caster show only if target exist at caster client
17920 // send data at target visibility change (adding to client)
17921 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17922 SendAurasForTarget((Unit
*)target
);
17924 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17925 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17931 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17933 s64
.insert(target
->GetGUID());
17937 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17939 if(!target
->IsTransport())
17940 s64
.insert(target
->GetGUID());
17944 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17946 if(HaveAtClient(target
))
17948 if(!target
->isVisibleForInState(this,true))
17950 target
->BuildOutOfRangeUpdateBlock(&data
);
17951 m_clientGUIDs
.erase(target
->GetGUID());
17953 #ifdef MANGOS_DEBUG
17954 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17955 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
));
17961 if(target
->isVisibleForInState(this,false))
17963 visibleNow
.insert(target
);
17964 target
->BuildUpdate(data_updates
);
17965 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17966 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17968 #ifdef MANGOS_DEBUG
17969 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17970 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
));
17976 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17977 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17978 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17979 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17980 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17982 void Player::InitPrimaryProffesions()
17984 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17987 void Player::SendComboPoints()
17989 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17992 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17993 data
.append(combotarget
->GetPackGUID());
17994 data
<< uint8(m_comboPoints
);
17995 GetSession()->SendPacket(&data
);
17999 void Player::AddComboPoints(Unit
* target
, int8 count
)
18004 // without combo points lost (duration checked in aura)
18005 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18007 if(target
->GetGUID() == m_comboTarget
)
18009 m_comboPoints
+= count
;
18014 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18015 target
->RemoveComboPointHolder(GetGUIDLow());
18017 m_comboTarget
= target
->GetGUID();
18018 m_comboPoints
= count
;
18020 target
->AddComboPointHolder(GetGUIDLow());
18023 if (m_comboPoints
> 5) m_comboPoints
= 5;
18024 if (m_comboPoints
< 0) m_comboPoints
= 0;
18029 void Player::ClearComboPoints()
18034 // without combopoints lost (duration checked in aura)
18035 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18041 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18042 target
->RemoveComboPointHolder(GetGUIDLow());
18047 void Player::SetGroup(Group
*group
, int8 subgroup
)
18049 if(group
== NULL
) m_group
.unlink();
18052 // never use SetGroup without a subgroup unless you specify NULL for group
18053 assert(subgroup
>= 0);
18054 m_group
.link(group
, this);
18055 m_group
.setSubGroup((uint8
)subgroup
);
18059 void Player::SendInitialPacketsBeforeAddToMap()
18061 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
18062 data
<< uint32(0); // unknown, may be rest state time or experience
18063 GetSession()->SendPacket(&data
);
18066 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
18067 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
18068 data
<< (uint32
) m_homebindMapId
;
18069 data
<< (uint32
) m_homebindZoneId
;
18070 GetSession()->SendPacket(&data
);
18072 // SMSG_SET_PROFICIENCY
18073 // SMSG_UPDATE_AURA_DURATION
18076 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
18077 for (int i
= 0; i
< 8; ++i
)
18078 data
<< uint32( GetTutorialInt(i
) );
18079 GetSession()->SendPacket(&data
);
18081 SendInitialSpells();
18083 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
18084 data
<< uint32(0); // count, for(count) uint32;
18085 GetSession()->SendPacket(&data
);
18087 SendInitialActionButtons();
18088 SendInitialReputations();
18089 m_achievementMgr
.SendAllAchievementData();
18090 UpdateZone(GetZoneId());
18091 SendInitWorldStates();
18093 // SMSG_SET_AURA_SINGLE
18095 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
18096 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
18097 data
<< (float)0.01666667f
; // game speed
18098 GetSession()->SendPacket( &data
);
18100 data
.Initialize(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18101 data
<< uint32(0x00000000); // on blizz it increments periodically
18102 GetSession()->SendPacket(&data
);
18104 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18105 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
18106 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
18111 void Player::SendInitialPacketsAfterAddToMap()
18113 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18114 data
<< uint32(0x00000000); // on blizz it increments periodically
18115 GetSession()->SendPacket(&data
);
18117 CastSpell(this, 836, true); // LOGINEFFECT
18119 // set some aura effects that send packet to player client after add player to map
18120 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18121 // same auras state lost at far teleport, send it one more time in this case also
18122 static const AuraType auratypes
[] =
18124 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
18125 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
18126 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
18128 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
18130 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
18131 if(!auraList
.empty())
18132 auraList
.front()->ApplyModifier(true,true);
18135 if(HasAuraType(SPELL_AURA_MOD_STUN
))
18136 SetMovement(MOVE_ROOT
);
18138 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18139 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
18141 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
18142 data
.append(GetPackGUID());
18144 SendMessageToSet(&data
,true);
18147 SendAurasForTarget(this);
18148 SendEnchantmentDurations(); // must be after add to map
18149 SendItemDurations(); // must be after add to map
18152 void Player::SendUpdateToOutOfRangeGroupMembers()
18154 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
18156 if(Group
* group
= GetGroup())
18157 group
->UpdatePlayerOutOfRange(this);
18159 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18160 m_auraUpdateMask
= 0;
18161 if(Pet
*pet
= GetPet())
18162 pet
->ResetAuraUpdateMask();
18165 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18167 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18168 data
<< uint32(mapid
);
18169 data
<< uint8(reason
); // transfer abort reason
18172 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18173 case TRANSFER_ABORT_DIFFICULTY
:
18174 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18175 data
<< uint8(arg
);
18178 GetSession()->SendPacket(&data
);
18181 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
18183 // type of warning, based on the time remaining until reset
18186 type
= RAID_INSTANCE_WELCOME
;
18187 else if(time
> 900 && time
<= 3600)
18188 type
= RAID_INSTANCE_WARNING_HOURS
;
18189 else if(time
> 300 && time
<= 900)
18190 type
= RAID_INSTANCE_WARNING_MIN
;
18192 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18193 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
18194 data
<< uint32(type
);
18195 data
<< uint32(mapid
);
18196 data
<< uint32(time
);
18197 GetSession()->SendPacket(&data
);
18200 void Player::ApplyEquipCooldown( Item
* pItem
)
18202 for(int i
= 0; i
<5; ++i
)
18204 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18207 if( !spellData
.SpellId
)
18210 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18211 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18214 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18216 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18217 data
<< pItem
->GetGUID();
18218 data
<< uint32(spellData
.SpellId
);
18219 GetSession()->SendPacket(&data
);
18223 void Player::resetSpells()
18225 // not need after this call
18226 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18228 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
18229 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18232 // make full copy of map (spells removed and marked as deleted at another spell remove
18233 // and we can't use original map for safe iterative with visit each spell at loop end
18234 PlayerSpellMap smap
= GetSpellMap();
18236 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18237 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18239 learnDefaultSpells();
18240 learnQuestRewardedSpells();
18243 void Player::learnDefaultSpells()
18245 // learn default race/class spells
18246 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18247 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18249 uint32 tspell
= *itr
;
18250 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18251 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18252 addSpell(tspell
,true,true,true,false);
18253 else // but send in normal spell in game learn case
18254 learnSpell(tspell
,true);
18258 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18260 uint32 spell_id
= quest
->GetRewSpellCast();
18262 // skip quests without rewarded spell
18266 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18270 // check learned spells state
18271 bool found
= false;
18272 for(int i
=0; i
< 3; ++i
)
18274 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18281 // skip quests with not teaching spell or already known spell
18285 // prevent learn non first rank unknown profession and second specialization for same profession)
18286 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18287 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18289 // not have first rank learned (unlearned prof?)
18290 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18291 if( !HasSpell(first_spell
) )
18294 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18299 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18301 // search other specialization for same prof
18302 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18304 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18307 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18311 // compare only specializations
18312 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18315 // compare same chain spells
18316 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18319 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18320 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18326 CastSpell( this, spell_id
, true);
18329 void Player::learnQuestRewardedSpells()
18331 // learn spells received from quest completing
18332 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18334 // skip no rewarded quests
18335 if(!itr
->second
.m_rewarded
)
18338 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18342 learnQuestRewardedSpells(quest
);
18346 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18348 uint32 raceMask
= getRaceMask();
18349 uint32 classMask
= getClassMask();
18350 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18352 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18353 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18355 // Check race if set
18356 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18358 // Check class if set
18359 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18362 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18364 // need unlearn spell
18365 if (skill_value
< pAbility
->req_skill_value
)
18366 removeSpell(pAbility
->spellId
);
18368 else if (!IsInWorld())
18369 addSpell(pAbility
->spellId
,true,true,true,false);
18371 learnSpell(pAbility
->spellId
,true);
18376 void Player::SendAurasForTarget(Unit
*target
)
18378 if(target
->GetVisibleAuras()->empty()) // speedup things
18381 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18382 data
.append(target
->GetPackGUID());
18384 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18385 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18387 for(uint32 j
= 0; j
< 3; ++j
)
18389 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18391 data
<< uint8(aura
->GetAuraSlot());
18392 data
<< uint32(aura
->GetId());
18396 uint8 auraFlags
= aura
->GetAuraFlags();
18398 data
<< uint8(auraFlags
);
18400 data
<< uint8(aura
->GetAuraLevel());
18402 data
<< uint8(aura
->GetAuraCharges());
18404 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18406 data
<< uint8(0); // packed GUID of someone (caster?)
18409 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18411 data
<< uint32(aura
->GetAuraMaxDuration());
18412 data
<< uint32(aura
->GetAuraDuration());
18420 GetSession()->SendPacket(&data
);
18423 void Player::SetDailyQuestStatus( uint32 quest_id
)
18425 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18427 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18429 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18430 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18431 m_DailyQuestChanged
= true;
18437 void Player::ResetDailyQuestStatus()
18439 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18440 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18442 // DB data deleted in caller
18443 m_DailyQuestChanged
= false;
18444 m_lastDailyQuestTime
= 0;
18447 BattleGround
* Player::GetBattleGround() const
18449 if(GetBattleGroundId()==0)
18452 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
18455 bool Player::InArena() const
18457 BattleGround
*bg
= GetBattleGround();
18458 if(!bg
|| !bg
->isArena())
18464 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18466 // get a template bg instead of running one
18467 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18471 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18477 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18479 //returned to hardcoded version of this function, because there is no way to code it dynamic
18480 uint32 level
= getLevel();
18481 if( bgTypeId
== BATTLEGROUND_QUEUE_AV
)
18484 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18485 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18487 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18488 return QUEUE_ID_MAX_LEVEL_80
;
18490 return BGQueueIdBasedOnLevel(queue_id
);
18493 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18495 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18496 if(!vendor_faction
)
18499 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18500 if(rank
<= REP_NEUTRAL
)
18503 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18506 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18508 uint32 racemask
= getRaceMask();
18509 uint32 classmask
= getClassMask();
18511 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18512 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18516 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18518 // skip wrong race skills
18519 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18522 // skip wrong class skills
18523 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18532 bool Player::HasQuestForGO(int32 GOId
) const
18534 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18536 uint32 questid
= GetQuestSlotQuestId(i
);
18537 if ( questid
== 0 )
18540 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18541 if(qs_itr
== mQuestStatus
.end())
18544 QuestStatusData
const& qs
= qs_itr
->second
;
18546 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18548 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18552 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18555 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18557 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18560 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18568 void Player::UpdateForQuestsGO()
18570 if(m_clientGUIDs
.empty())
18574 WorldPacket packet
;
18575 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18577 if(IS_GAMEOBJECT_GUID(*itr
))
18579 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18581 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18584 udata
.BuildPacket(&packet
);
18585 GetSession()->SendPacket(&packet
);
18588 void Player::SummonIfPossible(bool agree
)
18592 m_summon_expire
= 0;
18596 // expire and auto declined
18597 if(m_summon_expire
< time(NULL
))
18600 // stop taxi flight at summon
18603 GetMotionMaster()->MovementExpired();
18604 m_taxi
.ClearTaxiDestinations();
18607 // drop flag at summon
18608 if(BattleGround
*bg
= GetBattleGround())
18609 bg
->EventPlayerDroppedFlag(this);
18611 m_summon_expire
= 0;
18613 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18616 void Player::RemoveItemDurations( Item
*item
)
18618 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18622 m_itemDuration
.erase(itr
);
18628 void Player::AddItemDurations( Item
*item
)
18630 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18632 m_itemDuration
.push_back(item
);
18633 item
->SendTimeUpdate(this);
18637 void Player::AutoUnequipOffhandIfNeed()
18639 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18643 // need unequip for 2h-weapon without TitanGrip
18644 if (!IsTwoHandUsed())
18647 ItemPosCountVec off_dest
;
18648 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18649 if( off_msg
== EQUIP_ERR_OK
)
18651 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18652 StoreItem( off_dest
, offItem
, true );
18656 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18660 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18662 if(spellInfo
->EquippedItemClass
< 0)
18665 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18666 // for optimize check 2 used cases only
18667 switch(spellInfo
->EquippedItemClass
)
18669 case ITEM_CLASS_WEAPON
:
18671 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18672 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18673 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18677 case ITEM_CLASS_ARMOR
:
18679 // tabard not have dependent spells
18680 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18681 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18682 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18685 // shields can be equipped to offhand slot
18686 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18687 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18690 // ranged slot can have some armor subclasses
18691 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18692 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18698 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18705 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18707 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18708 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18709 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18712 // Check no reagent use mask
18713 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18714 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18715 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18716 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18722 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18724 AuraMap
& auras
= GetAuras();
18725 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18727 Aura
* aura
= itr
->second
;
18729 // skip passive (passive item dependent spells work in another way) and not self applied auras
18730 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18731 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18737 // skip if not item dependent or have alternative item
18738 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18744 // no alt item, remove aura, restart check
18745 RemoveAurasDueToSpell(aura
->GetId());
18746 itr
= auras
.begin();
18749 // currently casted spells can be dependent from item
18750 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18752 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18753 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18758 uint32
Player::GetResurrectionSpellId()
18760 // search priceless resurrection possibilities
18762 uint32 spell_id
= 0;
18763 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18764 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18766 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18767 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18769 switch((*itr
)->GetId())
18771 case 20707: spell_id
= 3026; break; // rank 1
18772 case 20762: spell_id
= 20758; break; // rank 2
18773 case 20763: spell_id
= 20759; break; // rank 3
18774 case 20764: spell_id
= 20760; break; // rank 4
18775 case 20765: spell_id
= 20761; break; // rank 5
18776 case 27239: spell_id
= 27240; break; // rank 6
18777 case 47883: spell_id
= 47882; break; // rank 7
18779 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18785 // Twisting Nether // prio: 2 (max)
18786 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18793 // Reincarnation (passive spell) // prio: 1
18794 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18800 // Used in triggers for check "Only to targets that grant experience or honor" req
18801 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18803 uint32 v_level
= pVictim
->getLevel();
18804 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18806 // Victim level less gray level
18807 if(v_level
<=k_grey
)
18810 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18812 if (((Creature
*)pVictim
)->isTotem() ||
18813 ((Creature
*)pVictim
)->isPet() ||
18814 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18820 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18822 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18824 // prepare data for near group iteration (PvP and !PvP cases)
18826 bool honored_kill
= false;
18828 if(Group
*pGroup
= GetGroup())
18831 uint32 sum_level
= 0;
18832 Player
* member_with_max_level
= NULL
;
18833 Player
* not_gray_member_with_max_level
= NULL
;
18835 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18837 if(member_with_max_level
)
18839 /// not get Xp in PvP or no not gray players in group
18840 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18842 /// skip in check PvP case (for speed, not used)
18843 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18844 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18845 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18847 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18849 Player
* pGroupGuy
= itr
->getSource();
18853 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18854 continue; // member (alive or dead) or his corpse at req. distance
18856 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18857 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18858 honored_kill
= true;
18860 // xp and reputation only in !PvP case
18863 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18865 // if is in dungeon then all receive full reputation at kill
18866 // rewarded any alive/dead/near_corpse group member
18867 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18869 // XP updated only for alive group member
18870 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18871 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18873 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18875 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18876 if(Pet
* pet
= pGroupGuy
->GetPet())
18877 pet
->GivePetXP(itr_xp
/2);
18880 // quest objectives updated only for alive group member or dead but with not released body
18881 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18883 // normal creature (not pet/etc) can be only in !PvP case
18884 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18885 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18891 else // if (!pGroup)
18893 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18895 // honor can be in PvP and !PvP (racial leader) cases
18896 if(RewardHonor(pVictim
,1))
18897 honored_kill
= true;
18899 // xp and reputation only in !PvP case
18902 RewardReputation(pVictim
,1);
18903 GiveXP(xp
, pVictim
);
18905 if(Pet
* pet
= GetPet())
18906 pet
->GivePetXP(xp
);
18908 // normal creature (not pet/etc) can be only in !PvP case
18909 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18910 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18913 return xp
|| honored_kill
;
18916 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18918 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18924 Corpse
* corpse
= GetCorpse();
18928 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18931 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18933 Item
* item
= GetWeaponForAttack(attType
,true);
18935 // unarmed only with base attack
18936 if(attType
!= BASE_ATTACK
&& !item
)
18939 // weapon skill or (unarmed for base attack)
18940 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18941 return GetBaseSkillValue(skill
);
18944 void Player::ResurectUsingRequestData()
18946 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18947 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18949 ResurrectPlayer(0.0f
,false);
18951 if(GetMaxHealth() > m_resurrectHealth
)
18952 SetHealth( m_resurrectHealth
);
18954 SetHealth( GetMaxHealth() );
18956 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18957 SetPower(POWER_MANA
, m_resurrectMana
);
18959 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18961 SetPower(POWER_RAGE
, 0 );
18963 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18965 SpawnCorpseBones();
18968 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18970 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18971 data
.append(target
->GetPackGUID());
18972 data
<< uint8(allowMove
);
18973 GetSession()->SendPacket(&data
);
18976 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18978 // remove new continent flight forms
18979 if( !IsAllowUseFlyMountsHere() )
18981 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18982 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18985 // Some spells applied at enter into zone (with subzones)
18988 case 2367: // Old Hillsbrad Foothills
18991 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18992 uint32 spellid
= 0;
18994 if( GetTeam() == HORDE
)
18995 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18996 // and some alliance races
18997 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18998 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
19000 if(spellid
&& !HasAura(spellid
,0) )
19001 CastSpell(this,spellid
,true);
19007 void Player::UpdateAreaDependentAuras( uint32 newArea
)
19009 // remove auras from spells with area limitations
19010 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
19012 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19013 if(GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,GetBattleGroundId())!=0)
19019 // some auras applied at subzone enter
19022 // Dragonmaw Illusion
19023 case 3759: // Netherwing Ledge
19024 case 3939: // Dragonmaw Fortress
19025 case 3966: // Dragonmaw Base Camp
19026 if( GetDummyAura(40214) )
19028 if( !HasAura(40216,0) )
19029 CastSpell(this,40216,true);
19030 if( !HasAura(42016,0) )
19031 CastSpell(this,42016,true);
19034 // Dominion Over Acherus
19035 case 4281: // Acherus: The Ebon Hold
19036 case 4342: // Acherus: The Ebon Hold
19037 if( HasSpell(51721) )
19038 if( !HasAura(51721,0) )
19039 CastSpell(this,51721,true);
19041 // Mist of the Kvaldir
19042 case 4028: //Riplash Strand
19043 case 4029: //Riplash Ruins
19044 case 4106: //Garrosh's Landing
19045 case 4031: //Pal'ea
19046 CastSpell(this,54119,true);
19051 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
19053 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19054 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19056 return copseReclaimDelay
[0];
19059 time_t now
= time(NULL
);
19060 // 0..2 full period
19061 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
19062 return copseReclaimDelay
[count
];
19065 void Player::UpdateCorpseReclaimDelay()
19067 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
19069 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19070 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19073 time_t now
= time(NULL
);
19074 if(now
< m_deathExpireTime
)
19076 // full and partly periods 1..3
19077 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
19078 if(count
< MAX_DEATH_COUNT
)
19079 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
19081 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
19084 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
19087 void Player::SendCorpseReclaimDelay(bool load
)
19089 Corpse
* corpse
= GetCorpse();
19096 if(corpse
->GetGhostTime() > m_deathExpireTime
)
19099 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
19102 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19103 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19105 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
19106 if(count
>=MAX_DEATH_COUNT
)
19107 count
= MAX_DEATH_COUNT
-1;
19112 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
19114 time_t now
= time(NULL
);
19115 if(now
>= expected_time
)
19118 delay
= expected_time
-now
;
19121 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
19123 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19124 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
19125 data
<< uint32(delay
*1000);
19126 GetSession()->SendPacket( &data
);
19129 Player
* Player::GetNextRandomRaidMember(float radius
)
19131 Group
*pGroup
= GetGroup();
19135 std::vector
<Player
*> nearMembers
;
19136 nearMembers
.reserve(pGroup
->GetMembersCount());
19138 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19140 Player
* Target
= itr
->getSource();
19142 // IsHostileTo check duel and controlled by enemy
19143 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19144 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19145 nearMembers
.push_back(Target
);
19148 if (nearMembers
.empty())
19151 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19152 return nearMembers
[randTarget
];
19155 PartyResult
Player::CanUninviteFromGroup() const
19157 const Group
* grp
= GetGroup();
19159 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19161 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19162 return PARTY_RESULT_YOU_NOT_LEADER
;
19164 if(InBattleGround())
19165 return PARTY_RESULT_INVITE_RESTRICTED
;
19167 return PARTY_RESULT_OK
;
19170 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19172 float water_z
= m
->GetWaterLevel(x
,y
);
19173 float terrain_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
19174 uint8 flag1
= m
->GetTerrainType(x
,y
);
19176 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19177 if (terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
-2) || z
> (water_z
- 2) )
19178 m_isunderwater
&= ~UNDERWATER_INWATER
;
19179 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
19180 m_isunderwater
|= UNDERWATER_INWATER
;
19182 //!in lava check, anywhere under lava level
19183 if ((terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
- 0)) && (flag1
== 0x00) && IsInWater())
19184 m_isunderwater
|= UNDERWATER_INLAVA
;
19186 m_isunderwater
&= ~UNDERWATER_INLAVA
;
19189 void Player::SetCanParry( bool value
)
19191 if(m_canParry
==value
)
19194 m_canParry
= value
;
19195 UpdateParryPercentage();
19198 void Player::SetCanBlock( bool value
)
19200 if(m_canBlock
==value
)
19203 m_canBlock
= value
;
19204 UpdateBlockPercentage();
19207 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19209 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19210 if(itr
->pos
== pos
)
19216 bool Player::isAllowUseBattleGroundObject()
19218 return ( //InBattleGround() && // in battleground - not need, check in other cases
19219 !IsMounted() && // not mounted
19220 !HasStealthAura() && // not stealthed
19221 !HasInvisibilityAura() && // not invisible
19222 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19223 isAlive() // live player
19227 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19229 uint32 level
= getLevel();
19231 if(level
> GT_MAX_LEVEL
)
19232 level
= GT_MAX_LEVEL
; // max level in this dbc
19234 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19235 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19236 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19238 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19241 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19243 if(!bsc
) // shouldn't happen
19248 if(hairstyle
!= newhairstyle
)
19249 cost
+= bsc
->cost
; // full price
19251 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19252 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19254 if(facialhair
!= newfacialhair
)
19255 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19257 return uint32(cost
);
19260 void Player::InitGlyphsForLevel()
19262 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19263 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19265 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19267 uint32 level
= getLevel();
19270 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19272 value
|= (0x01 | 0x02);
19282 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19285 void Player::EnterVehicle(Vehicle
*vehicle
)
19287 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19291 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19295 vehicle
->SetCharmerGUID(GetGUID());
19296 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19297 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19298 vehicle
->setFaction(getFaction());
19300 SetCharm(vehicle
); // charm
19301 SetFarSightGUID(vehicle
->GetGUID()); // set view
19303 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19305 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19306 GetSession()->SendPacket(&data
);
19308 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19309 data
.append(GetPackGUID());
19310 data
<< uint32(0); // counter?
19311 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19312 data
<< uint16(0); // special flags
19313 data
<< uint32(getMSTime()); // time
19314 data
<< vehicle
->GetPositionX(); // x
19315 data
<< vehicle
->GetPositionY(); // y
19316 data
<< vehicle
->GetPositionZ(); // z
19317 data
<< vehicle
->GetOrientation(); // o
19318 // transport part, TODO: load/calculate seat offsets
19319 data
<< uint64(vehicle
->GetGUID()); // transport guid
19320 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19321 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19322 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19323 data
<< float(0); // transport orientation
19324 data
<< uint32(getMSTime()); // transport time
19325 data
<< uint8(0); // seat
19326 // end of transport part
19327 data
<< uint32(0); // fall time
19328 GetSession()->SendPacket(&data
);
19330 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19331 data
<< uint64(vehicle
->GetGUID());
19332 data
<< uint32(0x00000000);
19333 data
<< uint32(0x00000000);
19334 data
<< uint32(0x00000101);
19336 for(uint32 i
= 0; i
< 10; ++i
)
19337 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19341 GetSession()->SendPacket(&data
);
19344 void Player::ExitVehicle(Vehicle
*vehicle
)
19346 vehicle
->SetCharmerGUID(0);
19347 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19348 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19349 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19352 SetFarSightGUID(0);
19354 SetClientControl(vehicle
, 0);
19356 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19357 data
.append(GetPackGUID());
19358 data
<< uint32(0); // counter?
19359 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19360 data
<< uint16(0x40); // special flags
19361 data
<< uint32(getMSTime()); // time
19362 data
<< vehicle
->GetPositionX(); // x
19363 data
<< vehicle
->GetPositionY(); // y
19364 data
<< vehicle
->GetPositionZ(); // z
19365 data
<< vehicle
->GetOrientation(); // o
19366 data
<< uint32(0); // fall time
19367 GetSession()->SendPacket(&data
);
19369 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19372 GetSession()->SendPacket(&data
);
19374 // only for flyable vehicles?
19375 CastSpell(this, 45472, true); // Parachute
19378 bool Player::HasTitle(uint32 bitIndex
)
19380 if (bitIndex
> 128)
19383 uint32 fieldIndexOffset
= bitIndex
/32;
19384 uint32 flag
= 1 << (bitIndex
%32);
19385 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19388 void Player::SetTitle(CharTitlesEntry
const* title
)
19390 uint32 fieldIndexOffset
= title
->bit_index
/32;
19391 uint32 flag
= 1 << (title
->bit_index
%32);
19392 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19395 void Player::ConvertRune(uint8 index
, uint8 newType
)
19397 SetCurrentRune(index
, newType
);
19399 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19400 data
<< uint8(index
);
19401 data
<< uint8(newType
);
19402 GetSession()->SendPacket(&data
);
19405 void Player::ResyncRunes(uint8 count
)
19407 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19408 for(uint32 i
= 0; i
< count
; ++i
)
19410 data
<< uint8(GetCurrentRune(i
)); // rune type
19411 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19413 GetSession()->SendPacket(&data
);
19416 void Player::AddRunePower(uint8 index
)
19418 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19419 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19420 GetSession()->SendPacket(&data
);
19423 void Player::InitRunes()
19425 if(getClass() != CLASS_DEATH_KNIGHT
)
19428 m_runes
= new Runes
;
19430 m_runes
->runeState
= 0;
19432 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19434 SetBaseRune(i
, i
/ 2); // init base types
19435 SetCurrentRune(i
, i
/ 2); // init current types
19436 SetRuneCooldown(i
, 0); // reset cooldowns
19437 m_runes
->SetRuneState(i
);
19440 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19441 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19444 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19447 loot
.FillLoot (loot_id
,store
,this,true);
19449 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19450 for(uint32 i
= 0; i
< max_slot
; ++i
)
19452 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19454 ItemPosCountVec dest
;
19455 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19456 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19457 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19458 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19459 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19460 if(msg
!= EQUIP_ERR_OK
)
19462 SendEquipError( msg
, NULL
, NULL
);
19466 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19467 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19471 uint32
Player::CalculateTalentsPoints() const
19473 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19475 if(getClass() != CLASS_DEATH_KNIGHT
)
19476 return base_talent
;
19478 uint32 talentPointsForLevel
=
19479 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19480 + m_questRewardTalentCount
;
19482 if(talentPointsForLevel
> base_talent
)
19483 talentPointsForLevel
= base_talent
;
19485 return talentPointsForLevel
;
19488 bool Player::IsAllowUseFlyMountsHere() const
19490 if (isGameMaster())
19493 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19494 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19497 void Player::learnSpellHighRank(uint32 spellid
)
19499 learnSpell(spellid
,false);
19501 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19502 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19503 learnSpellHighRank(itr
->second
);
19506 void Player::_LoadSkills()
19508 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19510 // reset skill modifiers and set correct unlearn flags
19511 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
19513 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19515 // set correct unlearn bit
19516 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19519 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19520 if(!pSkill
) continue;
19522 // enable unlearn button for primary professions only
19523 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19524 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19526 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19528 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19530 learnSkillRewardedSpells(id
, vskill
);
19533 // special settings
19534 if(getClass()==CLASS_DEATH_KNIGHT
)
19536 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19539 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19541 base_skill
= 1; // skill mast be known and then > 0 in any case
19543 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19544 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19545 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19546 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19547 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19548 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19549 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19550 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19551 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19552 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19553 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19554 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19555 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19556 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19557 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19558 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19562 uint32
Player::GetPhaseMaskForSpawn() const
19564 uint32 phase
= PHASEMASK_NORMAL
;
19565 if(!isGameMaster())
19566 phase
= GetPhaseMask();
19569 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19570 if(!phases
.empty())
19571 phase
= phases
.front()->GetMiscValue();
19574 // some aura phases include 1 normal map in addition to phase itself
19575 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19578 return PHASEMASK_NORMAL
;
19581 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19583 ItemPrototype
const* pProto
= pItem
->GetProto();
19585 // proto based limitations
19586 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19589 // check unique-equipped on gems
19590 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19592 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19595 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19599 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19603 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19604 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19605 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19607 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19611 return EQUIP_ERR_OK
;
19614 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19616 // check unique-equipped on item
19617 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19619 // there is an equip limit on this item
19620 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19621 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19624 // check unique-equipped limit
19625 if (itemProto
->ItemLimitCategory
)
19627 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19629 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19631 if(limit_count
> limitEntry
->maxCount
)
19632 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19634 // there is an equip limit on this item
19635 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19636 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19639 return EQUIP_ERR_OK
;