2 * Copyright (C) 2005-2008 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 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
147 // new continent starting masks (It will be accessible only at new map)
148 switch(Player::TeamForRace(race
))
150 case ALLIANCE
: SetTaximaskNode(100); break;
151 case HORDE
: SetTaximaskNode(99); break;
153 // level dependent taxi hubs
155 SetTaximaskNode(213); //Shattered Sun Staging Area
158 void PlayerTaxi::LoadTaxiMask(const char* data
)
160 Tokens tokens
= StrSplit(data
, " ");
163 Tokens::iterator iter
;
164 for (iter
= tokens
.begin(), index
= 0;
165 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
167 // load and set bits only for existed taxi nodes
168 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
172 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
176 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
177 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
181 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
182 data
<< uint32(m_taximask
[i
]); // known nodes
186 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values
)
188 ClearTaxiDestinations();
190 Tokens tokens
= StrSplit(values
," ");
192 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
194 uint32 node
= uint32(atol(iter
->c_str()));
195 AddTaxiDestination(node
);
198 if(m_TaxiDestinations
.empty())
202 if(m_TaxiDestinations
.size() < 2)
205 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
209 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
217 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
219 if(m_TaxiDestinations
.empty())
222 std::ostringstream ss
;
224 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
225 ss
<< m_TaxiDestinations
[i
] << " ";
230 uint32
PlayerTaxi::GetCurrentTaxiPath() const
232 if(m_TaxiDestinations
.size() < 2)
238 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
243 //== Player ====================================================
245 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
247 UpdateMask
Player::updateVisualBits
;
249 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this)
256 m_objectType
|= TYPEMASK_PLAYER
;
257 m_objectTypeId
= TYPEID_PLAYER
;
259 m_valuesCount
= PLAYER_END
;
266 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
267 SetAcceptTicket(true);
269 // players always accept
270 if(GetSession()->GetSecurity() == SEC_PLAYER
)
271 SetAcceptWhispers(true);
279 m_usedTalentCount
= 0;
282 m_weaponChangeTimer
= 0;
285 m_zoneUpdateTimer
= 0;
289 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
291 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
292 // this must help in case next save after mass player load after server startup
293 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
295 clearResurrectRequestData();
297 m_SpellModRemoveCount
= 0;
299 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
303 // group is initialized in the reference constructor
304 SetGroupInvite(NULL
);
305 m_groupUpdateMask
= 0;
306 m_auraUpdateMask
= 0;
310 m_GuildIdInvited
= 0;
311 m_ArenaTeamIdInvited
= 0;
313 m_atLoginFlags
= AT_LOGIN_NONE
;
322 PlayerTalkClass
= new PlayerMenu( GetSession() );
323 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
325 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
326 m_Tutorials
[ aX
] = 0x00;
327 m_TutorialsChanged
= false;
329 m_DailyQuestChanged
= false;
330 m_lastDailyQuestTime
= 0;
333 m_weaponChangeTimer
= 0;
341 m_deathExpireTime
= 0;
345 m_DetectInvTimer
= 1000;
347 m_bgBattleGroundID
= 0;
348 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
350 m_bgBattleGroundQueueID
[j
].bgType
= 0;
351 m_bgBattleGroundQueueID
[j
].invited
= false;
355 m_logintime
= time(NULL
);
356 m_Last_tick
= m_logintime
;
357 m_WeaponProficiency
= 0;
358 m_ArmorProficiency
= 0;
361 m_canDualWield
= false;
364 m_temporaryUnsummonedPetNumber
= 0;
365 //cache for UNIT_CREATED_BY_SPELL to allow
366 //returning reagests for temporarily removed pets
367 //when dying/logging out
370 ////////////////////Rest System/////////////////////
377 rest_type
=REST_TYPE_NO
;
378 ////////////////////Rest System/////////////////////
380 m_mailsLoaded
= false;
381 m_mailsUpdated
= false;
383 m_nextMailDelivereTime
= 0;
385 m_resetTalentsCost
= 0;
386 m_resetTalentsTime
= 0;
387 m_itemUpdateQueueBlocked
= false;
389 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
390 m_forced_speed_changes
[i
] = 0;
394 /////////////////// Instance System /////////////////////
397 m_InstanceValid
= true;
398 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
400 for (int i
= 0; i
< BASEMOD_END
; i
++)
402 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
403 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
407 m_lastHonorUpdateTime
= time(NULL
);
416 //Default movement to run mode
417 m_unit_movement_flags
= 0;
420 m_bgAfkReportedTimer
= 0;
421 m_contestedPvPTimer
= 0;
423 m_declinedname
= NULL
;
428 CleanupsBeforeDelete();
430 // it must be unloaded already in PlayerLogout and accessed only for loggined player
433 // Note: buy back item already deleted from DB when player was saved
434 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
441 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
444 //all mailed items should be deleted, also all mail should be deallocated
445 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
448 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
449 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
451 delete PlayerTalkClass
;
455 m_transport
->RemovePassenger(this);
458 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
460 delete ItemSetEff
[x
];
462 // clean up player-instance binds, may unload some instance saves
463 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
464 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
465 itr
->second
.save
->RemovePlayer(this);
467 delete m_declinedname
;
470 void Player::CleanupsBeforeDelete()
472 if(m_uint32Values
) // only for fully created Object
475 DuelComplete(DUEL_INTERUPTED
);
477 Unit::CleanupsBeforeDelete();
480 bool Player::Create( uint32 guidlow
, std::string name
, uint8 race
, uint8 class_
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
, uint8 outfitId
)
482 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
486 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
489 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
493 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
496 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
498 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
499 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
500 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
506 SetMapId(info
->mapId
);
507 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
509 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
512 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
516 uint8 powertype
= cEntry
->powerType
;
524 unitfield
= 0x00000000;
527 unitfield
= 0x00110000;
529 case POWER_RUNIC_POWER
:
530 unitfield
= 0x0000EE00; //TODO: find correct unitfield here
533 sLog
.outError("Invalid default powertype %u for player (class %u)",powertype
,class_
);
537 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
538 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
543 SetDisplayId(info
->displayId_f
);
544 SetNativeDisplayId(info
->displayId_f
);
547 SetDisplayId(info
->displayId_m
);
548 SetNativeDisplayId(info
->displayId_m
);
551 sLog
.outError("Invalid gender %u for player",gender
);
556 setFactionForRace(m_race
);
558 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( ( race
) | ( class_
<< 8 ) | ( gender
<< 16 ) | ( powertype
<< 24 ) ) );
559 SetUInt32Value(UNIT_FIELD_BYTES_1
, unitfield
);
560 SetByteValue(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
561 SetUInt32Value(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
562 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
564 //-1 is default value
565 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
567 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
568 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
569 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
571 SetUInt32Value( PLAYER_GUILDID
, 0 );
572 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
573 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
575 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
576 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
577 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
578 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
579 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
580 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
582 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
584 GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
);
586 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
589 // set starting level
590 if(getClass() == CLASS_DEATH_KNIGHT
)
591 SetUInt32Value(UNIT_FIELD_LEVEL
, 55);
593 SetUInt32Value( UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
) );
596 m_Last_tick
= time(NULL
);
597 m_Played_time
[0] = 0;
598 m_Played_time
[1] = 0;
600 // base stats and related field values
602 InitTaxiNodesForLevel();
603 InitGlyphsForLevel();
604 InitTalentForLevel();
605 InitPrimaryProffesions(); // to max set before any spell added
607 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
608 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
609 SetHealth(GetMaxHealth());
610 if (getPowerType()==POWER_MANA
)
612 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intelect)
613 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
616 learnDefaultSpells(true);
618 std::list
<uint16
>::const_iterator action_itr
[4];
619 for(int i
=0; i
<4; i
++)
620 action_itr
[i
] = info
->action
[i
].begin();
622 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
625 for(int i
=0; i
<4 ;i
++)
626 taction
[i
] = (*action_itr
[i
]);
628 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
630 for(int i
=0; i
<4 ;i
++)
634 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
636 uint32 titem_id
= item_id_itr
->item_id
;
637 uint32 titem_amount
= item_id_itr
->item_amount
;
639 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
643 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, titem_amount
, false );
644 if( msg
== EQUIP_ERR_OK
)
646 EquipNewItem( eDest
, titem_id
, titem_amount
, true);
647 AutoUnequipOffhandIfNeed();
648 continue; // equipped, to next
652 ItemPosCountVec sDest
;
653 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
654 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
655 if( msg
== EQUIP_ERR_OK
)
657 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
658 continue; // stored, to next
661 // item can't be added
662 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,race
,class_
,msg
);
665 // bags and main-hand weapon must equipped at this moment
666 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
667 // or ammo not equipped in special bag
668 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
670 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
673 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
674 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
675 if( msg
== EQUIP_ERR_OK
)
677 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
678 EquipItem( eDest
, pItem
, true);
680 // move other items to more appropriate slots (ammo not equipped in special bag)
683 ItemPosCountVec sDest
;
684 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
685 if( msg
== EQUIP_ERR_OK
)
687 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
688 pItem
= StoreItem( sDest
, pItem
, true);
691 // if this is ammo then use it
692 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
693 if( msg
== EQUIP_ERR_OK
)
694 SetAmmo( pItem
->GetProto()->ItemId
);
698 // all item positions resolved
703 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
705 uint32 BreathRegen
= (uint32
)-1;
707 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
708 data
<< (uint32
)Type
;
713 data
<< (uint32
)0; // spell id
714 GetSession()->SendPacket(&data
);
717 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
719 if(Type
==BREATH_TIMER
)
720 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
722 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
723 data
<< (uint32
)Type
;
724 data
<< CurrentValue
;
728 data
<< (uint32
)0; // spell id
729 GetSession()->SendPacket( &data
);
732 void Player::StopMirrorTimer(MirrorTimerType Type
)
734 if(Type
==BREATH_TIMER
)
737 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
738 data
<< (uint32
)Type
;
739 GetSession()->SendPacket( &data
);
742 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
744 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
745 data
<< (uint64
)guid
;
746 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
747 data
<< (uint32
)damage
;
750 //m_session->SendPacket(&data);
751 //Let other players see that you get damage
752 SendMessageToSet(&data
, true);
753 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
755 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
757 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
758 DurabilityLossAll(0.10f
,false);
759 // durability lost message
760 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
761 GetSession()->SendPacket(&data
);
765 void Player::HandleDrowning()
770 //if have water breath , then remove bar
771 if(waterbreath
|| isGameMaster() || !isAlive())
773 StopMirrorTimer(BREATH_TIMER
);
778 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default leangthL 1 min
780 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
781 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
782 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
784 if ((m_isunderwater
& 0x01) && !(m_isunderwater
& 0x80) && isAlive())
786 //single trigger timer
787 if (!(m_isunderwater
& 0x02))
789 m_isunderwater
|= 0x02;
790 m_breathTimer
= UnderWaterTime
+ 1000;
792 //single trigger "Breathbar"
793 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& 0x04))
795 m_isunderwater
|= 0x04;
796 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
798 //continius trigger drowning "Damage"
799 if ((m_breathTimer
== 0) && (m_isunderwater
& 0x01))
801 //TODO: Check this formula
802 uint64 guid
= GetGUID();
803 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
805 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
806 m_breathTimer
= 2000;
809 //single trigger retract bar
810 else if (!(m_isunderwater
& 0x01) && !(m_isunderwater
& 0x08) && (m_isunderwater
& 0x02) && (m_breathTimer
> 0) && isAlive())
812 m_isunderwater
= 0x08;
814 uint32 BreathRegen
= 10;
815 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
816 m_isunderwater
= 0x10;
819 else if ((m_breathTimer
< 50) && !(m_isunderwater
& 0x01) && (m_isunderwater
== 0x10))
821 StopMirrorTimer(BREATH_TIMER
);
826 void Player::HandleLava()
828 bool ValidArea
= false;
830 if ((m_isunderwater
& 0x80) && isAlive())
832 //Single trigger Set BreathTimer
833 if (!(m_isunderwater
& 0x80))
835 m_isunderwater
|= 0x04;
836 m_breathTimer
= 1000;
838 //Reset BreathTimer and still in the lava
841 uint64 guid
= GetGUID();
842 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
843 uint32 dmgZone
= GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
845 // Deal lava damage only in lava zones.
861 if (dmgZone
/ 5 & 0x408)
865 // if is valid area and is not gamemaster then deal damage
866 if ( ValidArea
&& !isGameMaster() )
867 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
869 m_breathTimer
= 1000;
873 //Death timer disabled and WaterFlags reset
874 else if (m_deathState
== DEAD
)
881 ///The player sobers by 256 every 10 seconds
882 void Player::HandleSobering()
886 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
887 SetDrunkValue(drunk
);
890 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
893 return DRUNKEN_SMASHED
;
895 return DRUNKEN_DRUNK
;
897 return DRUNKEN_TIPSY
;
898 return DRUNKEN_SOBER
;
901 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
903 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
905 m_drunk
= newDrunkenValue
;
906 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
908 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
910 // special drunk invisibility detection
911 if(newDrunkenState
>= DRUNKEN_DRUNK
)
912 m_detectInvisibilityMask
|= (1<<6);
914 m_detectInvisibilityMask
&= ~(1<<6);
916 if(newDrunkenState
== oldDrunkenState
)
919 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
921 data
<< uint32(newDrunkenState
);
922 data
<< uint32(itemId
);
924 SendMessageToSet(&data
, true);
927 void Player::Update( uint32 p_time
)
933 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
938 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
939 m_nextMailDelivereTime
= 0;
942 Unit::Update( p_time
);
944 // update player only attacks
945 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
947 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
950 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
952 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
955 time_t now
= time (NULL
);
959 UpdateContestedPvP(p_time
);
963 CheckDuelDistance(now
);
965 UpdateAfkReport(now
);
967 CheckExploreSystem();
969 // Update items that have just a limited lifetime
971 UpdateItemDuration(uint32(now
- m_Last_tick
));
973 if (!m_timedquests
.empty())
975 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
976 while (iter
!= m_timedquests
.end())
978 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
979 if( q_status
.m_timer
<= p_time
)
981 uint32 quest_id
= *iter
;
982 ++iter
; // current iter will be removed in FailTimedQuest
983 FailTimedQuest( quest_id
);
987 q_status
.m_timer
-= p_time
;
988 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
994 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
996 Unit
*pVictim
= getVictim();
997 if( !IsNonMeleeSpellCasted(false) && pVictim
)
999 // default combat reach 10
1000 // TODO add weapon,skill check
1002 float pldistance
= ATTACK_DISTANCE
;
1004 if (isAttackReady(BASE_ATTACK
))
1006 if(!IsWithinDistInMap(pVictim
, pldistance
))
1008 setAttackTimer(BASE_ATTACK
,100);
1009 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1011 SendAttackSwingNotInRange();
1012 m_swingErrorMsg
= 1;
1015 //120 degrees of radiant range
1016 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1018 setAttackTimer(BASE_ATTACK
,100);
1019 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1021 SendAttackSwingBadFacingAttack();
1022 m_swingErrorMsg
= 2;
1027 m_swingErrorMsg
= 0; // reset swing error state
1029 // prevent base and off attack in same time, delay attack at 0.2 sec
1030 if(haveOffhandWeapon())
1032 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1033 if(off_att
< ATTACK_DISPLAY_DELAY
)
1034 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1036 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1037 resetAttackTimer(BASE_ATTACK
);
1041 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1043 if(!IsWithinDistInMap(pVictim
, pldistance
))
1045 setAttackTimer(OFF_ATTACK
,100);
1047 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1049 setAttackTimer(OFF_ATTACK
,100);
1053 // prevent base and off attack in same time, delay attack at 0.2 sec
1054 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1055 if(base_att
< ATTACK_DISPLAY_DELAY
)
1056 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1058 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1059 resetAttackTimer(OFF_ATTACK
);
1063 Unit
*owner
= pVictim
->GetOwner();
1064 Unit
*u
= owner
? owner
: pVictim
;
1065 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1068 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1073 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1075 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1077 int time_inn
= time(NULL
)-GetTimeInnEnter();
1078 if (time_inn
>= 10) //freeze update
1080 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1081 //speed collect rest bonus (section/in hour)
1082 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1083 UpdateInnerTime(time(NULL
));
1088 if(m_regenTimer
> 0)
1090 if(p_time
>= m_regenTimer
)
1093 m_regenTimer
-= p_time
;
1096 if (m_weaponChangeTimer
> 0)
1098 if(p_time
>= m_weaponChangeTimer
)
1099 m_weaponChangeTimer
= 0;
1101 m_weaponChangeTimer
-= p_time
;
1104 if (m_zoneUpdateTimer
> 0)
1106 if(p_time
>= m_zoneUpdateTimer
)
1108 uint32 newzone
= GetZoneId();
1109 if( m_zoneUpdateId
!= newzone
)
1110 UpdateZone(newzone
); // also update area
1113 // use area updates as well
1114 // needed for free far all arenas for example
1115 uint32 newarea
= GetAreaId();
1116 if( m_areaUpdateId
!= newarea
)
1117 UpdateArea(newarea
);
1119 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1123 m_zoneUpdateTimer
-= p_time
;
1131 if (m_deathState
== JUST_DIED
)
1138 if(p_time
>= m_nextSave
)
1140 // m_nextSave reseted in SaveToDB call
1142 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1146 m_nextSave
-= p_time
;
1151 if(m_breathTimer
> 0)
1153 if(p_time
>= m_breathTimer
)
1156 m_breathTimer
-= p_time
;
1160 //Handle Water/drowning
1166 //Handle detect stealth players
1167 if (m_DetectInvTimer
> 0)
1169 if (p_time
>= m_DetectInvTimer
)
1171 m_DetectInvTimer
= 3000;
1172 HandleStealthedUnitsDetection();
1175 m_DetectInvTimer
-= p_time
;
1179 if (now
> m_Last_tick
)
1181 uint32 elapsed
= uint32(now
- m_Last_tick
);
1182 m_Played_time
[0] += elapsed
; // Total played time
1183 m_Played_time
[1] += elapsed
; // Level played time
1189 m_drunkTimer
+= p_time
;
1191 if (m_drunkTimer
> 10000)
1195 // not auto-free ghost from body in instances
1196 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1198 if(p_time
>= m_deathTimer
)
1205 m_deathTimer
-= p_time
;
1208 UpdateEnchantTime(p_time
);
1209 UpdateHomebindTime(p_time
);
1212 SendUpdateToOutOfRangeGroupMembers();
1214 Pet
* pet
= GetPet();
1215 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1217 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1222 void Player::setDeathState(DeathState s
)
1224 uint32 ressSpellId
= 0;
1226 bool cur
= isAlive();
1228 if(s
== JUST_DIED
&& cur
)
1230 // drunken state is cleared on death
1232 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1235 clearResurrectRequestData();
1237 // remove form before other mods to prevent incorrect stats calculation
1238 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1240 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1241 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1243 // remove uncontrolled pets
1247 // save value before aura remove in Unit::setDeathState
1248 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1252 ressSpellId
= GetResurrectionSpellId();
1254 Unit::setDeathState(s
);
1256 // restore resurrection spell id for player after aura remove
1257 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1258 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1260 if(isAlive() && !cur
)
1262 //clear aura case after resurrection by another way (spells will be applied before next death)
1263 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1265 // restore default warrior stance
1266 if(getClass()== CLASS_WARRIOR
)
1267 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1271 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1273 *p_data
<< GetGUID();
1276 *p_data
<< getRace();
1277 uint8 pClass
= getClass();
1279 *p_data
<< getGender();
1281 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1282 *p_data
<< uint8(bytes
);
1283 *p_data
<< uint8(bytes
>> 8);
1284 *p_data
<< uint8(bytes
>> 16);
1285 *p_data
<< uint8(bytes
>> 24);
1287 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1288 *p_data
<< uint8(bytes
);
1290 *p_data
<< uint8(getLevel()); // player level
1291 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1292 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1295 *p_data
<< GetMapId();
1297 *p_data
<< GetPositionX();
1298 *p_data
<< GetPositionY();
1299 *p_data
<< GetPositionZ();
1301 *p_data
<< GetUInt32Value(PLAYER_GUILDID
); // guild id
1303 uint32 char_flags
= 0;
1304 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1305 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1306 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1307 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1308 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1309 char_flags
|= CHARACTER_FLAG_GHOST
;
1310 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1311 char_flags
|= CHARACTER_FLAG_RENAME
;
1312 // always send the flag if declined names aren't used
1313 // to let the client select a default method of declining the name
1314 if(!sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) || (result
&& result
->Fetch()[12].GetCppString() != ""))
1315 char_flags
|= CHARACTER_FLAG_DECLINED
;
1317 *p_data
<< (uint32
)char_flags
; // character flags
1318 *p_data
<< (uint32
)0; // new wotlk
1319 *p_data
<< (uint8
)1; // unknown
1323 uint32 petDisplayId
= 0;
1324 uint32 petLevel
= 0;
1325 uint32 petFamily
= 0;
1327 // show pet at selection character in character list only for non-ghost character
1328 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1330 Field
* fields
= result
->Fetch();
1332 uint32 entry
= fields
[9].GetUInt32();
1333 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1336 petDisplayId
= fields
[10].GetUInt32();
1337 petLevel
= fields
[11].GetUInt32();
1338 petFamily
= cInfo
->family
;
1342 *p_data
<< (uint32
)petDisplayId
;
1343 *p_data
<< (uint32
)petLevel
;
1344 *p_data
<< (uint32
)petFamily
;
1347 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1348 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1351 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1356 Field *fields = result->Fetch();
1357 uint8 slot = fields[0].GetUInt8() & 255;
1358 uint32 item_id = fields[1].GetUInt32();
1359 if( slot >= EQUIPMENT_SLOT_END )
1362 items[slot] = objmgr.GetItemPrototype(item_id);
1365 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1368 } while (result->NextRow());
1372 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1374 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1375 uint32 item_id
= GetUInt32Value(visualbase
);
1376 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1377 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1379 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1381 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1382 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1388 *p_data
<< (uint32
)proto
->DisplayInfoID
;
1389 *p_data
<< (uint8
)proto
->InventoryType
;
1390 *p_data
<< (uint32
)(enchant
?enchant
->aura_id
:0);
1394 *p_data
<< (uint32
)0;
1395 *p_data
<< (uint8
)0;
1396 *p_data
<< (uint32
)0; // enchant?
1399 *p_data
<< (uint32
)0; // first bag display id
1400 *p_data
<< (uint8
)0; // first bag inventory type
1401 *p_data
<< (uint32
)0; // enchant?
1404 bool Player::ToggleAFK()
1406 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1408 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1410 // afk player not allowed in battleground
1411 if(state
&& InBattleGround())
1412 LeaveBattleground();
1417 bool Player::ToggleDND()
1419 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1421 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1424 uint8
Player::chatTag() const
1441 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1443 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1445 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1449 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1450 Pet
* pet
= GetPet();
1452 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1454 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1455 if(!InBattleGround() && mEntry
->IsBattleGround() && !GetSession()->GetSecurity())
1458 // client without expansion support
1459 if(GetSession()->Expansion() < mEntry
->Expansion())
1461 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessable map %u", GetName(), mapid
);
1464 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1466 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1468 return false; // normal client can't teleport to this map...
1472 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1475 // if we were on a transport, leave
1476 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1478 m_transport
->RemovePassenger(this);
1480 m_movementInfo
.t_x
= 0.0f
;
1481 m_movementInfo
.t_y
= 0.0f
;
1482 m_movementInfo
.t_z
= 0.0f
;
1483 m_movementInfo
.t_o
= 0.0f
;
1484 m_movementInfo
.t_time
= 0;
1487 SetSemaphoreTeleport(true);
1489 // The player was ported to another map and looses the duel immediatly.
1490 // We have to perform this check before the teleport, otherwise the
1491 // ObjectAccessor won't find the flag.
1492 if (duel
&& this->GetMapId()!=mapid
)
1494 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1496 DuelComplete(DUEL_FLED
);
1499 // reset movement flags at teleport, because player will continue move with these flags after teleport
1500 SetUnitMovementFlags(0);
1502 if ((this->GetMapId() == mapid
) && (!m_transport
))
1504 // prepare zone change detect
1505 uint32 old_zone
= GetZoneId();
1508 if(!GetSession()->PlayerLogout())
1511 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1512 GetSession()->SendPacket(&data
);
1513 SetPosition( x
, y
, z
, orientation
, true);
1516 // this will be used instead of the current location in SaveToDB
1517 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1519 //BuildHeartBeatMsg(&data);
1520 //SendMessageToSet(&data, true);
1521 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1523 //same map, only remove pet if out of range
1524 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1526 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1527 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1529 m_temporaryUnsummonedPetNumber
= 0;
1531 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1535 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1538 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1541 if(pet
&& m_temporaryUnsummonedPetNumber
)
1543 Pet
* NewPet
= new Pet
;
1544 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1547 m_temporaryUnsummonedPetNumber
= 0;
1551 if(!GetSession()->PlayerLogout())
1553 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1554 SetSemaphoreTeleport(false);
1556 UpdateZone(GetZoneId());
1560 if(old_zone
!= GetZoneId())
1563 if(pvpInfo
.inHostileArea
)
1564 CastSpell(this, 2479, true);
1569 // far teleport to another map
1570 Map
* oldmap
= IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL
;
1571 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1573 // Check enter rights before map getting to avoid creating instance copy for player
1574 // this check not dependent from map instance copy and same for all instance copies of selected map
1575 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1577 SetSemaphoreTeleport(false);
1581 // If the map is not created, assume it is possible to enter it.
1582 // It will be created in the WorldPortAck.
1583 Map
*map
= MapManager::Instance().FindMap(mapid
);
1584 if (!map
|| map
->CanEnter(this))
1590 ResetContestedPvP();
1592 // remove player from battleground on far teleport (when changing maps)
1593 if(BattleGround
const* bg
= GetBattleGround())
1595 // Note: at battleground join battleground id set before teleport
1596 // and we already will found "current" battleground
1597 // just need check that this is targeted map or leave
1598 if(bg
->GetMapId() != mapid
)
1599 LeaveBattleground(false); // don't teleport to entry point
1602 // remove pet on map change
1605 //leaving map -> delete pet right away (doing this later will cause problems)
1606 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1607 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1609 m_temporaryUnsummonedPetNumber
= 0;
1611 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1614 // remove all dyn objects
1615 RemoveAllDynObjects();
1617 // stop spellcasting
1618 // not attempt interrupt teleportation spell at caster teleport
1619 if(!(options
& TELE_TO_SPELL
))
1620 if(IsNonMeleeSpellCasted(true))
1621 InterruptNonMeleeSpells(true);
1623 if(!GetSession()->PlayerLogout())
1625 // send transfer packets
1626 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1627 data
<< uint32(mapid
);
1630 data
<< m_transport
->GetEntry() << GetMapId();
1632 GetSession()->SendPacket(&data
);
1634 data
.Initialize(SMSG_NEW_WORLD
, (20));
1637 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1641 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1643 GetSession()->SendPacket( &data
);
1644 SendSavedInstances();
1646 // remove from old map now
1647 if(oldmap
) oldmap
->Remove(this, false);
1650 // new final coordinates
1654 float final_o
= orientation
;
1658 final_x
+= m_movementInfo
.t_x
;
1659 final_y
+= m_movementInfo
.t_y
;
1660 final_z
+= m_movementInfo
.t_z
;
1661 final_o
+= m_movementInfo
.t_o
;
1664 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1665 // if the player is saved before worldportack (at logout for example)
1666 // this will be used instead of the current location in SaveToDB
1668 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1670 // move packet sent by client always after far teleport
1671 // SetPosition(final_x, final_y, final_z, final_o, true);
1674 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1682 void Player::AddToWorld()
1684 ///- Do not add/remove the player from the object storage
1685 ///- It will crash when updating the ObjectAccessor
1686 ///- The player should only be added when logging in
1689 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1692 m_items
[i
]->AddToWorld();
1696 void Player::RemoveFromWorld()
1701 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1703 UnsummonAllTotems();
1708 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1711 m_items
[i
]->RemoveFromWorld();
1714 ///- Do not add/remove the player from the object storage
1715 ///- It will crash when updating the ObjectAccessor
1716 ///- The player should only be removed when logging out
1717 Unit::RemoveFromWorld();
1720 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1724 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1728 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1730 // talent who gave more rage on attack
1731 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1735 addRage
= damage
/rageconversion
*2.5;
1737 // Berserker Rage effect
1738 if(HasAura(18499,0))
1742 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1744 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1747 void Player::RegenerateAll()
1749 if (m_regenTimer
!= 0)
1751 uint32 regenDelay
= 2000;
1753 // Not in combat or they have regeneration
1754 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1755 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1758 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1759 Regenerate(POWER_RAGE
);
1762 Regenerate( POWER_ENERGY
);
1764 Regenerate( POWER_MANA
);
1766 Regenerate( POWER_RUNIC_POWER
);
1768 m_regenTimer
= regenDelay
;
1771 void Player::Regenerate(Powers power
)
1773 uint32 curValue
= GetPower(power
);
1774 uint32 maxValue
= GetMaxPower(power
);
1776 float addvalue
= 0.0f
;
1782 bool recentCast
= IsUnderLastManaUseEffect();
1783 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1786 // Mangos Updates Mana in intervals of 2s, which is correct
1787 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1791 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1794 case POWER_RAGE
: // Regenerate rage
1796 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1797 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1799 case POWER_ENERGY
: // Regenerate energy (rogue)
1802 case POWER_RUNIC_POWER
:
1803 addvalue
= 100; // TODO: find correct regen rate
1806 case POWER_HAPPINESS
:
1810 // Mana regen calculated in Player::UpdateManaRegen()
1811 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1812 if(power
!= POWER_MANA
)
1814 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1815 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1816 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1817 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1820 if (power
!= POWER_RAGE
)
1822 curValue
+= uint32(addvalue
);
1823 if (curValue
> maxValue
)
1824 curValue
= maxValue
;
1828 if(curValue
<= uint32(addvalue
))
1831 curValue
-= uint32(addvalue
);
1833 SetPower(power
, curValue
);
1836 void Player::RegenerateHealth()
1838 uint32 curValue
= GetHealth();
1839 uint32 maxValue
= GetMaxHealth();
1841 if (curValue
>= maxValue
) return;
1843 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1845 float addvalue
= 0.0f
;
1848 if ( IsPolymorphed() )
1849 addvalue
= GetMaxHealth()/3;
1850 // normal regen case (maybe partly in combat case)
1851 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1853 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1856 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1857 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1858 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1860 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1861 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1867 // always regeneration bonus (including combat)
1868 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1873 ModifyHealth(int32(addvalue
));
1876 bool Player::CanInteractWithNPCs(bool alive
) const
1878 if(alive
&& !isAlive())
1886 bool Player::IsUnderWater() const
1888 return IsInWater() &&
1889 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1892 void Player::SetInWater(bool apply
)
1894 if(m_isInWater
==apply
)
1897 //define player in water by opcodes
1898 //move player's guid into HateOfflineList of those mobs
1899 //which can't swim and move guid back into ThreatList when
1901 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1902 m_isInWater
= apply
;
1904 // remove auras that need water/land
1905 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
1907 getHostilRefManager().updateThreatTables();
1910 void Player::SetGameMaster(bool on
)
1914 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
1916 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1918 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
1919 ResetContestedPvP();
1921 getHostilRefManager().setOnlineOfflineState(false);
1926 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
1927 setFactionForRace(getRace());
1928 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1930 // restore FFA PvP Server state
1931 if(sWorld
.IsFFAPvPRealm())
1932 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
1934 // restore FFA PvP area state, remove not allowed for GM mounts
1935 UpdateArea(m_areaUpdateId
);
1937 getHostilRefManager().setOnlineOfflineState(true);
1940 ObjectAccessor::UpdateVisibilityForPlayer(this);
1943 void Player::SetGMVisible(bool on
)
1947 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
1949 // Reapply stealth/invisibility if active or show if not any
1950 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
1951 SetVisibility(VISIBILITY_GROUP_STEALTH
);
1952 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
1953 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
1955 SetVisibility(VISIBILITY_ON
);
1959 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
1961 SetAcceptWhispers(false);
1962 SetGameMaster(true);
1964 SetVisibility(VISIBILITY_OFF
);
1968 bool Player::IsGroupVisibleFor(Player
* p
) const
1970 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
1972 default: return IsInSameGroupWith(p
);
1973 case 1: return IsInSameRaidWith(p
);
1974 case 2: return GetTeam()==p
->GetTeam();
1978 bool Player::IsInSameGroupWith(Player
const* p
) const
1980 return p
==this || GetGroup() != NULL
&&
1981 GetGroup() == p
->GetGroup() &&
1982 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
1985 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1986 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1987 void Player::UninviteFromGroup()
1989 if(GetGroupInvite()) // uninvited invitee
1991 Group
* group
= GetGroupInvite();
1992 group
->RemoveInvite(this);
1994 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
1996 if(group
->IsCreated())
1998 group
->Disband(true);
1999 objmgr
.RemoveGroup(group
);
2002 group
->RemoveAllInvites();
2009 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2013 if (group
->RemoveMember(guid
, 0) <= 1)
2015 // group->Disband(); already disbanded in RemoveMember
2016 objmgr
.RemoveGroup(group
);
2018 // removemember sets the player's group pointer to NULL
2023 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2025 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2026 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2027 data
<< uint32(GivenXP
+RestXP
); // given experience
2028 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2031 data
<< uint32(GivenXP
); // experience without rested bonus
2032 data
<< float(1); // 1 - none 0 - 100% group bonus output
2034 data
<< uint8(0); // new 2.4.0
2035 GetSession()->SendPacket(&data
);
2038 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2046 uint32 level
= getLevel();
2048 // XP to money conversion processed in Player::RewardQuest
2049 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2052 // handle SPELL_AURA_MOD_XP_PCT auras
2053 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2054 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2055 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2057 // XP resting bonus for kill
2058 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2060 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2062 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2063 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2064 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2066 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2070 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2071 GiveLevel(level
+ 1);
2074 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2077 SetUInt32Value(PLAYER_XP
, newXP
);
2080 // Update player to next level
2081 // Current player experience not update (must be update by caller)
2082 void Player::GiveLevel(uint32 level
)
2084 if ( level
== getLevel() )
2087 PlayerLevelInfo info
;
2088 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2090 PlayerClassLevelInfo classInfo
;
2091 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2093 // send levelup info to client
2094 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2095 data
<< uint32(level
);
2096 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2097 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2098 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2106 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2107 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2109 GetSession()->SendPacket(&data
);
2111 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(level
));
2113 //update level, max level of skills
2114 if(getLevel()!= level
)
2115 m_Played_time
[1] = 0; // Level Played Time reset
2119 // save base values (bonuses already included in stored stats
2120 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2121 SetCreateStat(Stats(i
), info
.stats
[i
]);
2123 SetCreateHealth(classInfo
.basehealth
);
2124 SetCreateMana(classInfo
.basemana
);
2126 InitTalentForLevel();
2127 InitTaxiNodesForLevel();
2128 InitGlyphsForLevel();
2132 // set current level health and mana/energy to maximum after applying all mods.
2133 SetHealth(GetMaxHealth());
2134 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2135 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2136 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2137 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2138 SetPower(POWER_FOCUS
, 0);
2139 SetPower(POWER_HAPPINESS
, 0);
2141 // give level to summoned pet
2142 Pet
* pet
= GetPet();
2143 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2144 pet
->GivePetLevel(level
);
2145 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2148 void Player::InitTalentForLevel()
2150 uint32 level
= getLevel();
2151 // talents base at level diff ( talents = level - 9 but some can be used already)
2154 // Remove all talent points
2155 if(m_usedTalentCount
> 0) // Free any used talents
2158 SetFreeTalentPoints(0);
2163 uint32 talentPointsForLevel
= uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
2164 // if used more that have then reset
2165 if(m_usedTalentCount
> talentPointsForLevel
)
2167 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2170 SetFreeTalentPoints(0);
2172 // else update amount of free points
2174 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2178 void Player::InitStatsForLevel(bool reapplyMods
)
2180 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2181 _RemoveAllStatBonuses();
2183 PlayerClassLevelInfo classInfo
;
2184 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2186 PlayerLevelInfo info
;
2187 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2189 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2190 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(getLevel()));
2194 // set default cast time multiplier
2195 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2197 // reset size before reapply auras
2198 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2200 // save base values (bonuses already included in stored stats
2201 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2202 SetCreateStat(Stats(i
), info
.stats
[i
]);
2204 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2205 SetStat(Stats(i
), info
.stats
[i
]);
2207 SetCreateHealth(classInfo
.basehealth
);
2210 SetCreateMana(classInfo
.basemana
);
2212 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2216 //reset rating fields values
2217 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2218 SetUInt32Value(index
, 0);
2220 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2221 for (int i
= 0; i
< 7; i
++)
2223 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2224 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2225 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2228 //reset attack power, damage and attack speed fields
2229 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2230 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2231 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2233 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2234 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2235 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2236 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2237 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2238 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2240 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2241 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2242 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2243 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2244 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2245 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2247 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2248 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2249 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2250 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2252 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2253 for (uint8 i
= 0; i
< 7; ++i
)
2254 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2256 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2257 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2258 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2261 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2263 // set armor (resistance 0) to original value (create_agility*2)
2264 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2265 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2266 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2267 // set other resistance to original value (0)
2268 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2270 SetResistance(SpellSchools(i
), 0);
2271 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2272 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2275 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2276 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2277 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2279 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2280 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2282 // Init data for form but skip reapply item mods for form
2283 InitDataForForm(reapplyMods
);
2286 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2287 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2289 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2291 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2292 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2294 // cleanup unit flags (will be re-applied if need at aura load).
2295 RemoveFlag( UNIT_FIELD_FLAGS
,
2296 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2297 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2298 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2299 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2300 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2301 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2303 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2304 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
| PLAYER_FLAGS_FFA_PVP
);
2306 SetByteValue(UNIT_FIELD_BYTES_1
, 2, 0x00); // one form stealth modified bytes
2308 // restore if need some important flags
2309 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2311 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2312 _ApplyAllStatBonuses();
2314 // set current level health and mana/energy to maximum after applying all mods.
2315 SetHealth(GetMaxHealth());
2316 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2317 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2318 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2319 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2320 SetPower(POWER_FOCUS
, 0);
2321 SetPower(POWER_HAPPINESS
, 0);
2322 SetPower(POWER_RUNIC_POWER
, 0);
2325 void Player::SendInitialSpells()
2327 uint16 spellCount
= 0;
2329 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2332 size_t countPos
= data
.wpos();
2333 data
<< uint16(spellCount
); // spell count placeholder
2335 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2337 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2340 if(!itr
->second
->active
|| itr
->second
->disabled
)
2343 data
<< uint16(itr
->first
);
2344 //data << uint16(itr->second->slotId);
2345 data
<< uint16(0); // it's not slot id
2350 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2352 uint16 spellCooldowns
= m_spellCooldowns
.size();
2353 data
<< uint16(spellCooldowns
);
2354 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); itr
++)
2356 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2360 data
<< uint16(itr
->first
);
2362 time_t cooldown
= 0;
2363 time_t curTime
= time(NULL
);
2364 if(itr
->second
.end
> curTime
)
2365 cooldown
= (itr
->second
.end
-curTime
)*1000;
2367 data
<< uint16(itr
->second
.itemid
); // cast item id
2368 data
<< uint16(sEntry
->Category
); // spell category
2369 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2372 data
<< uint32(cooldown
);
2376 data
<< uint32(cooldown
);
2381 GetSession()->SendPacket(&data
);
2383 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2386 void Player::RemoveMail(uint32 id
)
2388 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2390 if ((*itr
)->messageID
== id
)
2392 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2399 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2401 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2402 data
<< (uint32
) mailId
;
2403 data
<< (uint32
) mailAction
;
2404 data
<< (uint32
) mailError
;
2405 if ( mailError
== MAIL_ERR_BAG_FULL
)
2406 data
<< (uint32
) equipError
;
2407 else if( mailAction
== MAIL_ITEM_TAKEN
)
2409 data
<< (uint32
) item_guid
; // item guid low?
2410 data
<< (uint32
) item_count
; // item count?
2412 GetSession()->SendPacket(&data
);
2415 void Player::SendNewMail()
2417 // deliver undelivered mail
2418 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2420 GetSession()->SendPacket(&data
);
2423 void Player::UpdateNextMailTimeAndUnreads()
2425 // calculate next delivery time (min. from non-delivered mails
2426 // and recalculate unReadMail
2427 time_t cTime
= time(NULL
);
2428 m_nextMailDelivereTime
= 0;
2430 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2432 if((*itr
)->deliver_time
> cTime
)
2434 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2435 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2437 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2442 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2444 if(deliver_time
<= time(NULL
)) // ready now
2449 else // not ready and no have ready mails
2451 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2452 m_nextMailDelivereTime
= deliver_time
;
2456 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool loading
, uint16 slot_id
, bool disabled
)
2458 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2461 // do character spell book cleanup (all characters)
2462 if(loading
&& !learning
) // spell load case
2464 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2465 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2468 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2473 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2475 // do character spell book cleanup (all characters)
2476 if(loading
&& !learning
) // spell load case
2478 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2479 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2482 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2487 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2489 bool disabled_case
= false;
2490 bool superceded_old
= false;
2492 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2493 if (itr
!= m_spells
.end())
2495 // update active state for known spell
2496 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2498 itr
->second
->active
= active
;
2500 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2501 if(loading
&& !learning
)
2502 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2503 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2504 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2508 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2509 data
<< uint16(spell_id
);
2510 GetSession()->SendPacket(&data
);
2512 return active
; // learn (show in spell book if active now)
2515 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2517 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2518 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2519 itr
->second
->disabled
= disabled
;
2524 disabled_case
= true;
2526 else switch(itr
->second
->state
)
2528 case PLAYERSPELL_UNCHANGED
: // known saved spell
2530 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2533 m_spells
.erase(itr
);
2534 state
= PLAYERSPELL_CHANGED
;
2535 break; // need re-add
2537 default: // known not saved yet spell (new or modified)
2539 // can be in case spell loading but learned at some previous spell loading
2540 if(loading
&& !learning
)
2541 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2548 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2550 // talent: unlearn all other talent ranks (high and low)
2551 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2553 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2555 for(int i
=0; i
<5; ++i
)
2557 // skip learning spell and no rank spell case
2558 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2559 if(!rankSpellId
|| rankSpellId
==spell_id
)
2562 // skip unknown ranks
2563 if(!HasSpell(rankSpellId
))
2566 removeSpell(rankSpellId
);
2570 // non talent spell: learn low ranks (recursive call)
2571 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2573 if(loading
) // at spells loading, no output, but allow save
2574 addSpell(prev_spell
,active
,true,loading
,SPELL_WITHOUT_SLOT_ID
,disabled
);
2575 else // at normal learning
2576 learnSpell(prev_spell
);
2579 PlayerSpell
*newspell
= new PlayerSpell
;
2580 newspell
->active
= active
;
2581 newspell
->state
= state
;
2582 newspell
->disabled
= disabled
;
2584 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2585 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2587 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2589 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2590 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2591 if(!i_spellInfo
) continue;
2593 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2595 if(itr
->second
->active
)
2597 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2599 if(!loading
) // not send spell (re-/over-)learn packets at loading
2601 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2602 data
<< uint16(itr
->first
);
2603 data
<< uint16(spell_id
);
2604 GetSession()->SendPacket( &data
);
2607 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2608 itr
->second
->active
= false;
2609 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2610 superceded_old
= true; // new spell replace old in action bars and spell book.
2612 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2614 if(!loading
) // not send spell (re-/over-)learn packets at loading
2616 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2617 data
<< uint16(spell_id
);
2618 data
<< uint16(itr
->first
);
2619 GetSession()->SendPacket( &data
);
2622 // mark new spell as disable (not learned yet for client and will not learned)
2623 newspell
->active
= false;
2624 if(newspell
->state
!= PLAYERSPELL_NEW
)
2625 newspell
->state
= PLAYERSPELL_CHANGED
;
2632 uint16 tmpslot
=slot_id
;
2634 if (tmpslot
== SPELL_WITHOUT_SLOT_ID
)
2637 PlayerSpellMap::iterator itr
;
2638 for (itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2640 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2642 if (itr
->second
->slotId
> maxid
)
2643 maxid
= itr
->second
->slotId
;
2645 tmpslot
= maxid
+ 1;
2648 newspell
->slotId
= tmpslot
;
2649 m_spells
[spell_id
] = newspell
;
2651 // return false if spell disabled
2652 if (newspell
->disabled
)
2656 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2658 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2659 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2660 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2662 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2663 CastSpell(this, spell_id
, true);
2665 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2666 else if (IsPassiveSpell(spell_id
))
2668 // if spell doesn't require a stance or the player is in the required stance
2669 if( ( !spellInfo
->Stances
&&
2670 spell_id
!= 5420 && spell_id
!= 5419 && spell_id
!= 7376 &&
2671 spell_id
!= 7381 && spell_id
!= 21156 && spell_id
!= 21009 &&
2672 spell_id
!= 21178 && spell_id
!= 33948 && spell_id
!= 40121 ) ||
2673 m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))) ||
2674 (spell_id
== 5420 && m_form
== FORM_TREE
) ||
2675 (spell_id
== 5419 && m_form
== FORM_TRAVEL
) ||
2676 (spell_id
== 7376 && m_form
== FORM_DEFENSIVESTANCE
) ||
2677 (spell_id
== 7381 && m_form
== FORM_BERSERKERSTANCE
) ||
2678 (spell_id
== 21156 && m_form
== FORM_BATTLESTANCE
)||
2679 (spell_id
== 21178 && (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
) ) ||
2680 (spell_id
== 33948 && m_form
== FORM_FLIGHT
) ||
2681 (spell_id
== 40121 && m_form
== FORM_FLIGHT_EPIC
) )
2682 //Check CasterAuraStates
2683 if (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)))
2684 CastSpell(this, spell_id
, true);
2686 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2688 CastSpell(this, spell_id
, true);
2692 // update used talent points count
2693 m_usedTalentCount
+= talentCost
;
2695 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2696 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2698 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2699 SetFreePrimaryProffesions(freeProfs
-1);
2702 // add dependent skills
2703 uint16 maxskill
= GetMaxSkillValueForLevel();
2705 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2709 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2710 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2712 if(skill_value
< spellLearnSkill
->value
)
2713 skill_value
= spellLearnSkill
->value
;
2715 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2717 if(skill_max_value
< new_skill_max_value
)
2718 skill_max_value
= new_skill_max_value
;
2720 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2724 // not ranked skills
2725 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2726 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2728 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2730 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2734 if(HasSkill(pSkill
->id
))
2737 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2738 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2739 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2740 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2741 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2743 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2745 case SKILL_RANGE_LANGUAGE
:
2746 SetSkill(pSkill
->id
, 300, 300 );
2748 case SKILL_RANGE_LEVEL
:
2749 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2751 case SKILL_RANGE_MONO
:
2752 SetSkill(pSkill
->id
, 1, 1 );
2761 // learn dependent spells
2762 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2763 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2765 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2767 if(!itr
->second
.autoLearned
)
2769 if(loading
) // at spells loading, no output, but allow save
2770 addSpell(itr
->second
.spell
,true,true,loading
);
2771 else // at normal learning
2772 learnSpell(itr
->second
.spell
);
2776 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2777 return active
&& !disabled
&& !superceded_old
;
2780 void Player::learnSpell(uint32 spell_id
)
2782 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2784 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2785 bool active
= disabled
? itr
->second
->active
: true;
2787 bool learning
= addSpell(spell_id
,active
);
2789 // learn all disabled higher ranks (recursive)
2790 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2791 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2793 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2794 if (disabled
&& iter
!= m_spells
.end() && iter
->second
->disabled
)
2795 learnSpell(i
->second
);
2798 // prevent duplicated entires in spell book
2802 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2803 data
<< uint32(spell_id
);
2804 GetSession()->SendPacket(&data
);
2807 void Player::removeSpell(uint32 spell_id
, bool disabled
)
2809 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2810 if (itr
== m_spells
.end())
2813 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2816 // unlearn non talent higher ranks (recursive)
2817 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2818 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2819 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2820 removeSpell(itr2
->second
,disabled
);
2823 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2824 data
<< uint16(spell_id
);
2825 GetSession()->SendPacket(&data
);
2829 itr
->second
->disabled
= disabled
;
2830 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2831 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2835 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2838 m_spells
.erase(itr
);
2841 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2844 RemoveAurasDueToSpell(spell_id
);
2847 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2848 RemovePetAura(petSpell
);
2850 // free talent points
2851 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2854 if(talentCosts
< m_usedTalentCount
)
2855 m_usedTalentCount
-= talentCosts
;
2857 m_usedTalentCount
= 0;
2860 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2861 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2863 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2864 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2865 SetFreePrimaryProffesions(freeProfs
);
2868 // remove dependent skill
2869 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2872 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2873 if(!prev_spell
) // first rank, remove skill
2874 SetSkill(spellLearnSkill
->skill
,0,0);
2877 // search prev. skill setting by spell ranks chain
2878 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
2879 while(!prevSkill
&& prev_spell
)
2881 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
2882 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
2885 if(!prevSkill
) // not found prev skill setting, remove skill
2886 SetSkill(spellLearnSkill
->skill
,0,0);
2887 else // set to prev. skill setting values
2889 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
2890 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
2892 if(skill_value
> prevSkill
->value
)
2893 skill_value
= prevSkill
->value
;
2895 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
2897 if(skill_max_value
> new_skill_max_value
)
2898 skill_max_value
= new_skill_max_value
;
2900 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
2907 // not ranked skills
2908 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2909 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2911 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2913 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2917 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2918 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2919 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2920 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2921 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2923 // not reset skills for professions and racial abilities
2924 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
2925 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
2928 SetSkill(pSkill
->id
, 0, 0 );
2933 // remove dependent spells
2934 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2935 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2937 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2938 removeSpell(itr2
->second
.spell
, disabled
);
2941 void Player::RemoveArenaSpellCooldowns()
2943 // remove cooldowns on spells that has < 15 min CD
2944 SpellCooldowns::iterator itr
, next
;
2945 // iterate spell cooldowns
2946 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
2950 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
2951 // check if spellentry is present and if the cooldown is less than 15 mins
2953 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
2954 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
2957 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
2958 data
<< uint32(itr
->first
);
2960 GetSession()->SendPacket(&data
);
2962 m_spellCooldowns
.erase(itr
);
2967 void Player::RemoveAllSpellCooldown()
2969 if(!m_spellCooldowns
.empty())
2971 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
2973 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
2974 data
<< uint32(itr
->first
);
2975 data
<< uint64(GetGUID());
2976 GetSession()->SendPacket(&data
);
2978 m_spellCooldowns
.clear();
2982 void Player::_LoadSpellCooldowns(QueryResult
*result
)
2984 m_spellCooldowns
.clear();
2986 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2990 time_t curTime
= time(NULL
);
2994 Field
*fields
= result
->Fetch();
2996 uint32 spell_id
= fields
[0].GetUInt32();
2997 uint32 item_id
= fields
[1].GetUInt32();
2998 time_t db_time
= (time_t)fields
[2].GetUInt64();
3000 if(!sSpellStore
.LookupEntry(spell_id
))
3002 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3006 // skip outdated cooldown
3007 if(db_time
<= curTime
)
3010 AddSpellCooldown(spell_id
, item_id
, db_time
);
3012 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3014 while( result
->NextRow() );
3020 void Player::_SaveSpellCooldowns()
3022 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3024 time_t curTime
= time(NULL
);
3026 // remove outdated and save active
3027 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3029 if(itr
->second
.end
<= curTime
)
3030 m_spellCooldowns
.erase(itr
++);
3033 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
));
3039 uint32
Player::resetTalentsCost() const
3041 // The first time reset costs 1 gold
3042 if(m_resetTalentsCost
< 1*GOLD
)
3045 else if(m_resetTalentsCost
< 5*GOLD
)
3047 // After that it increases in increments of 5 gold
3048 else if(m_resetTalentsCost
< 10*GOLD
)
3052 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3055 // This cost will be reduced by a rate of 5 gold per month
3056 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3057 // to a minimum of 10 gold.
3058 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3062 // After that it increases in increments of 5 gold
3063 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3064 // until it hits a cap of 50 gold.
3065 if(new_cost
> 50*GOLD
)
3072 bool Player::resetTalents(bool no_cost
)
3074 // not need after this call
3075 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3077 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3078 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3081 uint32 level
= getLevel();
3082 uint32 talentPointsForLevel
= level
< 10 ? 0 : uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
3084 if (m_usedTalentCount
== 0)
3086 SetFreeTalentPoints(talentPointsForLevel
);
3094 cost
= resetTalentsCost();
3096 if (GetMoney() < cost
)
3098 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3103 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3105 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3107 if (!talentInfo
) continue;
3109 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3114 // unlearn only talents for character class
3115 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3116 // to prevent unexpected lost normal learned spell skip another class talents
3117 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3120 for (int j
= 0; j
< 5; j
++)
3122 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3124 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3130 // remove learned spells (all ranks)
3131 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3133 // unlearn if first rank is talent or learned by talent
3134 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3136 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3137 itr
= GetSpellMap().begin();
3146 SetFreeTalentPoints(talentPointsForLevel
);
3150 ModifyMoney(-(int32
)cost
);
3152 m_resetTalentsCost
= cost
;
3153 m_resetTalentsTime
= time(NULL
);
3156 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3157 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3162 bool Player::_removeSpell(uint16 spell_id
)
3164 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3165 if (itr
!= m_spells
.end())
3168 m_spells
.erase(itr
);
3174 Mail
* Player::GetMail(uint32 id
)
3176 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
3178 if ((*itr
)->messageID
== id
)
3186 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3190 Object::_SetCreateBits(updateMask
, target
);
3194 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3196 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3197 updateMask
->SetBit(index
);
3202 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3206 Object::_SetUpdateBits(updateMask
, target
);
3210 Object::_SetUpdateBits(updateMask
, target
);
3211 *updateMask
&= updateVisualBits
;
3215 void Player::InitVisibleBits()
3217 updateVisualBits
.SetCount(PLAYER_END
);
3219 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3220 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3221 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3222 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3223 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3224 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3225 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3226 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3227 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3228 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3229 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3230 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3231 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3232 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3233 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3234 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3235 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3236 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3237 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3238 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3239 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3240 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3241 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3242 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3243 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3244 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3245 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3246 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3247 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3248 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3249 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3250 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3251 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3252 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3253 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3254 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3255 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3256 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3257 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3258 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3259 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3260 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3261 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3262 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3263 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3264 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3265 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3266 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3267 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3268 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3269 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3270 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3271 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3272 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3273 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3275 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3276 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3277 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3278 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3279 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3280 updateVisualBits
.SetBit(PLAYER_BYTES
);
3281 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3282 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3283 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3284 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3286 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3287 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3288 updateVisualBits
.SetBit(i
);
3290 // Players visible items are not inventory stuff
3291 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3293 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3296 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3297 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3300 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3302 // item enchantments
3303 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3304 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3306 // random properties
3307 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3308 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3309 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3312 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3315 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3317 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3319 if(m_items
[i
] == NULL
)
3322 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3327 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3329 if(m_items
[i
] == NULL
)
3332 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3334 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3336 if(m_items
[i
] == NULL
)
3339 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3343 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3346 void Player::DestroyForPlayer( Player
*target
) const
3348 Unit::DestroyForPlayer( target
);
3350 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3352 if(m_items
[i
] == NULL
)
3355 m_items
[i
]->DestroyForPlayer( target
);
3360 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3362 if(m_items
[i
] == NULL
)
3365 m_items
[i
]->DestroyForPlayer( target
);
3367 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3369 if(m_items
[i
] == NULL
)
3372 m_items
[i
]->DestroyForPlayer( target
);
3377 bool Player::HasSpell(uint32 spell
) const
3379 PlayerSpellMap::const_iterator itr
= m_spells
.find((uint16
)spell
);
3380 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
);
3383 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3386 return TRAINER_SPELL_RED
;
3388 if (!trainer_spell
->spell
)
3389 return TRAINER_SPELL_RED
;
3392 if(HasSpell(trainer_spell
->spell
))
3393 return TRAINER_SPELL_GRAY
;
3395 // check race/class requirement
3396 if(!IsSpellFitByClassAndRace(trainer_spell
->spell
))
3397 return TRAINER_SPELL_RED
;
3399 // check level requirement
3400 if(getLevel() < trainer_spell
->reqlevel
)
3401 return TRAINER_SPELL_RED
;
3403 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->spell
))
3405 // check prev.rank requirement
3406 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3407 return TRAINER_SPELL_RED
;
3409 // check additional spell requirement
3410 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3411 return TRAINER_SPELL_RED
;
3414 // check skill requirement
3415 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3416 return TRAINER_SPELL_RED
;
3418 // exist, already checked at loading
3419 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->spell
);
3421 // secondary prof. or not prof. spell
3422 uint32 skill
= spell
->EffectMiscValue
[1];
3424 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3425 return TRAINER_SPELL_GREEN
;
3427 // check primary prof. limit
3428 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3429 return TRAINER_SPELL_RED
;
3431 return TRAINER_SPELL_GREEN
;
3434 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3436 uint32 guid
= GUID_LOPART(playerguid
);
3438 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3439 // bones will be deleted by corpse/bones deleting thread shortly
3440 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3442 // remove from guild
3443 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3446 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3448 guild
->DelMember(guid
);
3451 // the player was uninvited already on logout so just remove from group
3452 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3455 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3457 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3460 RemoveFromGroup(group
, playerguid
);
3464 // remove signs from petitions (also remove petitions if owner);
3465 RemovePetitionsAndSigns(playerguid
, 10);
3467 // return back all mails with COD and Item 0 1 2 3 4 5 6
3468 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
);
3473 Field
*fields
= resultMail
->Fetch();
3475 uint32 mail_id
= fields
[0].GetUInt32();
3476 uint16 mailTemplateId
= fields
[1].GetUInt16();
3477 uint32 sender
= fields
[2].GetUInt32();
3478 std::string subject
= fields
[3].GetCppString();
3479 uint32 itemTextId
= fields
[4].GetUInt32();
3480 uint32 money
= fields
[5].GetUInt32();
3481 bool has_items
= fields
[6].GetBool();
3483 //we can return mail now
3484 //so firstly delete the old one
3485 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3490 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id
);
3495 Field
*fields2
= resultItems
->Fetch();
3497 uint32 item_guidlow
= fields2
[0].GetUInt32();
3498 uint32 item_template
= fields2
[1].GetUInt32();
3500 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3503 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3507 Item
*pItem
= NewItemOrBag(itemProto
);
3508 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
)))
3510 pItem
->FSetState(ITEM_REMOVED
);
3511 pItem
->SaveToDB(); // it also deletes item object !
3515 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3517 while (resultItems
->NextRow());
3523 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3525 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3527 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, 0, mailTemplateId
);
3529 while (resultMail
->NextRow());
3534 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3535 // Get guids of character's pets, will deleted in transaction
3536 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3538 // NOW we can finally clear other DB data related to character
3539 CharacterDatabase
.BeginTransaction();
3544 Field
*fields3
= resultPets
->Fetch();
3545 uint32 petguidlow
= fields3
[0].GetUInt32();
3546 Pet::DeleteFromDB(petguidlow
);
3547 } while (resultPets
->NextRow());
3551 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3552 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3553 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3554 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3555 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3556 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3557 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3558 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3559 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3560 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3561 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3562 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3563 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3564 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3565 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3566 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3567 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3568 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3569 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3570 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3571 CharacterDatabase
.CommitTransaction();
3573 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3574 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3577 void Player::SetMovement(PlayerMovementType pType
)
3582 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3583 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3584 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3585 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3587 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3590 data
.append(GetPackGUID());
3592 GetSession()->SendPacket( &data
);
3596 - a resurrectable corpse must not be loaded for the player (only bones)
3597 - the player must be in world
3599 void Player::BuildPlayerRepop()
3601 if(getRace() == RACE_NIGHTELF
)
3602 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)
3603 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3605 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3606 // there must be SMSG.STOP_MIRROR_TIMER
3607 // there we must send 888 opcode
3609 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3612 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3616 // create a corpse and place it at the player's location
3618 Corpse
*corpse
= GetCorpse();
3621 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3624 GetMap()->Add(corpse
);
3626 // convert player body to ghost
3629 SetMovement(MOVE_WATER_WALK
);
3630 if(!GetSession()->isLogingOut())
3631 SetMovement(MOVE_UNROOT
);
3633 // BG - remove insignia related
3634 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3636 SendCorpseReclaimDelay();
3638 // to prevent cheating
3639 corpse
->ResetGhostTime();
3641 StopMirrorTimers(); //disable timers(bars)
3643 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3645 SetByteValue(UNIT_FIELD_BYTES_1
, 3, PLAYER_STATE_FLAG_ALWAYS_STAND
);
3648 void Player::SendDelayResponse(const uint32 ml_seconds
)
3650 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3651 data
<< (uint32
)time(NULL
);
3653 GetSession()->SendPacket( &data
);
3656 void Player::ResurrectPlayer(float restore_percent
, bool updateToWorld
, bool applySickness
)
3658 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3663 GetSession()->SendPacket(&data
);
3665 // speed change, land walk
3667 // remove death flag + set aura
3668 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3669 if(getRace() == RACE_NIGHTELF
)
3670 RemoveAurasDueToSpell(20584); // speed bonuses
3671 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3673 setDeathState(ALIVE
);
3675 SetMovement(MOVE_LAND_WALK
);
3676 SetMovement(MOVE_UNROOT
);
3680 // set health/powers (0- will be set in caller)
3681 if(restore_percent
>0.0f
)
3683 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3684 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3685 SetPower(POWER_RAGE
, 0);
3686 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3690 ObjectAccessor::UpdateVisibilityForPlayer(this);
3692 // some items limited to specific map
3693 DestroyZoneLimitedItem( true, GetZoneId());
3695 if(!applySickness
|| getLevel() <= 10)
3698 //Characters from level 1-10 are not affected by resurrection sickness.
3699 //Characters from level 11-19 will suffer from one minute of sickness
3700 //for each level they are above 10.
3701 //Characters level 20 and up suffer from ten minutes of sickness.
3702 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3704 if(int32(getLevel()) >= startLevel
)
3706 // set resurrection sickness
3707 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3709 // not full duration
3710 if(int32(getLevel()) < startLevel
+9)
3712 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3714 for(int i
=0; i
< 3; ++i
)
3716 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3718 Aur
->SetAuraDuration(delta
*1000);
3719 Aur
->SendAuraUpdate(false);
3726 void Player::KillPlayer()
3728 SetMovement(MOVE_ROOT
);
3730 StopMirrorTimers(); //disable timers(bars)
3732 setDeathState(CORPSE
);
3733 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3735 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3736 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3738 // 6 minutes until repop at graveyard
3739 m_deathTimer
= 6*MINUTE
*1000;
3741 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3743 // don't create corpse at this moment, player might be falling
3745 // update visibility
3746 ObjectAccessor::UpdateObjectVisibility(this);
3749 void Player::CreateCorpse()
3751 // prevent existence 2 corpse for player
3754 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3756 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3759 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3760 GetPositionY(), GetPositionZ(), GetOrientation()))
3766 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3767 _pb
= GetUInt32Value(PLAYER_BYTES
);
3768 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3770 uint8 race
= (uint8
)(_uf
);
3771 uint8 skin
= (uint8
)(_pb
);
3772 uint8 face
= (uint8
)(_pb
>> 8);
3773 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3774 uint8 haircolor
= (uint8
)(_pb
>> 24);
3775 uint8 facialhair
= (uint8
)(_pb2
);
3777 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3778 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3780 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3781 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3783 uint32 flags
= CORPSE_FLAG_UNK2
;
3784 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3785 flags
|= CORPSE_FLAG_HIDE_HELM
;
3786 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3787 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3788 if(InBattleGround())
3789 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3790 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3792 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3794 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3797 uint16 iIventoryType
;
3799 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3803 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3804 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3806 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3807 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3811 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3812 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3814 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3817 // register for player, but not show
3818 ObjectAccessor::Instance().AddCorpse(corpse
);
3821 void Player::SpawnCorpseBones()
3823 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3824 SaveToDB(); // prevent loading as ghost without corpse
3827 Corpse
* Player::GetCorpse() const
3829 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3832 void Player::DurabilityLossAll(double percent
, bool inventory
)
3834 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3835 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3836 DurabilityLoss(pItem
,percent
);
3840 // bags not have durability
3841 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3843 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3844 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3845 DurabilityLoss(pItem
,percent
);
3847 // keys not have durability
3848 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3850 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3851 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3852 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
3853 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
3854 if(Item
* pItem
= GetItemByPos( i
, j
))
3855 DurabilityLoss(pItem
,percent
);
3859 void Player::DurabilityLoss(Item
* item
, double percent
)
3864 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3869 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
3871 if(pDurabilityLoss
< 1 )
3872 pDurabilityLoss
= 1;
3874 DurabilityPointsLoss(item
,pDurabilityLoss
);
3877 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
3879 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3880 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3881 DurabilityPointsLoss(pItem
,points
);
3885 // bags not have durability
3886 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3888 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3889 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3890 DurabilityPointsLoss(pItem
,points
);
3892 // keys not have durability
3893 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3895 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3896 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3897 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
3898 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
3899 if(Item
* pItem
= GetItemByPos( i
, j
))
3900 DurabilityPointsLoss(pItem
,points
);
3904 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
3906 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3907 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3908 int32 pNewDurability
= pOldDurability
- points
;
3910 if (pNewDurability
< 0)
3912 else if (pNewDurability
> pMaxDurability
)
3913 pNewDurability
= pMaxDurability
;
3915 if (pOldDurability
!= pNewDurability
)
3917 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3918 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
3919 _ApplyItemMods(item
,item
->GetSlot(), false);
3921 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
3923 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3924 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
3925 _ApplyItemMods(item
,item
->GetSlot(), true);
3927 item
->SetState(ITEM_CHANGED
, this);
3931 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
3933 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
3934 DurabilityPointsLoss(pItem
,1);
3937 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
3939 uint32 TotalCost
= 0;
3940 // equipped, backpack, bags itself
3941 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3942 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
3944 // bank, buyback and keys not repaired
3946 // items in inventory bags
3947 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
3948 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
3949 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
3953 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
3955 Item
* item
= GetItemByPos(pos
);
3957 uint32 TotalCost
= 0;
3961 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3965 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3969 uint32 LostDurability
= maxDurability
- curDurability
;
3970 if(LostDurability
>0)
3972 ItemPrototype
const *ditemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(item
->GetEntry());
3975 sLog
.outError("ERROR: RepairDurability: Unknown item id %u", ditemProto
);
3979 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
3982 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", dcost
);
3986 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry((ditemProto
->Quality
+1)*2);
3987 if(!dQualitymodEntry
)
3989 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntry
);
3993 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
3994 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
3996 costs
= uint32(costs
* discountMod
);
3998 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4003 if (GetGuildId()==0)
4005 DEBUG_LOG("You are not member of a guild");
4009 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4013 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4015 DEBUG_LOG("You do not have rights to withdraw for repairs");
4019 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4021 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4025 if (pGuild
->GetGuildBankMoney() < costs
)
4027 DEBUG_LOG("There is not enough money in bank");
4031 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4034 else if (GetMoney() < costs
)
4036 DEBUG_LOG("You do not have enough money");
4040 ModifyMoney( -int32(costs
) );
4044 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4045 item
->SetState(ITEM_CHANGED
, this);
4047 // reapply mods for total broken and repaired item if equipped
4048 if(IsEquipmentPos(pos
) && !curDurability
)
4049 _ApplyItemMods(item
,pos
& 255, true);
4053 void Player::RepopAtGraveyard()
4055 // note: this can be called also when the player is alive
4056 // for example from WorldSession::HandleMovementOpcodes
4058 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4060 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4061 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4063 ResurrectPlayer(0.5f
);
4067 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4069 // Special handle for battleground maps
4070 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4072 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4073 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4075 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4077 // stop countdown until repop
4080 // if no grave found, stay at the current location
4081 // and don't show spirit healer location
4084 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4085 if(isDead()) // not send if alive, because it used in TeleportTo()
4087 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4088 data
<< ClosestGrave
->map_id
;
4089 data
<< ClosestGrave
->x
;
4090 data
<< ClosestGrave
->y
;
4091 data
<< ClosestGrave
->z
;
4092 GetSession()->SendPacket(&data
);
4097 void Player::JoinedChannel(Channel
*c
)
4099 m_channels
.push_back(c
);
4102 void Player::LeftChannel(Channel
*c
)
4104 m_channels
.remove(c
);
4107 void Player::CleanupChannels()
4109 while(!m_channels
.empty())
4111 Channel
* ch
= *m_channels
.begin();
4112 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4113 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4114 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4115 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4118 sLog
.outDebug("Player: channels cleaned up!");
4121 void Player::UpdateLocalChannels(uint32 newZone
)
4123 if(m_channels
.empty())
4126 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4130 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4134 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4136 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4140 // skip non built-in channels
4141 if(!(*i
)->IsConstant())
4144 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4148 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4152 char new_channel_name_buf
[100];
4153 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4154 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4156 if((*i
)!=new_channel
)
4158 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4160 // leave old channel
4161 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4162 std::string name
= (*i
)->GetName(); // stroe name, (*i)erase in LeftChannel
4163 LeftChannel(*i
); // remove from player's channel list
4164 cMgr
->LeftChannel(name
); // delete if empty
4167 sLog
.outDebug("Player: channels cleaned up!");
4170 void Player::LeaveLFGChannel()
4172 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4176 (*i
)->Leave(GetGUID());
4182 void Player::UpdateDefense()
4184 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4186 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4188 // update dependent from defense skill part
4189 UpdateDefenseBonusesMod();
4193 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
, bool affectStats
)
4195 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4197 sLog
.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4206 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4209 if(amount
<= -100.0f
)
4212 val
= (100.0f
+ amount
) / 100.0f
;
4213 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4217 if(!CanModifyStats())
4222 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4223 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4224 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4225 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4230 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4232 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4234 sLog
.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4238 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4241 return m_auraBaseMod
[modGroup
][modType
];
4244 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4246 if(modGroup
>= BASEMOD_END
)
4248 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4252 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4255 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4258 uint32
Player::GetShieldBlockValue() const
4260 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4262 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
)/20 - 1;
4264 value
= (value
< 0) ? 0 : value
;
4266 return uint32(value
);
4269 float Player::GetMeleeCritFromAgility()
4271 uint32 level
= getLevel();
4272 uint32 pclass
= getClass();
4274 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4276 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4277 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4278 if (critBase
==NULL
|| critRatio
==NULL
)
4281 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4285 float Player::GetDodgeFromAgility()
4287 // Table for base dodge values
4288 float dodge_base
[MAX_CLASSES
] = {
4290 0.00652f
, // Paladin
4297 0.02011f
, // Warlock
4301 // Crit/agility to dodge/agility coefficient multipliers
4302 float crit_to_dodge
[MAX_CLASSES
] = {
4316 uint32 level
= getLevel();
4317 uint32 pclass
= getClass();
4319 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4321 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4322 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4323 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4326 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4327 return dodge
*100.0f
;
4330 float Player::GetSpellCritFromIntellect()
4332 uint32 level
= getLevel();
4333 uint32 pclass
= getClass();
4335 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4337 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4338 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4339 if (critBase
==NULL
|| critRatio
==NULL
)
4342 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4346 float Player::GetRatingCoefficient(CombatRating cr
) const
4348 uint32 level
= getLevel();
4350 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4352 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4354 return 1.0f
; // By default use minimum coefficient (not must be called)
4356 return Rating
->ratio
;
4359 float Player::GetRatingBonusValue(CombatRating cr
) const
4361 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4364 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4366 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4367 if (melee
>25.0f
) melee
= 25.0f
;
4368 return uint32 (melee
* damage
/100.0f
);
4371 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4373 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4374 if (ranged
>25.0f
) ranged
=25.0f
;
4375 return uint32 (ranged
* damage
/100.0f
);
4378 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4380 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4381 // In wow script resilience limited to 25%
4384 return uint32 (spell
* damage
/ 100.0f
);
4387 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4389 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4390 // Dot resilience not limited (limit it by 100%)
4391 if (spellDot
> 100.0f
)
4393 return uint32 (spellDot
* damage
/ 100.0f
);
4396 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4401 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4403 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4410 float Player::OCTRegenHPPerSpirit()
4412 uint32 level
= getLevel();
4413 uint32 pclass
= getClass();
4415 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4417 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4418 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4419 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4422 // Formula from PaperDollFrame script
4423 float spirit
= GetStat(STAT_SPIRIT
);
4424 float baseSpirit
= spirit
;
4425 if (baseSpirit
>50) baseSpirit
= 50;
4426 float moreSpirit
= spirit
- baseSpirit
;
4427 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4431 float Player::OCTRegenMPPerSpirit()
4433 uint32 level
= getLevel();
4434 uint32 pclass
= getClass();
4436 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4438 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4439 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4440 if (moreRatio
==NULL
)
4443 // Formula get from PaperDollFrame script
4444 float spirit
= GetStat(STAT_SPIRIT
);
4445 float regen
= spirit
* moreRatio
->ratio
;
4449 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4451 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, value
, apply
);
4453 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4454 float RatingChange
= 0.0f
;
4456 bool affectStats
= CanModifyStats();
4460 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4461 case CR_DEFENSE_SKILL
:
4462 UpdateDefenseBonusesMod();
4465 UpdateDodgePercentage();
4468 UpdateParryPercentage();
4471 UpdateBlockPercentage();
4474 RatingChange
= value
/ RatingCoeffecient
;
4475 m_modMeleeHitChance
+= apply
? RatingChange
: -RatingChange
;
4478 RatingChange
= value
/ RatingCoeffecient
;
4479 m_modRangedHitChance
+= apply
? RatingChange
: -RatingChange
;
4482 RatingChange
= value
/ RatingCoeffecient
;
4483 m_modSpellHitChance
+= apply
? RatingChange
: -RatingChange
;
4488 UpdateCritPercentage(BASE_ATTACK
);
4489 UpdateCritPercentage(OFF_ATTACK
);
4492 case CR_CRIT_RANGED
:
4494 UpdateCritPercentage(RANGED_ATTACK
);
4498 UpdateAllSpellCritChances();
4500 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4501 case CR_HIT_TAKEN_RANGED
:
4503 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4505 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4506 case CR_CRIT_TAKEN_RANGED
:
4508 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4510 case CR_HASTE_MELEE
:
4511 RatingChange
= value
/ RatingCoeffecient
;
4512 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4513 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4515 case CR_HASTE_RANGED
:
4516 RatingChange
= value
/ RatingCoeffecient
;
4517 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4519 case CR_HASTE_SPELL
:
4520 RatingChange
= value
/ RatingCoeffecient
;
4521 ApplyCastTimePercentMod(RatingChange
,apply
);
4523 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4524 case CR_WEAPON_SKILL_OFFHAND
:
4525 case CR_WEAPON_SKILL_RANGED
:
4530 UpdateExpertise(BASE_ATTACK
);
4531 UpdateExpertise(OFF_ATTACK
);
4537 void Player::SetRegularAttackTime()
4539 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4541 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4542 if(tmpitem
&& !tmpitem
->IsBroken())
4544 ItemPrototype
const *proto
= tmpitem
->GetProto();
4546 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4548 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4553 //skill+step, checking for max value
4554 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4560 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4561 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4564 if(i
>=PLAYER_MAX_SKILLS
)
4567 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4568 uint32 value
= SKILL_VALUE(data
);
4569 uint32 max
= SKILL_MAX(data
);
4571 if ((!max
) || (!value
) || (value
>= max
))
4574 if (value
*512 < max
*urand(0,512))
4576 uint32 new_value
= value
+step
;
4580 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4587 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4589 if ( SkillValue
>= GrayLevel
)
4590 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4591 if ( SkillValue
>= GreenLevel
)
4592 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4593 if ( SkillValue
>= YellowLevel
)
4594 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4595 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4598 bool Player::UpdateCraftSkill(uint32 spellid
)
4600 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4602 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4603 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4605 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4607 if(_spell_idx
->second
->skillId
)
4609 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4611 // Alchemy Discoveries here
4612 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4613 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4615 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4616 learnSpell(discoveredSpell
);
4619 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4621 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4622 _spell_idx
->second
->max_value
,
4623 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4624 _spell_idx
->second
->min_value
),
4631 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4633 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4635 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4637 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4640 case SKILL_HERBALISM
:
4641 case SKILL_LOCKPICKING
:
4642 case SKILL_JEWELCRAFTING
:
4643 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4644 case SKILL_SKINNING
:
4645 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4646 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4648 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4650 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4651 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4653 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4658 bool Player::UpdateFishingSkill()
4660 sLog
.outDebug("UpdateFishingSkill");
4662 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4664 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4666 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4668 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4671 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4673 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4677 if(Chance
<= 0) // speedup in 0 chance case
4679 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4684 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4685 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4686 if ( i
>= PLAYER_MAX_SKILLS
)
4689 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4690 uint16 SkillValue
= SKILL_VALUE(data
);
4691 uint16 MaxValue
= SKILL_MAX(data
);
4693 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4696 int32 Roll
= irand(1,1000);
4698 if ( Roll
<= Chance
)
4700 uint32 new_value
= SkillValue
+step
;
4701 if(new_value
> MaxValue
)
4702 new_value
= MaxValue
;
4704 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4705 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4709 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4713 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4715 // no skill gain in pvp
4716 Unit
*pVictim
= getVictim();
4717 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4721 return; // always maximized SKILL_FERAL_COMBAT in fact
4723 if(m_form
== FORM_TREE
)
4724 return; // use weapon but not skill up
4726 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4732 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4735 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4736 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4737 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4743 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4745 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4749 UpdateAllCritPercentages();
4752 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, MeleeHitOutcome outcome
, bool defence
)
4756 case MELEE_HIT_CRIT
:
4757 case MELEE_HIT_DODGE
:
4758 case MELEE_HIT_PARRY
:
4759 case MELEE_HIT_BLOCK
:
4760 case MELEE_HIT_BLOCK_CRIT
:
4767 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4768 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4769 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4770 if(moblevel
< greylevel
)
4773 if (moblevel
> plevel
+ 5)
4774 moblevel
= plevel
+ 5;
4776 uint32 lvldif
= moblevel
- greylevel
;
4780 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4784 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4787 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4788 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4791 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4793 if(roll_chance_f(chance
))
4798 UpdateWeaponSkill(attType
);
4804 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4806 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4807 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4809 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4810 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4811 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4813 if(talent
) // permanent bonus stored in high part
4814 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4815 else // temporary/item bonus stored in low part
4816 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
4821 void Player::UpdateMaxSkills()
4823 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
4825 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4826 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4828 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4830 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
4834 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
4837 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4838 uint32 max
= SKILL_MAX(data
);
4839 uint32 val
= SKILL_VALUE(data
);
4841 // update only level dependent max skill values
4842 if(max
!=1 && max
!= maxconfskill
)
4844 uint32 max_Skill
= GetMaxSkillValueForLevel();
4845 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,max_Skill
));
4850 void Player::UpdateSkillsToMaxSkillsForLevel()
4852 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4853 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4855 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4856 if( IsProfessionSkill(pskill
) || pskill
== SKILL_RIDING
)
4858 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4860 uint32 max
= SKILL_MAX(data
);
4863 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
4865 if(pskill
== SKILL_DEFENSE
)
4866 UpdateDefenseBonusesMod();
4870 // This functions sets a skill line value (and adds if doesn't exist yet)
4871 // To "remove" a skill line, set it's values to zero
4872 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
4878 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4879 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
4881 if(i
<PLAYER_MAX_SKILLS
) //has skill
4884 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4887 // clear skill fields
4888 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
4889 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
4890 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4892 // remove spells that depend on this skill when removing the skill
4893 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
4896 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
4899 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(itr
->first
);
4900 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(itr
->first
);
4902 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4904 if (_spell_idx
->second
->skillId
== id
)
4906 // this may remove more than one spell (dependants)
4907 removeSpell(itr
->first
);
4908 next
= m_spells
.begin();
4915 else if(currVal
) //add
4917 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4918 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4920 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
4923 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
4926 // enable unlearn button for primary professions only
4927 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
4928 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
4930 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
4931 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4933 // apply skill bonuses
4934 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4936 // temporary bonuses
4937 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
4938 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
4939 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4940 (*i
)->ApplyModifier(true);
4942 // permanent bonuses
4943 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
4944 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
4945 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4946 (*i
)->ApplyModifier(true);
4948 // Learn all spells for skill
4949 learnSkillRewardedSpells(id
);
4955 bool Player::HasSkill(uint32 skill
) const
4957 if(!skill
)return false;
4958 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4960 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4968 uint16
Player::GetSkillValue(uint32 skill
) const
4973 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4975 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4977 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4979 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
4980 result
+= SKILL_TEMP_BONUS(bonus
);
4981 result
+= SKILL_PERM_BONUS(bonus
);
4982 return result
< 0 ? 0 : result
;
4988 uint16
Player::GetMaxSkillValue(uint32 skill
) const
4991 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4993 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4995 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4997 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
4998 result
+= SKILL_TEMP_BONUS(bonus
);
4999 result
+= SKILL_PERM_BONUS(bonus
);
5000 return result
< 0 ? 0 : result
;
5006 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5009 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5011 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5013 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5019 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5022 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5024 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5026 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5027 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5028 return result
< 0 ? 0 : result
;
5034 uint16
Player::GetPureSkillValue(uint32 skill
) const
5037 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5039 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5041 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5047 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5052 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5054 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5056 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5063 void Player::SendInitialActionButtons()
5065 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5067 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5068 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5070 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5071 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5073 data
<< uint16(itr
->second
.action
);
5074 data
<< uint8(itr
->second
.misc
);
5075 data
<< uint8(itr
->second
.type
);
5083 GetSession()->SendPacket( &data
);
5084 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5087 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5089 if(button
>= MAX_ACTION_BUTTONS
)
5091 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5095 // check cheating with adding non-known spells to action bar
5096 if(type
==ACTION_BUTTON_SPELL
)
5098 if(!sSpellStore
.LookupEntry(action
))
5100 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5104 if(!HasSpell(action
))
5106 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5111 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5113 if (buttonItr
==m_actionButtons
.end())
5114 { // just add new button
5115 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5118 { // change state of current button
5119 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5120 buttonItr
->second
= ActionButton(action
,type
,misc
);
5121 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5124 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5127 void Player::removeActionButton(uint8 button
)
5129 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5130 if (buttonItr
==m_actionButtons
.end())
5133 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5134 m_actionButtons
.erase(buttonItr
); // new and not saved
5136 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5138 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5141 void Player::SetDontMove(bool dontMove
)
5143 m_dontMove
= dontMove
;
5146 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5148 // prevent crash when a bad coord is sent by the client
5149 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5151 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5155 Map
*m
= MapManager::Instance().GetMap(GetMapId(), this);
5157 const float old_x
= GetPositionX();
5158 const float old_y
= GetPositionY();
5159 const float old_z
= GetPositionZ();
5160 const float old_r
= GetOrientation();
5162 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5164 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5165 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5167 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5169 // move and update visible state if need
5170 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5172 // reread after Map::Relocation
5173 m
= MapManager::Instance().GetMap(GetMapId(), this);
5179 // code block for underwater state update
5180 UpdateUnderwaterState(m
, x
, y
, z
);
5182 CheckExploreSystem();
5186 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5191 void Player::SaveRecallPosition()
5193 m_recallMap
= GetMapId();
5194 m_recallX
= GetPositionX();
5195 m_recallY
= GetPositionY();
5196 m_recallZ
= GetPositionZ();
5197 m_recallO
= GetOrientation();
5200 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5202 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data
, self
);
5205 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5207 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data
, dist
, self
);
5210 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5212 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5215 void Player::SendDirectMessage(WorldPacket
*data
)
5217 GetSession()->SendPacket(data
);
5220 void Player::CheckExploreSystem()
5228 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5229 if(areaFlag
==0xffff)
5231 int offset
= areaFlag
/ 32;
5235 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 < 64 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5239 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5240 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5242 if( !(currFields
& val
) )
5244 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5246 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5249 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5251 else if(p
->area_level
> 0)
5253 uint32 area
= p
->ID
;
5254 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5256 SendExplorationExperience(area
,0);
5260 int32 diff
= int32(getLevel()) - p
->area_level
;
5264 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5268 int32 exploration_percent
= (100-((diff
-5)*5));
5269 if (exploration_percent
> 100)
5270 exploration_percent
= 100;
5271 else if (exploration_percent
< 0)
5272 exploration_percent
= 0;
5274 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5278 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5282 SendExplorationExperience(area
,XP
);
5284 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5289 uint32
Player::TeamForRace(uint8 race
)
5291 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5294 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5298 switch(rEntry
->TeamID
)
5300 case 7: return ALLIANCE
;
5301 case 1: return HORDE
;
5304 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5308 uint32
Player::getFactionForRace(uint8 race
)
5310 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5313 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5317 return rEntry
->FactionID
;
5320 void Player::setFactionForRace(uint8 race
)
5322 m_team
= TeamForRace(race
);
5323 setFaction( getFactionForRace(race
) );
5326 void Player::UpdateReputation() const
5328 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5330 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5332 SendFactionState(&(itr
->second
));
5336 void Player::SendFactionState(FactionState
const* faction
) const
5338 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5340 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5341 data
<< (float) 0; // unk 2.4.0
5342 data
<< (uint8
) 0; // wotlk 8634
5343 data
<< (uint32
) 1; // count
5345 data
<< (uint32
) faction
->ReputationListID
;
5346 data
<< (uint32
) faction
->Standing
;
5348 GetSession()->SendPacket(&data
);
5352 void Player::SendInitialReputations()
5354 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5355 data
<< uint32 (0x00000080);
5359 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); itr
++)
5361 // fill in absent fields
5362 for (; a
!= itr
->first
; a
++)
5364 data
<< uint8 (0x00);
5365 data
<< uint32 (0x00000000);
5368 // fill in encountered data
5369 data
<< uint8 (itr
->second
.Flags
);
5370 data
<< uint32 (itr
->second
.Standing
);
5375 // fill in absent fields
5376 for (; a
!= 128; a
++)
5378 data
<< uint8 (0x00);
5379 data
<< uint32 (0x00000000);
5382 GetSession()->SendPacket(&data
);
5385 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5387 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5388 if (itr
!= m_factions
.end())
5389 return &itr
->second
;
5394 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5396 // not allow declare war to own faction
5397 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5401 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5405 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5407 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5409 faction
->Changed
= true;
5412 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5414 // always invisible or hidden faction can't be inactive
5415 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5419 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5423 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5425 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5427 faction
->Changed
= true;
5430 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5432 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5434 if(!factionTemplateEntry
)
5437 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5440 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5442 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5446 if(factionEntry
->reputationListID
< 0)
5449 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5450 if (itr
== m_factions
.end())
5453 SetFactionVisible(&itr
->second
);
5456 void Player::SetFactionVisible(FactionState
* faction
)
5458 // always invisible or hidden faction can't be make visible
5459 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5463 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5466 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5467 faction
->Changed
= true;
5469 if(!m_session
->PlayerLoading())
5471 // make faction visible in reputation list at client
5472 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5473 data
<< faction
->ReputationListID
;
5474 GetSession()->SendPacket(&data
);
5478 void Player::SetInitialFactions()
5480 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5482 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5484 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5486 FactionState newFaction
;
5487 newFaction
.ID
= factionEntry
->ID
;
5488 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5489 newFaction
.Standing
= 0;
5490 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5491 newFaction
.Changed
= true;
5493 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5498 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5503 uint32 raceMask
= getRaceMask();
5504 uint32 classMask
= getClassMask();
5505 for (int i
=0; i
< 4; i
++)
5507 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5508 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5509 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5510 return factionEntry
->ReputationFlags
[i
];
5515 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5520 uint32 raceMask
= getRaceMask();
5521 uint32 classMask
= getClassMask();
5522 for (int i
=0; i
< 4; i
++)
5524 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5525 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5526 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5527 return factionEntry
->BaseRepValue
[i
];
5530 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5534 int32
Player::GetReputation(uint32 faction_id
) const
5536 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5540 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5544 return GetReputation(factionEntry
);
5547 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5549 // Faction without recorded reputation. Just ignore.
5553 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5554 if (itr
!= m_factions
.end())
5555 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5560 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5562 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5564 return MIN_REPUTATION_RANK
;
5566 return GetReputationRank(factionEntry
);
5569 ReputationRank
Player::ReputationToRank(int32 standing
) const
5571 int32 Limit
= Reputation_Cap
+ 1;
5572 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5574 Limit
-= ReputationRank_Length
[i
];
5575 if (standing
>= Limit
)
5576 return ReputationRank(i
);
5578 return MIN_REPUTATION_RANK
;
5581 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5583 int32 Reputation
= GetReputation(factionEntry
);
5584 return ReputationToRank(Reputation
);
5587 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5589 int32 Reputation
= GetBaseReputation(factionEntry
);
5590 return ReputationToRank(Reputation
);
5593 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5595 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5597 if(!factionTemplateEntry
)
5599 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5603 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5605 // Faction without recorded reputation. Just ignore.
5609 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5612 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5614 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5618 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5620 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5621 if(factionEntryCalc
)
5622 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5627 return ModifyOneFactionReputation(factionEntry
, standing
);
5630 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5632 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5633 if (itr
!= m_factions
.end())
5635 int32 BaseRep
= GetBaseReputation(factionEntry
);
5636 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5638 if (new_rep
> Reputation_Cap
)
5639 new_rep
= Reputation_Cap
;
5641 if (new_rep
< Reputation_Bottom
)
5642 new_rep
= Reputation_Bottom
;
5644 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5645 SetFactionAtWar(&itr
->second
,true);
5647 itr
->second
.Standing
= new_rep
- BaseRep
;
5648 itr
->second
.Changed
= true;
5650 SetFactionVisible(&itr
->second
);
5652 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5654 if(uint32 questid
= GetQuestSlotQuestId(i
))
5656 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5657 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5659 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5660 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5662 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5663 if ( CanCompleteQuest( questid
) )
5664 CompleteQuest( questid
);
5666 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5668 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5669 IncompleteQuest( questid
);
5675 SendFactionState(&(itr
->second
));
5682 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5684 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5686 if(!factionTemplateEntry
)
5688 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5692 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5694 // Faction without recorded reputation. Just ignore.
5698 return SetFactionReputation(factionEntry
, standing
);
5701 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5703 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5707 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5709 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5710 if(factionEntryCalc
)
5711 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5716 return SetOneFactionReputation(factionEntry
, standing
);
5719 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5721 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5722 if (itr
!= m_factions
.end())
5724 if (standing
> Reputation_Cap
)
5725 standing
= Reputation_Cap
;
5727 if (standing
< Reputation_Bottom
)
5728 standing
= Reputation_Bottom
;
5730 int32 BaseRep
= GetBaseReputation(factionEntry
);
5731 itr
->second
.Standing
= standing
- BaseRep
;
5732 itr
->second
.Changed
= true;
5734 SetFactionVisible(&itr
->second
);
5736 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5737 SetFactionAtWar(&itr
->second
,true);
5739 SendFactionState(&(itr
->second
));
5745 //Calculate total reputation percent player gain with quest/creature level
5746 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5748 // for grey creature kill received 20%, in other case 100.
5749 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5751 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5753 percent
+= rep
> 0 ? repMod
: -repMod
;
5758 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5761 //Calculates how many reputation points player gains in victim's enemy factions
5762 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5764 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5767 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5772 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5774 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5775 donerep1
= int32(donerep1
*rate
);
5776 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5777 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5778 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5779 ModifyFactionReputation(factionEntry1
, donerep1
);
5781 // Wiki: Team factions value divided by 2
5782 if(Rep
->is_teamaward1
)
5784 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5785 if(team1_factionEntry
)
5786 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5790 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5792 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5793 donerep2
= int32(donerep2
*rate
);
5794 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5795 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5796 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5797 ModifyFactionReputation(factionEntry2
, donerep2
);
5799 // Wiki: Team factions value divided by 2
5800 if(Rep
->is_teamaward2
)
5802 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5803 if(team2_factionEntry
)
5804 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
5809 //Calculate how many reputation points player gain with the quest
5810 void Player::RewardReputation(Quest
const *pQuest
)
5812 // quest reputation reward/loss
5813 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5815 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5817 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
5818 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5820 ModifyFactionReputation(factionEntry
, rep
);
5824 // TODO: implement reputation spillover
5827 void Player::UpdateArenaFields(void)
5829 /* arena calcs go here */
5832 void Player::UpdateHonorFields()
5834 /// called when rewarding honor and at each save
5835 uint64 now
= time(NULL
);
5836 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5838 if(m_lastHonorUpdateTime
< today
)
5840 uint64 yesterday
= today
- DAY
;
5842 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5844 // update yesterday's contribution
5845 if(m_lastHonorUpdateTime
>= yesterday
)
5847 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5849 // this is the first update today, reset today's contribution
5850 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5851 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5855 // no honor/kills yesterday or today, reset
5856 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5857 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5861 m_lastHonorUpdateTime
= now
;
5864 ///Calculate the amount of honor gained based on the victim
5865 ///and the size of the group for which the honor is divided
5866 ///An exact honor value can also be given (overriding the calcs)
5867 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5869 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5870 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5873 uint64 victim_guid
= 0;
5874 uint32 victim_rank
= 0;
5875 time_t now
= time(NULL
);
5877 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5878 UpdateHonorFields();
5882 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5885 victim_guid
= uVictim
->GetGUID();
5887 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5889 Player
*pVictim
= (Player
*)uVictim
;
5891 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5894 float f
= 1; //need for total kills (?? need more info)
5896 uint32 k_level
= getLevel();
5897 uint32 v_level
= pVictim
->getLevel();
5900 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5902 // [1..14] Alliance honor titles and player name
5903 // [15..28] Horde honor titles and player name
5904 // [29..38] Other title and player name
5906 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5907 // Get Killer titles, CharTitlesEntry::bit_index
5909 // title[1..14] -> rank[5..18]
5910 // title[15..28] -> rank[5..18]
5911 // title[other] -> 0
5912 if (victim_title
== 0)
5913 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5914 else if (victim_title
< 15)
5915 victim_rank
= victim_title
+ 4;
5916 else if (victim_title
< 29)
5917 victim_rank
= victim_title
- 14 + 4;
5919 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5924 else if( k_level
<= 39 )
5925 k_grey
= k_level
- 5 - k_level
/10;
5927 k_grey
= k_level
- 1 - k_level
/5;
5932 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5934 int32 v_rank
=1; //need more info
5936 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5937 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5939 // count the number of playerkills in one day
5940 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5941 // and those in a lifetime
5942 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5946 Creature
*cVictim
= (Creature
*)uVictim
;
5948 if (!cVictim
->isRacialLeader())
5951 honor
= 100; // ??? need more info
5952 victim_rank
= 19; // HK: Leader
5956 if (uVictim
!= NULL
)
5958 honor
*= sWorld
.getRate(RATE_HONOR
);
5963 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5966 // honor - for show honor points in log
5967 // victim_guid - for show victim name in log
5968 // victim_rank [1..4] HK: <dishonored rank>
5969 // victim_rank [5..19] HK: <alliance\horde rank>
5970 // victim_rank [0,20+] HK: <>
5971 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5972 data
<< (uint32
) honor
;
5973 data
<< (uint64
) victim_guid
;
5974 data
<< (uint32
) victim_rank
;
5976 GetSession()->SendPacket(&data
);
5979 ModifyHonorPoints(int32(honor
));
5981 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5985 void Player::ModifyHonorPoints( int32 value
)
5989 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5990 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5992 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5995 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5998 void Player::ModifyArenaPoints( int32 value
)
6002 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6003 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6005 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6008 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6011 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6013 std::ostringstream ss
;
6014 ss
<<"SELECT guildid FROM guild_member WHERE guid='"<<guid
<<"'";
6015 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6018 uint32 v
= result
->Fetch()[0].GetUInt32();
6026 uint32
Player::GetRankFromDB(uint64 guid
)
6028 std::ostringstream ss
;
6029 ss
<<"SELECT rank FROM guild_member WHERE guid='"<<guid
<<"'";
6030 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6033 uint32 v
= result
->Fetch()[0].GetUInt32();
6041 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6044 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid
));
6047 // init id to 0, check the arena type before assigning a value to id
6051 QueryResult
*result2
= CharacterDatabase
.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id
);
6054 uint8 dbtype
= (*result2
)[0].GetUInt32();
6058 // if the type matches, we've found the id
6059 id
= (*result
)[0].GetUInt32();
6063 } while(result
->NextRow());
6067 // no arenateam for the specified guid, return 0
6071 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6073 std::ostringstream ss
;
6075 ss
<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6076 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6079 Field
* fields
= result
->Fetch();
6080 uint32 zone
= fields
[0].GetUInt32();
6085 // stored zone is zero, use generic and slow zone detection
6087 ss
<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6088 result
= CharacterDatabase
.Query(ss
.str().c_str());
6091 fields
= result
->Fetch();
6092 uint32 map
= fields
[0].GetUInt32();
6093 float posx
= fields
[1].GetFloat();
6094 float posy
= fields
[2].GetFloat();
6097 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
);
6100 ss
<< "UPDATE characters SET zone='"<<zone
<<"' WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6101 CharacterDatabase
.Execute(ss
.str().c_str());
6107 void Player::UpdateArea(uint32 newArea
)
6109 // FFA_PVP flags are area and not zone id dependent
6110 // so apply them accordingly
6111 m_areaUpdateId
= newArea
;
6113 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6115 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6118 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6122 // remove ffa flag only if not ffapvp realm
6123 // removal in sanctuaries and capitals is handled in zone update
6124 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6125 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6128 UpdateAreaDependentAuras(newArea
);
6131 void Player::UpdateZone(uint32 newZone
)
6133 m_zoneUpdateId
= newZone
;
6134 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6136 // zone changed, so area changed as well, update it
6137 UpdateArea(GetAreaId());
6139 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6143 if (sWorld
.getConfig(CONFIG_WEATHER
))
6145 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6148 wth
->SendWeatherUpdateToPlayer(this);
6152 if(!sWorld
.AddWeather(zone
->ID
))
6154 // send fine weather packet to remove old zone's weather
6155 Weather::SendFineWeatherUpdateToPlayer(this);
6160 pvpInfo
.inHostileArea
=
6161 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6162 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6163 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6164 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6166 if(pvpInfo
.inHostileArea
) // in hostile area
6168 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6169 UpdatePvP(true, true);
6171 else // in friendly area
6173 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6174 pvpInfo
.endTimer
= time(0); // start toggle-off
6177 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6179 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6180 if(sWorld
.IsFFAPvPRealm())
6181 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6185 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6188 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6190 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6191 SetRestType(REST_TYPE_IN_CITY
);
6192 InnEnter(time(0),GetMapId(),0,0,0);
6194 if(sWorld
.IsFFAPvPRealm())
6195 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6197 else // anywhere else
6199 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6201 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6203 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6205 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6206 SetRestType(REST_TYPE_NO
);
6208 if(sWorld
.IsFFAPvPRealm())
6209 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6212 else // not in tavern (leave city then)
6214 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6215 SetRestType(REST_TYPE_NO
);
6217 // Set player to FFA PVP when not in rested enviroment.
6218 if(sWorld
.IsFFAPvPRealm())
6219 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6224 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6225 // if player resurrected at teleport this will be applied in resurrect code
6227 DestroyZoneLimitedItem( true, newZone
);
6229 // recent client version not send leave/join channel packets for built-in local channels
6230 UpdateLocalChannels( newZone
);
6234 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6236 UpdateZoneDependentAuras(newZone
);
6239 //If players are too far way of duel flag... then player loose the duel
6240 void Player::CheckDuelDistance(time_t currTime
)
6245 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6246 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6250 if(duel
->outOfBound
== 0)
6252 if(!IsWithinDistInMap(obj
, 50))
6254 duel
->outOfBound
= currTime
;
6256 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6257 GetSession()->SendPacket(&data
);
6262 if(IsWithinDistInMap(obj
, 40))
6264 duel
->outOfBound
= 0;
6266 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6267 GetSession()->SendPacket(&data
);
6269 else if(currTime
>= (duel
->outOfBound
+10))
6271 DuelComplete(DUEL_FLED
);
6276 void Player::DuelComplete(DuelCompleteType type
)
6278 // duel not requested
6282 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6283 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6284 GetSession()->SendPacket(&data
);
6285 duel
->opponent
->GetSession()->SendPacket(&data
);
6287 if(type
!= DUEL_INTERUPTED
)
6289 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6290 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6291 data
<< duel
->opponent
->GetName();
6293 SendMessageToSet(&data
,true);
6296 // cool-down duel spell
6297 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6304 GetSession()->SendPacket(&data);
6305 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6306 data<<duel->opponent->GetGUID();
6310 duel->opponent->GetSession()->SendPacket(&data);*/
6312 //Remove Duel Flag object
6313 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6315 duel
->initiator
->RemoveGameObject(obj
,true);
6318 std::vector
<uint32
> auras2remove
;
6319 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6320 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); i
++)
6322 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6323 auras2remove
.push_back(i
->second
->GetId());
6326 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6327 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6329 auras2remove
.clear();
6330 AuraMap
const& auras
= GetAuras();
6331 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); i
++)
6333 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6334 auras2remove
.push_back(i
->second
->GetId());
6336 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6337 RemoveAurasDueToSpell(auras2remove
[i
]);
6339 // cleanup combo points
6340 if(GetComboTarget()==duel
->opponent
->GetGUID())
6342 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6345 if(duel
->opponent
->GetComboTarget()==GetGUID())
6346 duel
->opponent
->ClearComboPoints();
6347 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6348 duel
->opponent
->ClearComboPoints();
6351 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6352 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6353 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6354 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6356 delete duel
->opponent
->duel
;
6357 duel
->opponent
->duel
= NULL
;
6362 //---------------------------------------------------------//
6364 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6366 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6369 // not apply/remove mods for broken item
6370 if(item
->IsBroken())
6373 ItemPrototype
const *proto
= item
->GetProto();
6378 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6380 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6381 if(attacktype
< MAX_ATTACK
)
6382 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6384 _ApplyItemBonuses(proto
,slot
,apply
);
6386 if( slot
==EQUIPMENT_SLOT_RANGED
)
6387 _ApplyAmmoBonuses();
6389 ApplyItemEquipSpell(item
,apply
);
6390 ApplyEnchantment(item
, apply
);
6392 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6393 CorrectMetaGemEnchants(slot
, apply
);
6395 sLog
.outDebug("_ApplyItemMods complete.");
6398 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6400 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6403 for (int i
= 0; i
< 10; i
++)
6405 uint32 statType
= 0;
6408 if(proto
->ScalingStatDistribution
)
6410 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6412 statType
= ssd
->StatMod
[i
];
6414 if(uint32 modifier
= ssd
->Modifier
[i
])
6416 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6417 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6419 int multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6420 val
= (multiplier
* modifier
) / 10000;
6427 statType
= proto
->ItemStat
[i
].ItemStatType
;
6428 val
= float(proto
->ItemStat
[i
].ItemStatValue
);
6437 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6439 case ITEM_MOD_HEALTH
: // modify HP
6440 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6442 case ITEM_MOD_AGILITY
: // modify agility
6443 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6444 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6446 case ITEM_MOD_STRENGTH
: //modify strength
6447 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6448 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6450 case ITEM_MOD_INTELLECT
: //modify intellect
6451 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6452 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6454 case ITEM_MOD_SPIRIT
: //modify spirit
6455 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6456 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6458 case ITEM_MOD_STAMINA
: //modify stamina
6459 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6460 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6462 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6463 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6465 case ITEM_MOD_DODGE_RATING
:
6466 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6468 case ITEM_MOD_PARRY_RATING
:
6469 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6471 case ITEM_MOD_BLOCK_RATING
:
6472 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6474 case ITEM_MOD_HIT_MELEE_RATING
:
6475 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6477 case ITEM_MOD_HIT_RANGED_RATING
:
6478 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6480 case ITEM_MOD_HIT_SPELL_RATING
:
6481 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6483 case ITEM_MOD_CRIT_MELEE_RATING
:
6484 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6486 case ITEM_MOD_CRIT_RANGED_RATING
:
6487 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6489 case ITEM_MOD_CRIT_SPELL_RATING
:
6490 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6492 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6493 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6495 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6496 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6498 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6499 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6501 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6502 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6504 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6505 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6507 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6508 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6510 case ITEM_MOD_HASTE_MELEE_RATING
:
6511 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6513 case ITEM_MOD_HASTE_RANGED_RATING
:
6514 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6516 case ITEM_MOD_HASTE_SPELL_RATING
:
6517 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6519 case ITEM_MOD_HIT_RATING
:
6520 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6521 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6522 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6524 case ITEM_MOD_CRIT_RATING
:
6525 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6526 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6527 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6529 case ITEM_MOD_HIT_TAKEN_RATING
:
6530 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6531 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6532 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6534 case ITEM_MOD_CRIT_TAKEN_RATING
:
6535 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6536 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6537 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6539 case ITEM_MOD_RESILIENCE_RATING
:
6540 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6541 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6542 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6544 case ITEM_MOD_HASTE_RATING
:
6545 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6546 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6547 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6549 case ITEM_MOD_EXPERTISE_RATING
:
6550 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6552 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6553 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6559 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6562 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6565 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6568 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6570 if (proto
->NatureRes
)
6571 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6573 if (proto
->FrostRes
)
6574 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6576 if (proto
->ShadowRes
)
6577 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6579 if (proto
->ArcaneRes
)
6580 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6582 WeaponAttackType attType
= BASE_ATTACK
;
6583 float damage
= 0.0f
;
6585 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6586 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6587 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6589 attType
= RANGED_ATTACK
;
6591 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6593 attType
= OFF_ATTACK
;
6596 if (proto
->Damage
[0].DamageMin
> 0 )
6598 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6599 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6600 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6603 if (proto
->Damage
[0].DamageMax
> 0 )
6605 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6606 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6609 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6614 if(slot
== EQUIPMENT_SLOT_RANGED
)
6615 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6616 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6617 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6618 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6619 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6622 if(CanModifyStats() && (damage
|| proto
->Delay
))
6623 UpdateDamagePhysical(attType
);
6626 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6628 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6629 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6630 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6632 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6633 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6634 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6636 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6637 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6638 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6641 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6643 // generic not weapon specific case processes in aura code
6644 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6647 BaseModGroup mod
= BASEMOD_END
;
6650 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6651 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6652 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6656 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6658 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6662 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6664 // ignore spell mods for not wands
6665 Modifier
const* modifier
= aura
->GetModifier();
6666 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6669 // generic not weapon specific case processes in aura code
6670 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6673 UnitMods unitMod
= UNIT_MOD_END
;
6676 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6677 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6678 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6682 UnitModifierType unitModType
= TOTAL_VALUE
;
6683 switch(modifier
->m_auraname
)
6685 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6686 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6690 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6692 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6696 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6701 ItemPrototype
const *proto
= item
->GetProto();
6705 for (int i
= 0; i
< 5; i
++)
6707 _Spell
const& spellData
= proto
->Spells
[i
];
6710 if(!spellData
.SpellId
)
6713 // wrong triggering type
6714 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6717 // check if it is valid spell
6718 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6722 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6726 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6730 // Cannot be used in this stance/form
6731 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6734 if(form_change
) // check aura active state from other form
6737 for (int k
=0; k
< 3; ++k
)
6739 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6740 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6742 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6752 if(found
) // and skip re-cast already active aura at form change
6756 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6758 CastSpell(this,spellInfo
,true,item
);
6762 if(form_change
) // check aura compatibility
6764 // Cannot be used in this stance/form
6765 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6766 return; // and remove only not compatible at form change
6770 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6772 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6776 void Player::UpdateEquipSpellsAtFormChange()
6778 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6780 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6782 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6783 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6787 // item set bonuses not dependent from item broken state
6788 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6790 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6794 for(uint32 y
=0;y
<8; ++y
)
6796 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6800 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6801 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6806 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6808 if(!item
|| item
->IsBroken())
6811 ItemPrototype
const *proto
= item
->GetProto();
6815 if (!Target
|| Target
== this )
6818 for (int i
= 0; i
< 5; i
++)
6820 _Spell
const& spellData
= proto
->Spells
[i
];
6823 if(!spellData
.SpellId
)
6826 // wrong triggering type
6827 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6830 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6833 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6837 // not allow proc extra attack spell at extra attack
6838 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6841 float chance
= spellInfo
->procChance
;
6843 if(spellData
.SpellPPMRate
)
6845 uint32 WeaponSpeed
= GetAttackTime(attType
);
6846 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6848 else if(chance
> 100.0f
)
6850 chance
= GetWeaponProcChance();
6853 if (roll_chance_f(chance
))
6854 this->CastSpell(Target
, spellInfo
->Id
, true, item
);
6857 // item combat enchantments
6858 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6860 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6861 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6862 if(!pEnchant
) continue;
6863 for (int s
=0;s
<3;s
++)
6865 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6868 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6871 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6875 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6876 if (roll_chance_f(chance
))
6878 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6879 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6881 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6887 void Player::_RemoveAllItemMods()
6889 sLog
.outDebug("_RemoveAllItemMods start.");
6891 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6895 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6899 // item set bonuses not dependent from item broken state
6901 RemoveItemsSetItem(this,proto
);
6903 if(m_items
[i
]->IsBroken())
6906 ApplyItemEquipSpell(m_items
[i
],false);
6907 ApplyEnchantment(m_items
[i
], false);
6911 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6915 if(m_items
[i
]->IsBroken())
6917 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6921 uint32 attacktype
= Player::GetAttackBySlot(i
);
6922 if(attacktype
< MAX_ATTACK
)
6923 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6925 _ApplyItemBonuses(proto
,i
, false);
6927 if( i
== EQUIPMENT_SLOT_RANGED
)
6928 _ApplyAmmoBonuses();
6932 sLog
.outDebug("_RemoveAllItemMods complete.");
6935 void Player::_ApplyAllItemMods()
6937 sLog
.outDebug("_ApplyAllItemMods start.");
6939 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6943 if(m_items
[i
]->IsBroken())
6946 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6950 uint32 attacktype
= Player::GetAttackBySlot(i
);
6951 if(attacktype
< MAX_ATTACK
)
6952 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6954 _ApplyItemBonuses(proto
,i
, true);
6956 if( i
== EQUIPMENT_SLOT_RANGED
)
6957 _ApplyAmmoBonuses();
6961 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6965 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6969 // item set bonuses not dependent from item broken state
6971 AddItemsSetItem(this,m_items
[i
]);
6973 if(m_items
[i
]->IsBroken())
6976 ApplyItemEquipSpell(m_items
[i
],true);
6977 ApplyEnchantment(m_items
[i
], true);
6981 sLog
.outDebug("_ApplyAllItemMods complete.");
6984 void Player::_ApplyAmmoBonuses()
6987 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
6991 float currentAmmoDPS
;
6993 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
6994 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
6995 currentAmmoDPS
= 0.0f
;
6997 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
6999 if(currentAmmoDPS
== GetAmmoDPS())
7002 m_ammoDPS
= currentAmmoDPS
;
7004 if(CanModifyStats())
7005 UpdateDamagePhysical(RANGED_ATTACK
);
7008 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7013 // check ranged weapon
7014 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7015 if(!weapon
|| weapon
->IsBroken() )
7018 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7019 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7022 // check ammo ws. weapon compatibility
7023 switch(weapon_proto
->SubClass
)
7025 case ITEM_SUBCLASS_WEAPON_BOW
:
7026 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7027 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7030 case ITEM_SUBCLASS_WEAPON_GUN
:
7031 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7041 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7042 Called by remove insignia spell effect */
7043 void Player::RemovedInsignia(Player
* looterPlr
)
7045 if (!GetBattleGroundId())
7048 // If not released spirit, do it !
7049 if(m_deathTimer
> 0)
7056 Corpse
*corpse
= GetCorpse();
7060 // We have to convert player corpse to bones, not to be able to resurrect there
7061 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7062 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7066 // Now we must make bones lootable, and send player loot
7067 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7069 // We store the level of our player in the gold field
7070 // We retrieve this information at Player::SendLoot()
7071 bones
->loot
.gold
= getLevel();
7072 bones
->lootRecipient
= looterPlr
;
7073 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7082 void Player::SendLootRelease( uint64 guid
)
7084 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7085 data
<< uint64(guid
) << uint8(1);
7086 SendDirectMessage( &data
);
7089 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7092 PermissionTypes permission
= ALL_PERMISSION
;
7094 sLog
.outDebug("Player::SendLoot");
7095 if (IS_GAMEOBJECT_GUID(guid
))
7097 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7099 ObjectAccessor::GetGameObject(*this, guid
);
7101 // not check distance for GO in case owned GO (fishing bobber case, for example)
7102 // And permit out of range GO with no owner in case fishing hole
7103 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7105 SendLootRelease(guid
);
7111 if(go
->getLootState() == GO_READY
)
7113 uint32 lootid
= go
->GetLootId();
7117 sLog
.outDebug(" if(lootid)");
7119 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7122 if(loot_type
== LOOT_FISHING
)
7123 go
->getFishLoot(loot
);
7125 go
->SetLootState(GO_ACTIVATED
);
7128 else if (IS_ITEM_GUID(guid
))
7130 Item
*item
= GetItemByGuid( guid
);
7134 SendLootRelease(guid
);
7138 if(loot_type
== LOOT_DISENCHANTING
)
7142 if(!item
->m_lootGenerated
)
7144 item
->m_lootGenerated
= true;
7146 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7149 else if(loot_type
== LOOT_PROSPECTING
)
7153 if(!item
->m_lootGenerated
)
7155 item
->m_lootGenerated
= true;
7157 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7164 if(!item
->m_lootGenerated
)
7166 item
->m_lootGenerated
= true;
7168 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7170 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7174 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7176 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7178 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7180 SendLootRelease(guid
);
7184 loot
= &bones
->loot
;
7186 if (!bones
->lootForBody
)
7188 bones
->lootForBody
= true;
7189 uint32 pLevel
= bones
->loot
.gold
;
7190 bones
->loot
.clear();
7191 // It may need a better formula
7192 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7193 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7196 if (bones
->lootRecipient
!= this)
7197 permission
= NONE_PERMISSION
;
7201 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7203 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7204 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7206 SendLootRelease(guid
);
7210 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7212 SendLootRelease(guid
);
7216 loot
= &creature
->loot
;
7218 if(loot_type
== LOOT_PICKPOCKETING
)
7220 if ( !creature
->lootForPickPocketed
)
7222 creature
->lootForPickPocketed
= true;
7225 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7226 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7228 // Generate extra money for pick pocket loot
7229 const uint32 a
= urand(0, creature
->getLevel()/2);
7230 const uint32 b
= urand(0, getLevel()/2);
7231 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7236 // the player whose group may loot the corpse
7237 Player
*recipient
= creature
->GetLootRecipient();
7240 creature
->SetLootRecipient(this);
7244 if (creature
->lootForPickPocketed
)
7246 creature
->lootForPickPocketed
= false;
7250 if(!creature
->lootForBody
)
7252 creature
->lootForBody
= true;
7255 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7256 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7258 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7260 if(Group
* group
= recipient
->GetGroup())
7262 group
->UpdateLooterGuid(creature
,true);
7264 switch (group
->GetLootMethod())
7267 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7268 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7270 case NEED_BEFORE_GREED
:
7271 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7274 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7282 // possible only if creature->lootForBody && loot->empty() at spell cast check
7283 if (loot_type
== LOOT_SKINNING
)
7286 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7288 // set group rights only for loot_type != LOOT_SKINNING
7291 if(Group
* group
= GetGroup())
7293 if( group
== recipient
->GetGroup() )
7295 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7296 permission
= ALL_PERMISSION
;
7297 else if(group
->GetLooterGuid() == GetGUID())
7299 if(group
->GetLootMethod() == MASTER_LOOT
)
7300 permission
= MASTER_PERMISSION
;
7302 permission
= ALL_PERMISSION
;
7305 permission
= GROUP_PERMISSION
;
7308 permission
= NONE_PERMISSION
;
7310 else if(recipient
== this)
7311 permission
= ALL_PERMISSION
;
7313 permission
= NONE_PERMISSION
;
7320 QuestItemList
*q_list
= 0;
7321 if (permission
!= NONE_PERMISSION
)
7323 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7324 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7325 if (itr
== lootPlayerQuestItems
.end())
7326 q_list
= loot
->FillQuestLoot(this);
7328 q_list
= itr
->second
;
7331 QuestItemList
*ffa_list
= 0;
7332 if (permission
!= NONE_PERMISSION
)
7334 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7335 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7336 if (itr
== lootPlayerFFAItems
.end())
7337 ffa_list
= loot
->FillFFALoot(this);
7339 ffa_list
= itr
->second
;
7342 QuestItemList
*conditional_list
= 0;
7343 if (permission
!= NONE_PERMISSION
)
7345 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7346 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7347 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7348 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7350 conditional_list
= itr
->second
;
7353 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7354 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
)
7355 loot_type
= LOOT_SKINNING
;
7357 if(loot_type
== LOOT_FISHINGHOLE
)
7358 loot_type
= LOOT_FISHING
;
7360 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7362 data
<< uint64(guid
);
7363 data
<< uint8(loot_type
);
7364 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7366 SendDirectMessage(&data
);
7368 // add 'this' player as one of the players that are looting 'loot'
7369 if (permission
!= NONE_PERMISSION
)
7370 loot
->AddLooter(GetGUID());
7372 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7373 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7376 void Player::SendNotifyLootMoneyRemoved()
7378 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7379 GetSession()->SendPacket( &data
);
7382 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7384 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7385 data
<< uint8(lootSlot
);
7386 GetSession()->SendPacket( &data
);
7389 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7391 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7394 GetSession()->SendPacket(&data
);
7397 void Player::SendInitWorldStates()
7399 // data depends on zoneid/mapid...
7400 BattleGround
* bg
= GetBattleGround();
7401 uint16 NumberOfFields
= 0;
7402 uint32 mapid
= GetMapId();
7403 uint32 zoneid
= GetZoneId();
7404 uint32 areaid
= GetAreaId();
7405 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7406 // may be exist better way to do this...
7429 NumberOfFields
= 81;
7432 NumberOfFields
= 14;
7436 NumberOfFields
= 38;
7439 NumberOfFields
= 22;
7442 NumberOfFields
= 36;
7445 NumberOfFields
= 35;
7456 NumberOfFields
= 10;
7460 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7461 data
<< uint32(mapid
); // mapid
7462 data
<< uint32(zoneid
); // zone id
7463 data
<< uint32(areaid
); // area id, new 2.1.0
7464 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7465 data
<< uint32(0x8d8) << uint32(0x0); // 1
7466 data
<< uint32(0x8d7) << uint32(0x0); // 2
7467 data
<< uint32(0x8d6) << uint32(0x0); // 3
7468 data
<< uint32(0x8d5) << uint32(0x0); // 4
7469 data
<< uint32(0x8d4) << uint32(0x0); // 5
7470 data
<< uint32(0x8d3) << uint32(0x0); // 6
7471 if(mapid
== 530) // Outland
7473 data
<< uint32(0x9bf) << uint32(0x0); // 7
7474 data
<< uint32(0x9bd) << uint32(0xF); // 8
7475 data
<< uint32(0x9bb) << uint32(0xF); // 9
7490 data
<< uint32(0x7ae) << uint32(0x1); // 7
7491 data
<< uint32(0x532) << uint32(0x1); // 8
7492 data
<< uint32(0x531) << uint32(0x0); // 9
7493 data
<< uint32(0x52e) << uint32(0x0); // 10
7494 data
<< uint32(0x571) << uint32(0x0); // 11
7495 data
<< uint32(0x570) << uint32(0x0); // 12
7496 data
<< uint32(0x567) << uint32(0x1); // 13
7497 data
<< uint32(0x566) << uint32(0x1); // 14
7498 data
<< uint32(0x550) << uint32(0x1); // 15
7499 data
<< uint32(0x544) << uint32(0x0); // 16
7500 data
<< uint32(0x536) << uint32(0x0); // 17
7501 data
<< uint32(0x535) << uint32(0x1); // 18
7502 data
<< uint32(0x518) << uint32(0x0); // 19
7503 data
<< uint32(0x517) << uint32(0x0); // 20
7504 data
<< uint32(0x574) << uint32(0x0); // 21
7505 data
<< uint32(0x573) << uint32(0x0); // 22
7506 data
<< uint32(0x572) << uint32(0x0); // 23
7507 data
<< uint32(0x56f) << uint32(0x0); // 24
7508 data
<< uint32(0x56e) << uint32(0x0); // 25
7509 data
<< uint32(0x56d) << uint32(0x0); // 26
7510 data
<< uint32(0x56c) << uint32(0x0); // 27
7511 data
<< uint32(0x56b) << uint32(0x0); // 28
7512 data
<< uint32(0x56a) << uint32(0x1); // 29
7513 data
<< uint32(0x569) << uint32(0x1); // 30
7514 data
<< uint32(0x568) << uint32(0x1); // 13
7515 data
<< uint32(0x565) << uint32(0x0); // 32
7516 data
<< uint32(0x564) << uint32(0x0); // 33
7517 data
<< uint32(0x563) << uint32(0x0); // 34
7518 data
<< uint32(0x562) << uint32(0x0); // 35
7519 data
<< uint32(0x561) << uint32(0x0); // 36
7520 data
<< uint32(0x560) << uint32(0x0); // 37
7521 data
<< uint32(0x55f) << uint32(0x0); // 38
7522 data
<< uint32(0x55e) << uint32(0x0); // 39
7523 data
<< uint32(0x55d) << uint32(0x0); // 40
7524 data
<< uint32(0x3c6) << uint32(0x4); // 41
7525 data
<< uint32(0x3c4) << uint32(0x6); // 42
7526 data
<< uint32(0x3c2) << uint32(0x4); // 43
7527 data
<< uint32(0x516) << uint32(0x1); // 44
7528 data
<< uint32(0x515) << uint32(0x0); // 45
7529 data
<< uint32(0x3b6) << uint32(0x6); // 46
7530 data
<< uint32(0x55c) << uint32(0x0); // 47
7531 data
<< uint32(0x55b) << uint32(0x0); // 48
7532 data
<< uint32(0x55a) << uint32(0x0); // 49
7533 data
<< uint32(0x559) << uint32(0x0); // 50
7534 data
<< uint32(0x558) << uint32(0x0); // 51
7535 data
<< uint32(0x557) << uint32(0x0); // 52
7536 data
<< uint32(0x556) << uint32(0x0); // 53
7537 data
<< uint32(0x555) << uint32(0x0); // 54
7538 data
<< uint32(0x554) << uint32(0x1); // 55
7539 data
<< uint32(0x553) << uint32(0x1); // 56
7540 data
<< uint32(0x552) << uint32(0x1); // 57
7541 data
<< uint32(0x551) << uint32(0x1); // 58
7542 data
<< uint32(0x54f) << uint32(0x0); // 59
7543 data
<< uint32(0x54e) << uint32(0x0); // 60
7544 data
<< uint32(0x54d) << uint32(0x1); // 61
7545 data
<< uint32(0x54c) << uint32(0x0); // 62
7546 data
<< uint32(0x54b) << uint32(0x0); // 63
7547 data
<< uint32(0x545) << uint32(0x0); // 64
7548 data
<< uint32(0x543) << uint32(0x1); // 65
7549 data
<< uint32(0x542) << uint32(0x0); // 66
7550 data
<< uint32(0x540) << uint32(0x0); // 67
7551 data
<< uint32(0x53f) << uint32(0x0); // 68
7552 data
<< uint32(0x53e) << uint32(0x0); // 69
7553 data
<< uint32(0x53d) << uint32(0x0); // 70
7554 data
<< uint32(0x53c) << uint32(0x0); // 71
7555 data
<< uint32(0x53b) << uint32(0x0); // 72
7556 data
<< uint32(0x53a) << uint32(0x1); // 73
7557 data
<< uint32(0x539) << uint32(0x0); // 74
7558 data
<< uint32(0x538) << uint32(0x0); // 75
7559 data
<< uint32(0x537) << uint32(0x0); // 76
7560 data
<< uint32(0x534) << uint32(0x0); // 77
7561 data
<< uint32(0x533) << uint32(0x0); // 78
7562 data
<< uint32(0x530) << uint32(0x0); // 79
7563 data
<< uint32(0x52f) << uint32(0x0); // 80
7564 data
<< uint32(0x52d) << uint32(0x1); // 81
7567 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7568 bg
->FillInitialWorldStates(data
);
7571 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7572 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7573 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7574 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7575 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7576 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7577 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7578 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7582 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7583 bg
->FillInitialWorldStates(data
);
7586 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7587 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7588 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7589 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7590 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7591 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7592 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7593 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7594 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7595 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7596 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7597 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7598 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7599 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7600 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7601 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7602 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7603 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7604 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7605 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7606 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7607 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7608 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7609 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7610 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7611 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7612 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7613 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7614 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7615 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7616 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7617 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7621 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7622 bg
->FillInitialWorldStates(data
);
7625 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7626 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7627 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7628 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7629 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7630 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7631 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7632 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7633 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7634 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7635 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7636 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7637 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7638 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7639 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7640 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7641 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7642 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7643 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7644 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7645 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7646 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7647 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7648 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7649 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7650 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7651 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7652 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7653 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7654 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7655 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7656 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7657 // and some more ... unknown
7660 case 3483: // Hellfire Peninsula
7661 data
<< uint32(0x9ba) << uint32(0x1); // 10
7662 data
<< uint32(0x9b9) << uint32(0x1); // 11
7663 data
<< uint32(0x9b5) << uint32(0x0); // 12
7664 data
<< uint32(0x9b4) << uint32(0x1); // 13
7665 data
<< uint32(0x9b3) << uint32(0x0); // 14
7666 data
<< uint32(0x9b2) << uint32(0x0); // 15
7667 data
<< uint32(0x9b1) << uint32(0x1); // 16
7668 data
<< uint32(0x9b0) << uint32(0x0); // 17
7669 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7670 data
<< uint32(0x9ac) << uint32(0x0); // 19
7671 data
<< uint32(0x9a8) << uint32(0x0); // 20
7672 data
<< uint32(0x9a7) << uint32(0x0); // 21
7673 data
<< uint32(0x9a6) << uint32(0x1); // 22
7675 case 3519: // Terokkar Forest
7676 data
<< uint32(0xa41) << uint32(0x0); // 10
7677 data
<< uint32(0xa40) << uint32(0x14); // 11
7678 data
<< uint32(0xa3f) << uint32(0x0); // 12
7679 data
<< uint32(0xa3e) << uint32(0x0); // 13
7680 data
<< uint32(0xa3d) << uint32(0x5); // 14
7681 data
<< uint32(0xa3c) << uint32(0x0); // 15
7682 data
<< uint32(0xa87) << uint32(0x0); // 16
7683 data
<< uint32(0xa86) << uint32(0x0); // 17
7684 data
<< uint32(0xa85) << uint32(0x0); // 18
7685 data
<< uint32(0xa84) << uint32(0x0); // 19
7686 data
<< uint32(0xa83) << uint32(0x0); // 20
7687 data
<< uint32(0xa82) << uint32(0x0); // 21
7688 data
<< uint32(0xa81) << uint32(0x0); // 22
7689 data
<< uint32(0xa80) << uint32(0x0); // 23
7690 data
<< uint32(0xa7e) << uint32(0x0); // 24
7691 data
<< uint32(0xa7d) << uint32(0x0); // 25
7692 data
<< uint32(0xa7c) << uint32(0x0); // 26
7693 data
<< uint32(0xa7b) << uint32(0x0); // 27
7694 data
<< uint32(0xa7a) << uint32(0x0); // 28
7695 data
<< uint32(0xa79) << uint32(0x0); // 29
7696 data
<< uint32(0x9d0) << uint32(0x5); // 30
7697 data
<< uint32(0x9ce) << uint32(0x0); // 31
7698 data
<< uint32(0x9cd) << uint32(0x0); // 32
7699 data
<< uint32(0x9cc) << uint32(0x0); // 33
7700 data
<< uint32(0xa88) << uint32(0x0); // 34
7701 data
<< uint32(0xad0) << uint32(0x0); // 35
7702 data
<< uint32(0xacf) << uint32(0x1); // 36
7704 case 3521: // Zangarmarsh
7705 data
<< uint32(0x9e1) << uint32(0x0); // 10
7706 data
<< uint32(0x9e0) << uint32(0x0); // 11
7707 data
<< uint32(0x9df) << uint32(0x0); // 12
7708 data
<< uint32(0xa5d) << uint32(0x1); // 13
7709 data
<< uint32(0xa5c) << uint32(0x0); // 14
7710 data
<< uint32(0xa5b) << uint32(0x1); // 15
7711 data
<< uint32(0xa5a) << uint32(0x0); // 16
7712 data
<< uint32(0xa59) << uint32(0x1); // 17
7713 data
<< uint32(0xa58) << uint32(0x0); // 18
7714 data
<< uint32(0xa57) << uint32(0x0); // 19
7715 data
<< uint32(0xa56) << uint32(0x0); // 20
7716 data
<< uint32(0xa55) << uint32(0x1); // 21
7717 data
<< uint32(0xa54) << uint32(0x0); // 22
7718 data
<< uint32(0x9e7) << uint32(0x0); // 23
7719 data
<< uint32(0x9e6) << uint32(0x0); // 24
7720 data
<< uint32(0x9e5) << uint32(0x0); // 25
7721 data
<< uint32(0xa00) << uint32(0x0); // 26
7722 data
<< uint32(0x9ff) << uint32(0x1); // 27
7723 data
<< uint32(0x9fe) << uint32(0x0); // 28
7724 data
<< uint32(0x9fd) << uint32(0x0); // 29
7725 data
<< uint32(0x9fc) << uint32(0x1); // 30
7726 data
<< uint32(0x9fb) << uint32(0x0); // 31
7727 data
<< uint32(0xa62) << uint32(0x0); // 32
7728 data
<< uint32(0xa61) << uint32(0x1); // 33
7729 data
<< uint32(0xa60) << uint32(0x1); // 34
7730 data
<< uint32(0xa5f) << uint32(0x0); // 35
7732 case 3698: // Nagrand Arena
7733 data
<< uint32(0xa0f) << uint32(0x0); // 7
7734 data
<< uint32(0xa10) << uint32(0x0); // 8
7735 data
<< uint32(0xa11) << uint32(0x0); // 9
7737 case 3702: // Blade's Edge Arena
7738 data
<< uint32(0x9f0) << uint32(0x0); // 7
7739 data
<< uint32(0x9f1) << uint32(0x0); // 8
7740 data
<< uint32(0x9f3) << uint32(0x0); // 9
7742 case 3968: // Ruins of Lordaeron
7743 data
<< uint32(0xbb8) << uint32(0x0); // 7
7744 data
<< uint32(0xbb9) << uint32(0x0); // 8
7745 data
<< uint32(0xbba) << uint32(0x0); // 9
7747 case 3703: // Shattrath City
7750 data
<< uint32(0x914) << uint32(0x0); // 7
7751 data
<< uint32(0x913) << uint32(0x0); // 8
7752 data
<< uint32(0x912) << uint32(0x0); // 9
7753 data
<< uint32(0x915) << uint32(0x0); // 10
7756 GetSession()->SendPacket(&data
);
7759 uint32
Player::GetXPRestBonus(uint32 xp
)
7761 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7763 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7766 SetRestBonus( GetRestBonus() - rested_bonus
);
7768 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7769 return rested_bonus
;
7772 void Player::SetBindPoint(uint64 guid
)
7774 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7775 data
<< uint64(guid
);
7776 GetSession()->SendPacket( &data
);
7779 void Player::SendTalentWipeConfirm(uint64 guid
)
7781 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7782 data
<< uint64(guid
);
7783 data
<< uint32(resetTalentsCost());
7784 GetSession()->SendPacket( &data
);
7787 void Player::SendPetSkillWipeConfirm()
7789 Pet
* pet
= GetPet();
7792 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7793 data
<< pet
->GetGUID();
7794 data
<< uint32(pet
->resetTalentsCost());
7795 GetSession()->SendPacket( &data
);
7798 /*********************************************************/
7799 /*** STORAGE SYSTEM ***/
7800 /*********************************************************/
7802 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7807 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7809 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7813 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7814 else if(charges
<= 1)
7816 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7817 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7822 void Player::SetSheath( uint32 sheathed
)
7826 case SHEATH_STATE_UNARMED
: // no prepared weapon
7827 SetVirtualItemSlot(0,NULL
);
7828 SetVirtualItemSlot(1,NULL
);
7829 SetVirtualItemSlot(2,NULL
);
7831 case SHEATH_STATE_MELEE
: // prepared melee weapon
7833 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7834 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7835 SetVirtualItemSlot(2,NULL
);
7837 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7838 SetVirtualItemSlot(0,NULL
);
7839 SetVirtualItemSlot(1,NULL
);
7840 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7843 SetVirtualItemSlot(0,NULL
);
7844 SetVirtualItemSlot(1,NULL
);
7845 SetVirtualItemSlot(2,NULL
);
7848 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7851 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7853 uint8 pClass
= getClass();
7856 slots
[0] = NULL_SLOT
;
7857 slots
[1] = NULL_SLOT
;
7858 slots
[2] = NULL_SLOT
;
7859 slots
[3] = NULL_SLOT
;
7860 switch( proto
->InventoryType
)
7863 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7866 slots
[0] = EQUIPMENT_SLOT_NECK
;
7868 case INVTYPE_SHOULDERS
:
7869 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7872 slots
[0] = EQUIPMENT_SLOT_BODY
;
7875 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7878 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7881 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7884 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7887 slots
[0] = EQUIPMENT_SLOT_FEET
;
7889 case INVTYPE_WRISTS
:
7890 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7893 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7895 case INVTYPE_FINGER
:
7896 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7897 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7899 case INVTYPE_TRINKET
:
7900 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7901 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7904 slots
[0] = EQUIPMENT_SLOT_BACK
;
7906 case INVTYPE_WEAPON
:
7908 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7910 // suggest offhand slot only if know dual wielding
7911 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7913 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7915 case INVTYPE_SHIELD
:
7916 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7918 case INVTYPE_RANGED
:
7919 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7921 case INVTYPE_2HWEAPON
:
7922 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7924 case INVTYPE_TABARD
:
7925 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7927 case INVTYPE_WEAPONMAINHAND
:
7928 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7930 case INVTYPE_WEAPONOFFHAND
:
7931 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7933 case INVTYPE_HOLDABLE
:
7934 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7936 case INVTYPE_THROWN
:
7937 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7939 case INVTYPE_RANGEDRIGHT
:
7940 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7943 slots
[0] = INVENTORY_SLOT_BAG_1
;
7944 slots
[1] = INVENTORY_SLOT_BAG_2
;
7945 slots
[2] = INVENTORY_SLOT_BAG_3
;
7946 slots
[3] = INVENTORY_SLOT_BAG_4
;
7950 switch(proto
->SubClass
)
7952 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7953 if (pClass
== CLASS_PALADIN
)
7954 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7956 case ITEM_SUBCLASS_ARMOR_IDOL
:
7957 if (pClass
== CLASS_DRUID
)
7958 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7960 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7961 if (pClass
== CLASS_SHAMAN
)
7962 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7964 case ITEM_SUBCLASS_ARMOR_MISC
:
7965 if (pClass
== CLASS_WARLOCK
)
7966 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7975 if( slot
!= NULL_SLOT
)
7977 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
7979 for (int i
= 0; i
< 4; i
++)
7981 if ( slots
[i
] == slot
)
7988 // search free slot at first
7989 for (int i
= 0; i
< 4; i
++)
7991 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
7993 // in case 2hand equipped weapon offhand slot empty but not free
7994 if(slots
[i
]==EQUIPMENT_SLOT_OFFHAND
)
7996 Item
* mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
7997 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
8005 // if not found free and can swap return first appropriate from used
8006 for (int i
= 0; i
< 4; i
++)
8008 if ( slots
[i
] != NULL_SLOT
&& swap
)
8017 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8020 uint32 tempcount
= 0;
8022 uint8 res
= EQUIP_ERR_OK
;
8024 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8026 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8027 if( pItem
&& pItem
->GetEntry() == item
)
8029 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8030 if(ires
==EQUIP_ERR_OK
)
8032 tempcount
+= pItem
->GetCount();
8033 if( tempcount
>= count
)
8034 return EQUIP_ERR_OK
;
8040 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8042 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8043 if( pItem
&& pItem
->GetEntry() == item
)
8045 tempcount
+= pItem
->GetCount();
8046 if( tempcount
>= count
)
8047 return EQUIP_ERR_OK
;
8050 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8052 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8053 if( pItem
&& pItem
->GetEntry() == item
)
8055 tempcount
+= pItem
->GetCount();
8056 if( tempcount
>= count
)
8057 return EQUIP_ERR_OK
;
8061 ItemPrototype
const *pBagProto
;
8062 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8064 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8067 pBagProto
= pBag
->GetProto();
8070 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8072 pItem
= GetItemByPos( i
, j
);
8073 if( pItem
&& pItem
->GetEntry() == item
)
8075 tempcount
+= pItem
->GetCount();
8076 if( tempcount
>= count
)
8077 return EQUIP_ERR_OK
;
8084 // not found req. item count and have unequippable items
8088 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8091 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8093 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8094 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8095 count
+= pItem
->GetCount();
8097 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8099 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8100 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8101 count
+= pItem
->GetCount();
8103 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8105 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8107 count
+= pBag
->GetItemCount(item
,skipItem
);
8110 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8112 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8114 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8115 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8116 count
+= pItem
->GetGemCountWithID(item
);
8122 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8124 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8125 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8126 count
+= pItem
->GetCount();
8128 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8130 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8132 count
+= pBag
->GetItemCount(item
,skipItem
);
8135 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8137 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8139 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8140 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8141 count
+= pItem
->GetGemCountWithID(item
);
8149 Item
* Player::GetItemByGuid( uint64 guid
) const
8151 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8153 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8154 if( pItem
&& pItem
->GetGUID() == guid
)
8157 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8159 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8160 if( pItem
&& pItem
->GetGUID() == guid
)
8164 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8166 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8169 ItemPrototype
const *pBagProto
= pBag
->GetProto();
8172 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8174 Item
* pItem
= pBag
->GetItemByPos( j
);
8175 if( pItem
&& pItem
->GetGUID() == guid
)
8181 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8183 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8186 ItemPrototype
const *pBagProto
= pBag
->GetProto();
8189 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8191 Item
* pItem
= pBag
->GetItemByPos( j
);
8192 if( pItem
&& pItem
->GetGUID() == guid
)
8202 Item
* Player::GetItemByPos( uint16 pos
) const
8204 uint8 bag
= pos
>> 8;
8205 uint8 slot
= pos
& 255;
8206 return GetItemByPos( bag
, slot
);
8209 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8211 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8212 return m_items
[slot
];
8213 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8214 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8216 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8218 return pBag
->GetItemByPos(slot
);
8223 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8228 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8229 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8230 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8231 default: return NULL
;
8234 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8235 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8241 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8247 Item
* Player::GetShield(bool useable
) const
8249 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8250 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8256 if( item
->IsBroken())
8262 uint32
Player::GetAttackBySlot( uint8 slot
)
8266 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8267 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8268 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8269 default: return MAX_ATTACK
;
8273 bool Player::HasBankBagSlot( uint8 slot
) const
8275 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8276 if( slot
< maxslot
)
8281 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8283 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8285 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8287 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8289 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8294 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8296 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8298 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8303 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8305 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8307 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8309 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8314 bool Player::IsBagPos( uint16 pos
)
8316 uint8 bag
= pos
>> 8;
8317 uint8 slot
= pos
& 255;
8318 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8320 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8325 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8327 uint32 tempcount
= 0;
8328 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8330 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8331 if( pItem
&& pItem
->GetEntry() == item
)
8333 tempcount
+= pItem
->GetCount();
8334 if( tempcount
>= count
)
8338 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8340 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8341 if( pItem
&& pItem
->GetEntry() == item
)
8343 tempcount
+= pItem
->GetCount();
8344 if( tempcount
>= count
)
8348 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8350 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8352 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
8354 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8356 Item
* pItem
= GetItemByPos( i
, j
);
8357 if( pItem
&& pItem
->GetEntry() == item
)
8359 tempcount
+= pItem
->GetCount();
8360 if( tempcount
>= count
)
8370 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8372 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8373 if( pItem
&& pItem
->GetEntry() == item
)
8375 tempcount
+= pItem
->GetCount();
8376 if( tempcount
>= count
)
8380 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8382 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8384 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
8386 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8388 Item
* pItem
= GetItemByPos( i
, j
);
8389 if( pItem
&& pItem
->GetEntry() == item
)
8391 tempcount
+= pItem
->GetCount();
8392 if( tempcount
>= count
)
8404 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8407 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8409 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8410 if( pItem
&& pItem
->GetEntry() == item
)
8414 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8415 if (pProto
&& pProto
->GemProperties
)
8417 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8419 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8420 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8422 if (pItem
->GetGemCountWithID(item
) > 0 )
8431 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8433 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8437 *no_space_count
= count
;
8438 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8442 if(pProto
->MaxCount
== 0)
8443 return EQUIP_ERR_OK
;
8445 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8447 if( curcount
+ count
> pProto
->MaxCount
)
8450 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8451 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8454 return EQUIP_ERR_OK
;
8457 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8460 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8462 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8463 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8466 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8468 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8469 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8473 ItemPrototype
const *pBagProto
;
8474 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8476 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8479 pBagProto
= pBag
->GetProto();
8482 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; ++j
)
8484 pItem
= GetItemByPos( i
, j
);
8485 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8494 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8496 Item
* pItem2
= GetItemByPos( bag
, slot
);
8498 // ignore move item (this slot will be empty at move)
8499 if(pItem2
==pSrcItem
)
8504 // empty specific slot - check item fit to slot
8505 if( !pItem2
|| swap
)
8507 if( bag
== INVENTORY_SLOT_BAG_0
)
8510 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8511 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8514 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
))
8515 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8517 // currencytoken case
8518 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8519 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8522 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
))
8523 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8526 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8527 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8531 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8533 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8535 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8537 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8539 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8540 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8543 // non empty stack with space
8544 need_space
= pProto
->Stackable
;
8546 // non empty slot, check item type
8550 if(pItem2
->GetEntry() != pProto
->ItemId
)
8551 return EQUIP_ERR_ITEM_CANT_STACK
;
8554 if(pItem2
->GetCount() >= pProto
->Stackable
)
8555 return EQUIP_ERR_ITEM_CANT_STACK
;
8557 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8560 if(need_space
> count
)
8563 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8564 if(!newPosition
.isContainedIn(dest
))
8566 dest
.push_back(newPosition
);
8567 count
-= need_space
;
8569 return EQUIP_ERR_OK
;
8572 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
8574 // skip specific bag already processed in first called _CanStoreItem_InBag
8576 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8578 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8580 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8582 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8584 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8586 // specialized bag mode or non-specilized
8587 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8588 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8590 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8591 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8593 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8595 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8599 Item
* pItem2
= GetItemByPos( bag
, j
);
8601 // ignore move item (this slot will be empty at move)
8602 if(pItem2
==pSrcItem
)
8605 // if merge skip empty, if !merge skip non-empty
8606 if((pItem2
!=NULL
)!=merge
)
8611 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8613 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8614 if(need_space
> count
)
8617 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8618 if(!newPosition
.isContainedIn(dest
))
8620 dest
.push_back(newPosition
);
8621 count
-= need_space
;
8624 return EQUIP_ERR_OK
;
8630 uint32 need_space
= pProto
->Stackable
;
8631 if(need_space
> count
)
8634 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8635 if(!newPosition
.isContainedIn(dest
))
8637 dest
.push_back(newPosition
);
8638 count
-= need_space
;
8641 return EQUIP_ERR_OK
;
8645 return EQUIP_ERR_OK
;
8648 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
8650 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8652 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8653 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8656 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8658 // ignore move item (this slot will be empty at move)
8659 if(pItem2
==pSrcItem
)
8662 // if merge skip empty, if !merge skip non-empty
8663 if((pItem2
!=NULL
)!=merge
)
8668 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8670 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8671 if(need_space
> count
)
8673 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8674 if(!newPosition
.isContainedIn(dest
))
8676 dest
.push_back(newPosition
);
8677 count
-= need_space
;
8680 return EQUIP_ERR_OK
;
8686 uint32 need_space
= pProto
->Stackable
;
8687 if(need_space
> count
)
8690 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8691 if(!newPosition
.isContainedIn(dest
))
8693 dest
.push_back(newPosition
);
8694 count
-= need_space
;
8697 return EQUIP_ERR_OK
;
8701 return EQUIP_ERR_OK
;
8704 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8706 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8708 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8712 *no_space_count
= count
;
8713 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8716 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8719 *no_space_count
= count
;
8720 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8723 // check count of items (skip for auto move for same player from bank)
8724 uint32 no_similar_count
= 0; // can't store this amount similar items
8725 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8726 if(res
!=EQUIP_ERR_OK
)
8728 if(count
==no_similar_count
)
8731 *no_space_count
= no_similar_count
;
8734 count
-= no_similar_count
;
8738 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8740 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8741 if(res
!=EQUIP_ERR_OK
)
8744 *no_space_count
= count
+ no_similar_count
;
8750 if(no_similar_count
==0)
8751 return EQUIP_ERR_OK
;
8754 *no_space_count
= count
+ no_similar_count
;
8755 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8759 // not specific slot or have space for partly store only in specific slot
8762 if( bag
!= NULL_BAG
)
8764 // search stack in bag for merge to
8765 if( pProto
->Stackable
> 1 )
8767 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8769 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8770 if(res
!=EQUIP_ERR_OK
)
8773 *no_space_count
= count
+ no_similar_count
;
8779 if(no_similar_count
==0)
8780 return EQUIP_ERR_OK
;
8783 *no_space_count
= count
+ no_similar_count
;
8784 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8787 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8788 if(res
!=EQUIP_ERR_OK
)
8791 *no_space_count
= count
+ no_similar_count
;
8797 if(no_similar_count
==0)
8798 return EQUIP_ERR_OK
;
8801 *no_space_count
= count
+ no_similar_count
;
8802 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8805 else // equipped bag
8807 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8808 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8809 if(res
!=EQUIP_ERR_OK
)
8810 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8812 if(res
!=EQUIP_ERR_OK
)
8815 *no_space_count
= count
+ no_similar_count
;
8821 if(no_similar_count
==0)
8822 return EQUIP_ERR_OK
;
8825 *no_space_count
= count
+ no_similar_count
;
8826 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8831 // search free slot in bag for place to
8832 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8834 // search free slot - keyring case
8835 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8837 uint32 keyringSize
= GetMaxKeyringSize();
8838 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8839 if(res
!=EQUIP_ERR_OK
)
8842 *no_space_count
= count
+ no_similar_count
;
8848 if(no_similar_count
==0)
8849 return EQUIP_ERR_OK
;
8852 *no_space_count
= count
+ no_similar_count
;
8853 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8856 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
8858 res
= _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START
,VANITYPET_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8859 if(res
!=EQUIP_ERR_OK
)
8862 *no_space_count
= count
+ no_similar_count
;
8868 if(no_similar_count
==0)
8869 return EQUIP_ERR_OK
;
8872 *no_space_count
= count
+ no_similar_count
;
8873 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8876 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
8878 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8879 if(res
!=EQUIP_ERR_OK
)
8882 *no_space_count
= count
+ no_similar_count
;
8888 if(no_similar_count
==0)
8889 return EQUIP_ERR_OK
;
8892 *no_space_count
= count
+ no_similar_count
;
8893 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8896 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
8898 res
= _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8899 if(res
!=EQUIP_ERR_OK
)
8902 *no_space_count
= count
+ no_similar_count
;
8908 if(no_similar_count
==0)
8909 return EQUIP_ERR_OK
;
8912 *no_space_count
= count
+ no_similar_count
;
8913 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8917 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8918 if(res
!=EQUIP_ERR_OK
)
8921 *no_space_count
= count
+ no_similar_count
;
8927 if(no_similar_count
==0)
8928 return EQUIP_ERR_OK
;
8931 *no_space_count
= count
+ no_similar_count
;
8932 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8935 else // equipped bag
8937 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
8938 if(res
!=EQUIP_ERR_OK
)
8939 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
8941 if(res
!=EQUIP_ERR_OK
)
8944 *no_space_count
= count
+ no_similar_count
;
8950 if(no_similar_count
==0)
8951 return EQUIP_ERR_OK
;
8954 *no_space_count
= count
+ no_similar_count
;
8955 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8960 // not specific bag or have space for partly store only in specific bag
8962 // search stack for merge to
8963 if( pProto
->Stackable
> 1 )
8965 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8966 if(res
!=EQUIP_ERR_OK
)
8969 *no_space_count
= count
+ no_similar_count
;
8975 if(no_similar_count
==0)
8976 return EQUIP_ERR_OK
;
8979 *no_space_count
= count
+ no_similar_count
;
8980 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8983 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8984 if(res
!=EQUIP_ERR_OK
)
8987 *no_space_count
= count
+ no_similar_count
;
8993 if(no_similar_count
==0)
8994 return EQUIP_ERR_OK
;
8997 *no_space_count
= count
+ no_similar_count
;
8998 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9001 if( pProto
->BagFamily
)
9003 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9005 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9006 if(res
!=EQUIP_ERR_OK
)
9011 if(no_similar_count
==0)
9012 return EQUIP_ERR_OK
;
9015 *no_space_count
= count
+ no_similar_count
;
9016 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9021 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9023 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9024 if(res
!=EQUIP_ERR_OK
)
9029 if(no_similar_count
==0)
9030 return EQUIP_ERR_OK
;
9033 *no_space_count
= count
+ no_similar_count
;
9034 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9039 // search free slot - special bag case
9040 if( pProto
->BagFamily
)
9042 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9044 uint32 keyringSize
= GetMaxKeyringSize();
9045 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9046 if(res
!=EQUIP_ERR_OK
)
9049 *no_space_count
= count
+ no_similar_count
;
9055 if(no_similar_count
==0)
9056 return EQUIP_ERR_OK
;
9059 *no_space_count
= count
+ no_similar_count
;
9060 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9063 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
9065 res
= _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START
,VANITYPET_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9066 if(res
!=EQUIP_ERR_OK
)
9069 *no_space_count
= count
+ no_similar_count
;
9075 if(no_similar_count
==0)
9076 return EQUIP_ERR_OK
;
9079 *no_space_count
= count
+ no_similar_count
;
9080 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9083 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9085 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9086 if(res
!=EQUIP_ERR_OK
)
9089 *no_space_count
= count
+ no_similar_count
;
9095 if(no_similar_count
==0)
9096 return EQUIP_ERR_OK
;
9099 *no_space_count
= count
+ no_similar_count
;
9100 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9103 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
9105 res
= _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9106 if(res
!=EQUIP_ERR_OK
)
9109 *no_space_count
= count
+ no_similar_count
;
9115 if(no_similar_count
==0)
9116 return EQUIP_ERR_OK
;
9119 *no_space_count
= count
+ no_similar_count
;
9120 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9124 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9126 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9127 if(res
!=EQUIP_ERR_OK
)
9132 if(no_similar_count
==0)
9133 return EQUIP_ERR_OK
;
9136 *no_space_count
= count
+ no_similar_count
;
9137 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9143 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9144 if(res
!=EQUIP_ERR_OK
)
9147 *no_space_count
= count
+ no_similar_count
;
9153 if(no_similar_count
==0)
9154 return EQUIP_ERR_OK
;
9157 *no_space_count
= count
+ no_similar_count
;
9158 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9161 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9163 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9164 if(res
!=EQUIP_ERR_OK
)
9169 if(no_similar_count
==0)
9170 return EQUIP_ERR_OK
;
9173 *no_space_count
= count
+ no_similar_count
;
9174 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9179 *no_space_count
= count
+ no_similar_count
;
9181 return EQUIP_ERR_INVENTORY_FULL
;
9184 //////////////////////////////////////////////////////////////////////////
9185 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9190 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9191 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9192 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9193 int inv_pets
[VANITYPET_SLOT_END
-VANITYPET_SLOT_START
];
9194 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9195 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9197 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9198 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9199 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9200 memset(inv_pets
,0,sizeof(int)*(VANITYPET_SLOT_END
-VANITYPET_SLOT_START
));
9201 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9202 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9204 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9206 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9208 if (pItem2
&& !pItem2
->IsInTrade())
9210 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9214 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9216 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9218 if (pItem2
&& !pItem2
->IsInTrade())
9220 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9224 for(int i
= VANITYPET_SLOT_START
; i
< VANITYPET_SLOT_END
; i
++)
9226 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9228 if (pItem2
&& !pItem2
->IsInTrade())
9230 inv_pets
[i
-VANITYPET_SLOT_START
] = pItem2
->GetCount();
9234 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9236 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9238 if (pItem2
&& !pItem2
->IsInTrade())
9240 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9244 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9246 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9248 if (pItem2
&& !pItem2
->IsInTrade())
9250 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9254 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9257 ItemPrototype
const *pBagProto
;
9259 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9262 pBagProto
= pBag
->GetProto();
9266 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9268 pItem2
= GetItemByPos( i
, j
);
9269 if (pItem2
&& !pItem2
->IsInTrade())
9271 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9278 // check free space for all items
9279 for (int k
=0;k
<count
;k
++)
9281 Item
*pItem
= pItems
[k
];
9284 if (!pItem
) continue;
9286 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9287 ItemPrototype
const *pProto
= pItem
->GetProto();
9291 return EQUIP_ERR_ITEM_NOT_FOUND
;
9294 if(pItem
->IsBindedNotWith(GetGUID()))
9295 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9298 ItemPrototype
const *pBagProto
;
9300 // item is 'one item only'
9301 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9302 if(res
!= EQUIP_ERR_OK
)
9305 // search stack for merge to
9306 if( pProto
->Stackable
> 1 )
9308 bool b_found
= false;
9310 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9312 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9313 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9315 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9320 if (b_found
) continue;
9322 for(int t
= VANITYPET_SLOT_START
; t
< VANITYPET_SLOT_END
; t
++)
9324 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9325 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_pets
[t
-VANITYPET_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9327 inv_pets
[t
-VANITYPET_SLOT_START
] += pItem
->GetCount();
9332 if (b_found
) continue;
9334 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9336 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9337 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9339 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9344 if (b_found
) continue;
9346 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9348 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9349 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9351 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9356 if (b_found
) continue;
9358 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9360 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9361 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9363 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9368 if (b_found
) continue;
9370 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9372 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9375 pBagProto
= pBag
->GetProto();
9378 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9380 pItem2
= GetItemByPos( t
, j
);
9381 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->Stackable
)
9383 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9391 if (b_found
) continue;
9395 if( pProto
->BagFamily
)
9397 bool b_found
= false;
9398 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9400 uint32 keyringSize
= GetMaxKeyringSize();
9401 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9403 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9405 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9412 if (b_found
) continue;
9414 if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
9416 for(uint32 t
= VANITYPET_SLOT_START
; t
< VANITYPET_SLOT_END
; ++t
)
9418 if( inv_pets
[t
-VANITYPET_SLOT_START
] == 0 )
9420 inv_pets
[t
-VANITYPET_SLOT_START
] = 1;
9427 if (b_found
) continue;
9429 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9431 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9433 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9435 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9442 if (b_found
) continue;
9444 if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
9446 for(uint32 t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; ++t
)
9448 if( inv_quests
[t
-QUESTBAG_SLOT_START
] == 0 )
9450 inv_quests
[t
-QUESTBAG_SLOT_START
] = 1;
9457 if (b_found
) continue;
9459 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9461 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9464 pBagProto
= pBag
->GetProto();
9466 // not plain container check
9467 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9468 ItemCanGoIntoBag(pProto
,pBagProto
) )
9470 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9472 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9474 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9482 if (b_found
) continue;
9486 bool b_found
= false;
9487 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9489 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9491 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9496 if (b_found
) continue;
9498 // search free slot in bags
9499 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9501 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9504 pBagProto
= pBag
->GetProto();
9505 if( pBagProto
&& ItemCanGoIntoBag(pProto
,pBagProto
))
9507 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9509 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9511 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9520 // no free slot found?
9522 return EQUIP_ERR_INVENTORY_FULL
;
9525 return EQUIP_ERR_OK
;
9528 //////////////////////////////////////////////////////////////////////////
9529 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, uint32 count
, bool swap
) const
9532 Item
*pItem
= Item::CreateItem( item
, count
, this );
9535 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9540 return EQUIP_ERR_ITEM_NOT_FOUND
;
9543 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9548 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9549 ItemPrototype
const *pProto
= pItem
->GetProto();
9552 // May be here should be more stronger checks; STUNNED checked
9553 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9554 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9555 return EQUIP_ERR_YOU_ARE_STUNNED
;
9557 if(pItem
->IsBindedNotWith(GetGUID()))
9558 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9560 // check count of items (skip for auto move for same player from bank)
9561 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9562 if(res
!= EQUIP_ERR_OK
)
9565 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9567 // - in-progress arenas
9568 if( !pProto
->CanChangeEquipStateInCombat() )
9571 return EQUIP_ERR_NOT_IN_COMBAT
;
9573 if(BattleGround
* bg
= GetBattleGround())
9574 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9575 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9578 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9579 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9581 if(IsNonMeleeSpellCasted(false))
9582 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9584 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9585 if( eslot
== NULL_SLOT
)
9586 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9588 uint8 msg
= CanUseItem( pItem
, not_loading
);
9589 if( msg
!= EQUIP_ERR_OK
)
9591 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9592 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9594 // check unique-equipped on item
9595 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9597 // there is an equip limit on this item
9598 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9599 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9600 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9603 // check unique-equipped on gems
9604 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9606 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9609 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9613 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9614 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9616 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9617 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9618 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9622 // check unique-equipped special item classes
9623 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9625 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9627 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9629 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9631 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9632 (!swap
|| pBag
->GetSlot() != eslot
) )
9634 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9635 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9637 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9644 uint32 type
= pProto
->InventoryType
;
9646 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9648 if( type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9651 return EQUIP_ERR_CANT_DUAL_WIELD
;
9654 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
9657 if(mainItem
->GetProto()->InventoryType
== INVTYPE_2HWEAPON
)
9658 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9662 // equip two-hand weapon case (with possible unequip 2 items)
9663 if( type
== INVTYPE_2HWEAPON
)
9665 if(eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9666 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9668 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9669 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9670 ItemPosCountVec off_dest
;
9671 if( offItem
&& (!not_loading
||
9672 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9673 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9674 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9676 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9677 return EQUIP_ERR_OK
;
9681 return EQUIP_ERR_ITEM_NOT_FOUND
;
9683 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9686 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9688 // Applied only to equipped items and bank bags
9689 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9690 return EQUIP_ERR_OK
;
9692 Item
* pItem
= GetItemByPos(pos
);
9694 // Applied only to existed equipped item
9696 return EQUIP_ERR_OK
;
9698 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9700 ItemPrototype
const *pProto
= pItem
->GetProto();
9702 return EQUIP_ERR_ITEM_NOT_FOUND
;
9704 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9706 // - in-progress arenas
9707 if( !pProto
->CanChangeEquipStateInCombat() )
9710 return EQUIP_ERR_NOT_IN_COMBAT
;
9712 if(BattleGround
* bg
= GetBattleGround())
9713 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9714 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9717 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9718 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9720 return EQUIP_ERR_OK
;
9723 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9726 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9728 uint32 count
= pItem
->GetCount();
9730 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9731 ItemPrototype
const *pProto
= pItem
->GetProto();
9733 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9735 if( pItem
->IsBindedNotWith(GetGUID()) )
9736 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9738 // check count of items (skip for auto move for same player from bank)
9739 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9740 if(res
!= EQUIP_ERR_OK
)
9744 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9746 if( pProto
->InventoryType
== INVTYPE_BAG
)
9748 Bag
*pBag
= (Bag
*)pItem
;
9751 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9753 if( !HasBankBagSlot( slot
) )
9754 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9755 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9760 if( !pBag
->IsEmpty() )
9761 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9767 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9768 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9771 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9772 if(res
!=EQUIP_ERR_OK
)
9776 return EQUIP_ERR_OK
;
9779 // not specific slot or have spece for partly store only in specific slot
9782 if( bag
!= NULL_BAG
)
9784 if( pProto
->InventoryType
== INVTYPE_BAG
)
9786 Bag
*pBag
= (Bag
*)pItem
;
9787 if( pBag
&& !pBag
->IsEmpty() )
9788 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9791 // search stack in bag for merge to
9792 if( pProto
->Stackable
> 1 )
9794 if( bag
== INVENTORY_SLOT_BAG_0
)
9796 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9797 if(res
!=EQUIP_ERR_OK
)
9801 return EQUIP_ERR_OK
;
9805 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9806 if(res
!=EQUIP_ERR_OK
)
9807 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9809 if(res
!=EQUIP_ERR_OK
)
9813 return EQUIP_ERR_OK
;
9817 // search free slot in bag
9818 if( bag
== INVENTORY_SLOT_BAG_0
)
9820 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9821 if(res
!=EQUIP_ERR_OK
)
9825 return EQUIP_ERR_OK
;
9829 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9830 if(res
!=EQUIP_ERR_OK
)
9831 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9833 if(res
!=EQUIP_ERR_OK
)
9837 return EQUIP_ERR_OK
;
9841 // not specific bag or have spece for partly store only in specific bag
9843 // search stack for merge to
9844 if( pProto
->Stackable
> 1 )
9847 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9848 if(res
!=EQUIP_ERR_OK
)
9852 return EQUIP_ERR_OK
;
9855 if( pProto
->BagFamily
)
9857 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9859 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9860 if(res
!=EQUIP_ERR_OK
)
9864 return EQUIP_ERR_OK
;
9868 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9870 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9871 if(res
!=EQUIP_ERR_OK
)
9875 return EQUIP_ERR_OK
;
9879 // search free place in special bag
9880 if( pProto
->BagFamily
)
9882 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9884 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9885 if(res
!=EQUIP_ERR_OK
)
9889 return EQUIP_ERR_OK
;
9893 // search free space
9894 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9895 if(res
!=EQUIP_ERR_OK
)
9899 return EQUIP_ERR_OK
;
9901 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9903 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9904 if(res
!=EQUIP_ERR_OK
)
9908 return EQUIP_ERR_OK
;
9910 return EQUIP_ERR_BANK_FULL
;
9913 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9917 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9918 if( !isAlive() && not_loading
)
9919 return EQUIP_ERR_YOU_ARE_DEAD
;
9921 // return EQUIP_ERR_YOU_ARE_STUNNED;
9922 ItemPrototype
const *pProto
= pItem
->GetProto();
9925 if( pItem
->IsBindedNotWith(GetGUID()) )
9926 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9927 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9928 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9929 if( pItem
->GetSkill() != 0 )
9931 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9932 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9934 if( pProto
->RequiredSkill
!= 0 )
9936 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9937 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9938 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9939 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9941 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9942 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9943 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9944 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9945 if( getLevel() < pProto
->RequiredLevel
)
9946 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9947 return EQUIP_ERR_OK
;
9950 return EQUIP_ERR_ITEM_NOT_FOUND
;
9953 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9955 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9959 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9961 if( pProto
->RequiredSkill
!= 0 )
9963 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9965 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9968 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9970 if( getLevel() < pProto
->RequiredLevel
)
9977 uint8
Player::CanUseAmmo( uint32 item
) const
9979 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9981 return EQUIP_ERR_YOU_ARE_DEAD
;
9983 // return EQUIP_ERR_YOU_ARE_STUNNED;
9984 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9987 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9988 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9989 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9990 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9991 if( pProto
->RequiredSkill
!= 0 )
9993 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9994 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9995 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9996 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9998 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9999 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10000 /*if( GetReputation() < pProto->RequiredReputation )
10001 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10003 if( getLevel() < pProto
->RequiredLevel
)
10004 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10006 // Requires No Ammo
10007 if(GetDummyAura(46699))
10008 return EQUIP_ERR_BAG_FULL6
;
10010 return EQUIP_ERR_OK
;
10012 return EQUIP_ERR_ITEM_NOT_FOUND
;
10015 void Player::SetAmmo( uint32 item
)
10021 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10027 uint8 msg
= CanUseAmmo( item
);
10028 if( msg
!= EQUIP_ERR_OK
)
10030 SendEquipError( msg
, NULL
, NULL
);
10035 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10037 _ApplyAmmoBonuses();
10040 void Player::RemoveAmmo()
10042 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10046 if(CanModifyStats())
10047 UpdateDamagePhysical(RANGED_ATTACK
);
10050 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10051 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10054 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10055 count
+= itr
->count
;
10057 Item
*pItem
= Item::CreateItem( item
, count
, this );
10060 ItemAddedQuestCheck( item
, count
);
10061 if(randomPropertyId
)
10062 pItem
->SetItemRandomProperties(randomPropertyId
);
10063 pItem
= StoreItem( dest
, pItem
, update
);
10068 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10073 Item
* lastItem
= pItem
;
10075 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10077 uint16 pos
= itr
->pos
;
10078 uint32 count
= itr
->count
;
10082 if(itr
== dest
.end())
10084 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10088 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10094 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10095 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10100 uint8 bag
= pos
>> 8;
10101 uint8 slot
= pos
& 255;
10103 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10105 Item
*pItem2
= GetItemByPos( bag
, slot
);
10110 pItem
= pItem
->CloneItem(count
,this);
10112 pItem
->SetCount(count
);
10117 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10118 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10119 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10120 pItem
->SetBinding( true );
10122 if( bag
== INVENTORY_SLOT_BAG_0
)
10124 m_items
[slot
] = pItem
;
10125 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10126 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10127 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10129 pItem
->SetSlot( slot
);
10130 pItem
->SetContainer( NULL
);
10132 if( IsInWorld() && update
)
10134 pItem
->AddToWorld();
10135 pItem
->SendUpdateToPlayer( this );
10138 pItem
->SetState(ITEM_CHANGED
, this);
10142 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10145 pBag
->StoreItem( slot
, pItem
, update
);
10146 if( IsInWorld() && update
)
10148 pItem
->AddToWorld();
10149 pItem
->SendUpdateToPlayer( this );
10151 pItem
->SetState(ITEM_CHANGED
, this);
10152 pBag
->SetState(ITEM_CHANGED
, this);
10156 AddEnchantmentDurations(pItem
);
10157 AddItemDurations(pItem
);
10163 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10164 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10165 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10166 pItem2
->SetBinding( true );
10168 pItem2
->SetCount( pItem2
->GetCount() + count
);
10169 if( IsInWorld() && update
)
10170 pItem2
->SendUpdateToPlayer( this );
10174 // delete item (it not in any slot currently)
10175 if( IsInWorld() && update
)
10177 pItem
->RemoveFromWorld();
10178 pItem
->DestroyForPlayer( this );
10181 RemoveEnchantmentDurations(pItem
);
10182 RemoveItemDurations(pItem
);
10184 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10185 pItem
->SetState(ITEM_REMOVED
, this);
10187 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10188 AddEnchantmentDurations(pItem2
);
10190 pItem2
->SetState(ITEM_CHANGED
, this);
10196 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, uint32 count
, bool update
)
10198 Item
*pItem
= Item::CreateItem( item
, count
, this );
10201 ItemAddedQuestCheck( item
, count
);
10202 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10209 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10213 AddEnchantmentDurations(pItem
);
10214 AddItemDurations(pItem
);
10216 uint8 bag
= pos
>> 8;
10217 uint8 slot
= pos
& 255;
10219 Item
*pItem2
= GetItemByPos( bag
, slot
);
10223 VisualizeItem( slot
, pItem
);
10227 ItemPrototype
const *pProto
= pItem
->GetProto();
10229 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10230 if(pProto
&& pProto
->ItemSet
)
10231 AddItemsSetItem(this,pItem
);
10233 _ApplyItemMods(pItem
, slot
, true);
10235 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10237 m_weaponChangeTimer
= DEFAULT_SWITCH_WEAPON
;
10238 if (getClass() == CLASS_ROGUE
)
10239 m_weaponChangeTimer
= ROGUE_SWITCH_WEAPON
;
10243 if( IsInWorld() && update
)
10245 pItem
->AddToWorld();
10246 pItem
->SendUpdateToPlayer( this );
10249 ApplyEquipCooldown(pItem
);
10251 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10252 UpdateExpertise(BASE_ATTACK
);
10253 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10254 UpdateExpertise(OFF_ATTACK
);
10258 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10259 if( IsInWorld() && update
)
10260 pItem2
->SendUpdateToPlayer( this );
10262 // delete item (it not in any slot currently)
10263 //pItem->DeleteFromDB();
10264 if( IsInWorld() && update
)
10266 pItem
->RemoveFromWorld();
10267 pItem
->DestroyForPlayer( this );
10270 RemoveEnchantmentDurations(pItem
);
10271 RemoveItemDurations(pItem
);
10273 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10274 pItem
->SetState(ITEM_REMOVED
, this);
10275 pItem2
->SetState(ITEM_CHANGED
, this);
10277 ApplyEquipCooldown(pItem2
);
10286 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10290 AddEnchantmentDurations(pItem
);
10291 AddItemDurations(pItem
);
10293 uint8 slot
= pos
& 255;
10294 VisualizeItem( slot
, pItem
);
10298 pItem
->AddToWorld();
10299 pItem
->SendUpdateToPlayer( this );
10304 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10306 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10307 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10308 // entry // Size: 1
10309 // inspected enchantments // Size: 6
10311 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10312 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10317 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10319 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10320 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10322 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10323 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10325 // Use SetInt16Value to prevent set high part to FFFF for negative value
10326 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10327 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10331 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10333 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10334 SetUInt32Value(VisibleBase
+ 0, 0);
10336 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10337 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10339 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10340 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10344 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10349 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10350 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10351 pItem
->SetBinding( true );
10353 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10355 m_items
[slot
] = pItem
;
10356 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10357 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10358 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10359 pItem
->SetSlot( slot
);
10360 pItem
->SetContainer( NULL
);
10362 if( slot
< EQUIPMENT_SLOT_END
)
10363 SetVisibleItemSlot(slot
,pItem
);
10365 pItem
->SetState(ITEM_CHANGED
, this);
10368 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10370 // note: removeitem does not actually change the item
10371 // it only takes the item out of storage temporarily
10372 // note2: if removeitem is to be used for delinking
10373 // the item must be removed from the player's updatequeue
10375 Item
*pItem
= GetItemByPos( bag
, slot
);
10378 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10380 RemoveEnchantmentDurations(pItem
);
10381 RemoveItemDurations(pItem
);
10383 if( bag
== INVENTORY_SLOT_BAG_0
)
10385 if ( slot
< INVENTORY_SLOT_BAG_END
)
10387 ItemPrototype
const *pProto
= pItem
->GetProto();
10388 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10390 if(pProto
&& pProto
->ItemSet
)
10391 RemoveItemsSetItem(this,pProto
);
10393 _ApplyItemMods(pItem
, slot
, false);
10395 // remove item dependent auras and casts (only weapon and armor slots)
10396 if(slot
< EQUIPMENT_SLOT_END
)
10397 RemoveItemDependentAurasAndCasts(pItem
);
10399 // remove held enchantments
10400 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10402 if (pItem
->GetItemSuffixFactor())
10404 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10405 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10409 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10410 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10415 m_items
[slot
] = NULL
;
10416 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10418 if ( slot
< EQUIPMENT_SLOT_END
)
10419 SetVisibleItemSlot(slot
,NULL
);
10423 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10425 pBag
->RemoveItem(slot
, update
);
10427 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10428 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10429 pItem
->SetSlot( NULL_SLOT
);
10430 if( IsInWorld() && update
)
10431 pItem
->SendUpdateToPlayer( this );
10433 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10434 UpdateExpertise(BASE_ATTACK
);
10435 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10436 UpdateExpertise(OFF_ATTACK
);
10440 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10441 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10443 if(Item
* it
= GetItemByPos(bag
,slot
))
10445 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10446 RemoveItem( bag
,slot
,update
);
10447 it
->RemoveFromUpdateQueueOf(this);
10448 if(it
->IsInWorld())
10450 it
->RemoveFromWorld();
10451 it
->DestroyForPlayer( this );
10456 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10457 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10459 // update quest counters
10460 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10463 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10465 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10466 if(pLastItem
==pItem
)
10468 // update owner for last item (this can be original item with wrong owner
10469 if(pLastItem
->GetOwnerGUID() != GetGUID())
10470 pLastItem
->SetOwnerGUID(GetGUID());
10472 // if this original item then it need create record in inventory
10473 // in case trade we laready have item in other player inventory
10474 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10478 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10480 Item
*pItem
= GetItemByPos( bag
, slot
);
10483 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10485 // start from destroy contained items (only equipped bag can have its)
10486 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10488 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10489 DestroyItem(slot
,i
,update
);
10492 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10493 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10495 ItemPrototype
const *pProto
= pItem
->GetProto();
10497 RemoveEnchantmentDurations(pItem
);
10498 RemoveItemDurations(pItem
);
10500 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10502 if( bag
== INVENTORY_SLOT_BAG_0
)
10504 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10506 // equipment and equipped bags can have applied bonuses
10507 if ( slot
< INVENTORY_SLOT_BAG_END
)
10509 ItemPrototype
const *pProto
= pItem
->GetProto();
10511 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10512 if(pProto
&& pProto
->ItemSet
)
10513 RemoveItemsSetItem(this,pProto
);
10515 _ApplyItemMods(pItem
, slot
, false);
10518 if ( slot
< EQUIPMENT_SLOT_END
)
10520 // remove item dependent auras and casts (only weapon and armor slots)
10521 RemoveItemDependentAurasAndCasts(pItem
);
10523 // equipment visual show
10524 SetVisibleItemSlot(slot
,NULL
);
10527 m_items
[slot
] = NULL
;
10529 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10530 pBag
->RemoveItem(slot
, update
);
10532 if( IsInWorld() && update
)
10534 pItem
->RemoveFromWorld();
10535 pItem
->DestroyForPlayer(this);
10538 //pItem->SetOwnerGUID(0);
10539 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10540 pItem
->SetSlot( NULL_SLOT
);
10541 pItem
->SetState(ITEM_REMOVED
, this);
10545 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10547 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10549 ItemPrototype
const *pProto
;
10550 uint32 remcount
= 0;
10553 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10555 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10556 if( pItem
&& pItem
->GetEntry() == item
)
10558 if( pItem
->GetCount() + remcount
<= count
)
10560 // all items in inventory can unequipped
10561 remcount
+= pItem
->GetCount();
10562 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10564 if(remcount
>=count
)
10569 pProto
= pItem
->GetProto();
10570 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10571 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10572 if( IsInWorld() & update
)
10573 pItem
->SendUpdateToPlayer( this );
10574 pItem
->SetState(ITEM_CHANGED
, this);
10579 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10581 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10582 if( pItem
&& pItem
->GetEntry() == item
)
10584 if( pItem
->GetCount() + remcount
<= count
)
10586 // all keys can be unequipped
10587 remcount
+= pItem
->GetCount();
10588 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10590 if(remcount
>=count
)
10595 pProto
= pItem
->GetProto();
10596 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10597 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10598 if( IsInWorld() & update
)
10599 pItem
->SendUpdateToPlayer( this );
10600 pItem
->SetState(ITEM_CHANGED
, this);
10606 // in inventory bags
10608 ItemPrototype
const *pBagProto
;
10609 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10611 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10614 pBagProto
= pBag
->GetProto();
10617 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10619 pItem
= pBag
->GetItemByPos(j
);
10620 if( pItem
&& pItem
->GetEntry() == item
)
10622 // all items in bags can be unequipped
10623 if( pItem
->GetCount() + remcount
<= count
)
10625 remcount
+= pItem
->GetCount();
10626 DestroyItem( i
, j
, update
);
10628 if(remcount
>=count
)
10633 pProto
= pItem
->GetProto();
10634 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10635 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10636 if( IsInWorld() && update
)
10637 pItem
->SendUpdateToPlayer( this );
10638 pItem
->SetState(ITEM_CHANGED
, this);
10647 // in equipment and bag list
10648 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10650 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10651 if( pItem
&& pItem
->GetEntry() == item
)
10653 if( pItem
->GetCount() + remcount
<= count
)
10655 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10657 remcount
+= pItem
->GetCount();
10658 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10660 if(remcount
>=count
)
10666 pProto
= pItem
->GetProto();
10667 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10668 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10669 if( IsInWorld() & update
)
10670 pItem
->SendUpdateToPlayer( this );
10671 pItem
->SetState(ITEM_CHANGED
, this);
10678 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10680 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10683 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10685 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10686 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10687 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10689 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10691 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10692 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10693 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10696 // in inventory bags
10697 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10699 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10702 ItemPrototype
const *pBagProto
= pBag
->GetProto();
10705 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10707 Item
* pItem
= pBag
->GetItemByPos(j
);
10708 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10709 DestroyItem( i
, j
, update
);
10715 // in equipment and bag list
10716 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10718 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10719 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10720 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10724 void Player::DestroyConjuredItems( bool update
)
10726 // used when entering arena
10727 // destroys all conjured items
10728 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10731 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10733 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10734 if( pItem
&& pItem
->GetProto() &&
10735 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10736 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10737 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10740 // in inventory bags
10741 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10743 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10746 ItemPrototype
const *pBagProto
= pBag
->GetProto();
10749 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10751 Item
* pItem
= pBag
->GetItemByPos(j
);
10752 if( pItem
&& pItem
->GetProto() &&
10753 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10754 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10755 DestroyItem( i
, j
, update
);
10761 // in equipment and bag list
10762 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10764 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10765 if( pItem
&& pItem
->GetProto() &&
10766 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10767 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10768 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10772 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10777 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10779 if( pItem
->GetCount() <= count
)
10781 count
-= pItem
->GetCount();
10783 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10787 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10788 pItem
->SetCount( pItem
->GetCount() - count
);
10790 if( IsInWorld() & update
)
10791 pItem
->SendUpdateToPlayer( this );
10792 pItem
->SetState(ITEM_CHANGED
, this);
10796 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10798 uint8 srcbag
= src
>> 8;
10799 uint8 srcslot
= src
& 255;
10801 uint8 dstbag
= dst
>> 8;
10802 uint8 dstslot
= dst
& 255;
10804 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10807 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10811 // not let split all items (can be only at cheating)
10812 if(pSrcItem
->GetCount() == count
)
10814 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10818 // not let split more existed items (can be only at cheating)
10819 if(pSrcItem
->GetCount() < count
)
10821 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10825 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10827 //best error message found for attempting to split while looting
10828 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10832 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10833 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10836 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10840 if( IsInventoryPos( dst
) )
10842 // change item amount before check (for unique max count check)
10843 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10845 ItemPosCountVec dest
;
10846 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10847 if( msg
!= EQUIP_ERR_OK
)
10850 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10851 SendEquipError( msg
, pSrcItem
, NULL
);
10856 pSrcItem
->SendUpdateToPlayer( this );
10857 pSrcItem
->SetState(ITEM_CHANGED
, this);
10858 StoreItem( dest
, pNewItem
, true);
10860 else if( IsBankPos ( dst
) )
10862 // change item amount before check (for unique max count check)
10863 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10865 ItemPosCountVec dest
;
10866 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10867 if( msg
!= EQUIP_ERR_OK
)
10870 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10871 SendEquipError( msg
, pSrcItem
, NULL
);
10876 pSrcItem
->SendUpdateToPlayer( this );
10877 pSrcItem
->SetState(ITEM_CHANGED
, this);
10878 BankItem( dest
, pNewItem
, true);
10880 else if( IsEquipmentPos ( dst
) )
10882 // change item amount before check (for unique max count check), provide space for splitted items
10883 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10886 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10887 if( msg
!= EQUIP_ERR_OK
)
10890 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10891 SendEquipError( msg
, pSrcItem
, NULL
);
10896 pSrcItem
->SendUpdateToPlayer( this );
10897 pSrcItem
->SetState(ITEM_CHANGED
, this);
10898 EquipItem( dest
, pNewItem
, true);
10899 AutoUnequipOffhandIfNeed();
10903 void Player::SwapItem( uint16 src
, uint16 dst
)
10905 uint8 srcbag
= src
>> 8;
10906 uint8 srcslot
= src
& 255;
10908 uint8 dstbag
= dst
>> 8;
10909 uint8 dstslot
= dst
& 255;
10911 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10912 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10917 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10921 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10925 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10927 //best error message found for attempting to swap while looting
10928 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10932 // check unequip potability for equipped items and bank bags
10933 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10935 // bags can be swapped with empty bag slots
10936 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
10937 if(msg
!= EQUIP_ERR_OK
)
10939 SendEquipError( msg
, pSrcItem
, pDstItem
);
10944 // prevent put equipped/bank bag in self
10945 if( IsBagPos ( src
) && srcslot
== dstbag
)
10947 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10953 if( IsInventoryPos( dst
) )
10955 ItemPosCountVec dest
;
10956 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10957 if( msg
!= EQUIP_ERR_OK
)
10959 SendEquipError( msg
, pSrcItem
, NULL
);
10963 RemoveItem(srcbag
, srcslot
, true);
10964 StoreItem( dest
, pSrcItem
, true);
10966 else if( IsBankPos ( dst
) )
10968 ItemPosCountVec dest
;
10969 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10970 if( msg
!= EQUIP_ERR_OK
)
10972 SendEquipError( msg
, pSrcItem
, NULL
);
10976 RemoveItem(srcbag
, srcslot
, true);
10977 BankItem( dest
, pSrcItem
, true);
10979 else if( IsEquipmentPos ( dst
) )
10982 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10983 if( msg
!= EQUIP_ERR_OK
)
10985 SendEquipError( msg
, pSrcItem
, NULL
);
10989 RemoveItem(srcbag
, srcslot
, true);
10990 EquipItem( dest
, pSrcItem
, true);
10991 AutoUnequipOffhandIfNeed();
10994 else // if (!pDstItem)
10996 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10998 //best error message found for attempting to swap while looting
10999 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11003 // check unequip potability for equipped items and bank bags
11004 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11006 // bags can be swapped with empty bag slots
11007 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
11008 if(msg
!= EQUIP_ERR_OK
)
11010 SendEquipError( msg
, pSrcItem
, pDstItem
);
11015 // attempt merge to / fill target item
11018 ItemPosCountVec sDest
;
11020 if( IsInventoryPos( dst
) )
11021 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11022 else if( IsBankPos ( dst
) )
11023 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11024 else if( IsEquipmentPos ( dst
) )
11025 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11029 // can be merge/fill
11030 if(msg
== EQUIP_ERR_OK
)
11032 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->Stackable
)
11034 RemoveItem(srcbag
, srcslot
, true);
11036 if( IsInventoryPos( dst
) )
11037 StoreItem( sDest
, pSrcItem
, true);
11038 else if( IsBankPos ( dst
) )
11039 BankItem( sDest
, pSrcItem
, true);
11040 else if( IsEquipmentPos ( dst
) )
11042 EquipItem( eDest
, pSrcItem
, true);
11043 AutoUnequipOffhandIfNeed();
11048 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->Stackable
);
11049 pDstItem
->SetCount( pSrcItem
->GetProto()->Stackable
);
11050 pSrcItem
->SetState(ITEM_CHANGED
, this);
11051 pDstItem
->SetState(ITEM_CHANGED
, this);
11054 pSrcItem
->SendUpdateToPlayer( this );
11055 pDstItem
->SendUpdateToPlayer( this );
11062 // impossible merge/fill, do real swap
11065 // check src->dest move possibility
11066 ItemPosCountVec sDest
;
11068 if( IsInventoryPos( dst
) )
11069 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11070 else if( IsBankPos( dst
) )
11071 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11072 else if( IsEquipmentPos( dst
) )
11074 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11075 if( msg
== EQUIP_ERR_OK
)
11076 msg
= CanUnequipItem( eDest
, true );
11079 if( msg
!= EQUIP_ERR_OK
)
11081 SendEquipError( msg
, pSrcItem
, pDstItem
);
11085 // check dest->src move possibility
11086 ItemPosCountVec sDest2
;
11088 if( IsInventoryPos( src
) )
11089 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11090 else if( IsBankPos( src
) )
11091 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11092 else if( IsEquipmentPos( src
) )
11094 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11095 if( msg
== EQUIP_ERR_OK
)
11096 msg
= CanUnequipItem( eDest2
, true);
11099 if( msg
!= EQUIP_ERR_OK
)
11101 SendEquipError( msg
, pDstItem
, pSrcItem
);
11105 // now do moves, remove...
11106 RemoveItem(dstbag
, dstslot
, false);
11107 RemoveItem(srcbag
, srcslot
, false);
11110 if( IsInventoryPos( dst
) )
11111 StoreItem(sDest
, pSrcItem
, true);
11112 else if( IsBankPos( dst
) )
11113 BankItem(sDest
, pSrcItem
, true);
11114 else if( IsEquipmentPos( dst
) )
11115 EquipItem(eDest
, pSrcItem
, true);
11118 if( IsInventoryPos( src
) )
11119 StoreItem(sDest2
, pDstItem
, true);
11120 else if( IsBankPos( src
) )
11121 BankItem(sDest2
, pDstItem
, true);
11122 else if( IsEquipmentPos( src
) )
11123 EquipItem(eDest2
, pDstItem
, true);
11125 AutoUnequipOffhandIfNeed();
11129 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11133 uint32 slot
= m_currentBuybackSlot
;
11134 // if current back slot non-empty search oldest or free
11137 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11138 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11140 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11149 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11151 if(oldest_time
> i_time
)
11153 oldest_time
= i_time
;
11159 slot
= oldest_slot
;
11162 RemoveItemFromBuyBackSlot( slot
, true );
11163 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11165 m_items
[slot
] = pItem
;
11166 time_t base
= time(NULL
);
11167 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11168 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11170 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11171 ItemPrototype
const *pProto
= pItem
->GetProto();
11173 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11175 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11176 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11178 // move to next (for non filled list is move most optimized choice)
11179 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11180 ++m_currentBuybackSlot
;
11184 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11186 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11187 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11188 return m_items
[slot
];
11192 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11194 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11195 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11197 Item
*pItem
= m_items
[slot
];
11200 pItem
->RemoveFromWorld();
11201 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11204 m_items
[slot
] = NULL
;
11206 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11207 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11208 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11209 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11211 // if current backslot is filled set to now free slot
11212 if(m_items
[m_currentBuybackSlot
])
11213 m_currentBuybackSlot
= slot
;
11217 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11219 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11220 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11221 data
<< uint8(msg
);
11225 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11226 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11227 data
<< uint8(0); // not 0 there...
11229 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11234 if(ItemPrototype
const* proto
= pItem
->GetProto())
11235 level
= proto
->RequiredLevel
;
11237 data
<< uint32(level
); // new 2.4.0
11240 GetSession()->SendPacket(&data
);
11243 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11245 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11246 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11247 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11248 data
<< uint32(item
);
11250 data
<< uint32(param
);
11251 data
<< uint8(msg
);
11252 GetSession()->SendPacket(&data
);
11255 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11257 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11258 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11259 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11260 data
<< uint64(guid
);
11262 data
<< uint32(param
);
11263 data
<< uint8(msg
);
11264 GetSession()->SendPacket(&data
);
11267 void Player::ClearTrade()
11270 acceptTrade
= false;
11271 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11272 tradeItems
[i
] = NULL_SLOT
;
11275 void Player::TradeCancel(bool sendback
)
11279 // send yellow "Trade cancelled" message to both traders
11283 ws
->SendCancelTrade();
11284 ws
= pTrader
->GetSession();
11285 if(!ws
->PlayerLogout())
11286 ws
->SendCancelTrade();
11290 pTrader
->ClearTrade();
11291 // prevent loss of reference
11292 pTrader
->pTrader
= NULL
;
11297 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11299 if(m_itemDuration
.empty())
11302 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11304 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11307 ++itr
; // current element can be erased in UpdateDuration
11309 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11310 item
->UpdateDuration(this,time
);
11314 void Player::UpdateEnchantTime(uint32 time
)
11316 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11320 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11322 next
= m_enchantDuration
.erase(itr
);
11324 else if(itr
->leftduration
<= time
)
11326 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11327 itr
->item
->ClearEnchantment(itr
->slot
);
11328 next
= m_enchantDuration
.erase(itr
);
11330 else if(itr
->leftduration
> time
)
11332 itr
->leftduration
-= time
;
11338 void Player::AddEnchantmentDurations(Item
*item
)
11340 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11342 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11345 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11347 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11351 void Player::RemoveEnchantmentDurations(Item
*item
)
11353 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11355 if(itr
->item
== item
)
11357 // save duration in item
11358 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11359 itr
= m_enchantDuration
.erase(itr
);
11366 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11368 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11369 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11372 if(itr
->slot
==slot
)
11374 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11376 // remove from stats
11377 ApplyEnchantment(itr
->item
,slot
,false,false);
11379 itr
->item
->ClearEnchantment(slot
);
11381 // remove from update list
11382 next
= m_enchantDuration
.erase(itr
);
11388 // remove enchants from inventory items
11389 // NOTE: no need to remove these from stats, since these aren't equipped
11391 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11393 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11394 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11395 pItem
->ClearEnchantment(slot
);
11398 // in inventory bags
11399 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11401 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11404 ItemPrototype
const *pBagProto
= pBag
->GetProto();
11407 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
11409 Item
* pItem
= pBag
->GetItemByPos(j
);
11410 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11411 pItem
->ClearEnchantment(slot
);
11418 // duration == 0 will remove item enchant
11419 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11424 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11427 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11429 if(itr
->item
== item
&& itr
->slot
== slot
)
11431 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11432 m_enchantDuration
.erase(itr
);
11436 if(item
&& duration
> 0 )
11438 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11439 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11443 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11445 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11446 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11449 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11454 if(!item
->IsEquipped())
11457 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11460 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11464 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11468 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11471 for (int s
=0; s
<3; s
++)
11473 uint32 enchant_display_type
= pEnchant
->type
[s
];
11474 uint32 enchant_amount
= pEnchant
->amount
[s
];
11475 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11477 switch(enchant_display_type
)
11479 case ITEM_ENCHANTMENT_TYPE_NONE
:
11481 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11482 // processed in Player::CastItemCombatSpell
11484 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11485 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11486 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11487 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11488 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11489 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11490 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11492 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11493 if(enchant_spell_id
)
11497 int32 basepoints
= int32(enchant_amount
);
11498 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11499 if (item
->GetItemRandomPropertyId() !=0 && !enchant_amount
)
11501 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11504 // Search enchant_amount
11505 for (int k
=0; k
<3; k
++)
11507 if(item_rand
->enchant_id
[k
] == enchant_id
)
11509 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11515 // Cast custom spell vs all equal basepoints getted from enchant_amount
11517 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11519 CastSpell(this,enchant_spell_id
,true,item
);
11522 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11525 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11526 if (!enchant_amount
)
11528 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11531 for (int k
=0; k
<3; k
++)
11533 if(item_rand
->enchant_id
[k
] == enchant_id
)
11535 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11542 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11544 case ITEM_ENCHANTMENT_TYPE_STAT
:
11546 if (!enchant_amount
)
11548 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11549 if(item_rand_suffix
)
11551 for (int k
=0; k
<3; k
++)
11553 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11555 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11562 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11563 switch (enchant_spell_id
)
11565 case ITEM_MOD_AGILITY
:
11566 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11567 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11568 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11570 case ITEM_MOD_STRENGTH
:
11571 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11572 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11573 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11575 case ITEM_MOD_INTELLECT
:
11576 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11577 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11578 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11580 case ITEM_MOD_SPIRIT
:
11581 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11582 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11583 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11585 case ITEM_MOD_STAMINA
:
11586 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11587 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11588 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11590 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11591 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11592 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11594 case ITEM_MOD_DODGE_RATING
:
11595 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11596 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11598 case ITEM_MOD_PARRY_RATING
:
11599 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11600 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11602 case ITEM_MOD_BLOCK_RATING
:
11603 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11604 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11606 case ITEM_MOD_HIT_MELEE_RATING
:
11607 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11608 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11610 case ITEM_MOD_HIT_RANGED_RATING
:
11611 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11612 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11614 case ITEM_MOD_HIT_SPELL_RATING
:
11615 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11616 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11618 case ITEM_MOD_CRIT_MELEE_RATING
:
11619 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11620 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11622 case ITEM_MOD_CRIT_RANGED_RATING
:
11623 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11624 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11626 case ITEM_MOD_CRIT_SPELL_RATING
:
11627 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11628 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11630 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11632 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11633 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11635 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11636 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11638 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11639 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11641 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11642 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11644 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11645 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11647 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11648 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11650 // case ITEM_MOD_HASTE_MELEE_RATING:
11651 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11653 // case ITEM_MOD_HASTE_RANGED_RATING:
11654 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11656 case ITEM_MOD_HASTE_SPELL_RATING
:
11657 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11659 case ITEM_MOD_HIT_RATING
:
11660 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11661 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11662 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11663 sLog
.outDebug("+ %u HIT", enchant_amount
);
11665 case ITEM_MOD_CRIT_RATING
:
11666 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11667 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11668 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11669 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11671 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11672 // case ITEM_MOD_HIT_TAKEN_RATING:
11673 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11674 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11675 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11677 // case ITEM_MOD_CRIT_TAKEN_RATING:
11678 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11679 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11680 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11682 case ITEM_MOD_RESILIENCE_RATING
:
11683 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11684 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11685 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11686 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11688 case ITEM_MOD_HASTE_RATING
:
11689 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11690 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11691 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11692 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11694 case ITEM_MOD_EXPERTISE_RATING
:
11695 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11696 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11698 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11699 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11700 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11707 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11709 if(getClass() == CLASS_SHAMAN
)
11711 float addValue
= 0.0f
;
11712 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11714 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11715 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11717 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11719 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11720 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11726 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
11728 } /*switch(enchant_display_type)*/
11731 // visualize enchantment at player and equipped items
11732 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11734 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11735 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11743 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11745 AddEnchantmentDuration(item
,slot
,duration
);
11749 // duration == 0 will remove EnchantDuration
11750 AddEnchantmentDuration(item
,slot
,0);
11755 void Player::SendEnchantmentDurations()
11757 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11759 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11763 void Player::SendItemDurations()
11765 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11767 (*itr
)->SendTimeUpdate(this);
11771 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11773 if(!item
) // prevent crash
11776 // last check 2.0.10
11777 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11778 data
<< GetGUID(); // player GUID
11779 data
<< uint32(received
); // 0=looted, 1=from npc
11780 data
<< uint32(created
); // 0=received, 1=created
11781 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11782 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11783 // item slot, but when added to stack: 0xFFFFFFFF
11784 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11785 data
<< uint32(item
->GetEntry()); // item id
11786 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11787 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11788 data
<< uint32(count
); // count of items
11789 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11791 if (broadcast
&& GetGroup())
11792 GetGroup()->BroadcastPacket(&data
);
11794 GetSession()->SendPacket(&data
);
11797 /*********************************************************/
11798 /*** QUEST SYSTEM ***/
11799 /*********************************************************/
11801 void Player::PrepareQuestMenu( uint64 guid
)
11804 QuestRelations
* pObjectQR
;
11805 QuestRelations
* pObjectQIR
;
11806 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11809 pObject
= (Object
*)pCreature
;
11810 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11811 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11815 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11818 pObject
= (Object
*)pGameObject
;
11819 pObjectQR
= &objmgr
.mGOQuestRelations
;
11820 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11826 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11829 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11831 uint32 quest_id
= i
->second
;
11832 QuestStatus status
= GetQuestStatus( quest_id
);
11833 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11834 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11835 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11836 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11837 else if (status
== QUEST_STATUS_AVAILABLE
)
11838 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11841 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11843 uint32 quest_id
= i
->second
;
11844 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11845 if(!pQuest
) continue;
11847 QuestStatus status
= GetQuestStatus( quest_id
);
11849 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11850 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11851 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11852 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11856 void Player::SendPreparedQuest( uint64 guid
)
11858 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11859 if( questMenu
.Empty() )
11862 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11864 uint32 status
= qmi0
.m_qIcon
;
11866 // single element case
11867 if ( questMenu
.MenuItemCount() == 1 )
11869 // Auto open -- maybe also should verify there is no greeting
11870 uint32 quest_id
= qmi0
.m_qId
;
11871 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11874 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11875 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11876 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11877 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11878 // Send completable on repeatable quest if player don't have quest
11879 else if( pQuest
->IsRepeatable() )
11880 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11882 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11885 // multiply entries
11891 std::string title
= "";
11892 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11895 uint32 textid
= pCreature
->GetNpcTextId();
11896 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
11899 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11900 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11905 qe
= gossiptext
->Options
[0].Emotes
[0];
11907 if(!gossiptext
->Options
[0].Text_0
.empty())
11909 title
= gossiptext
->Options
[0].Text_0
;
11911 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11914 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11917 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11918 title
= nl
->Text_0
[0][loc_idx
];
11924 title
= gossiptext
->Options
[0].Text_1
;
11926 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11929 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11932 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11933 title
= nl
->Text_1
[0][loc_idx
];
11939 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11943 bool Player::IsActiveQuest( uint32 quest_id
) const
11945 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11947 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11950 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11953 QuestRelations
* pObjectQR
;
11954 QuestRelations
* pObjectQIR
;
11956 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11959 pObject
= (Object
*)pCreature
;
11960 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11961 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11965 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11968 pObject
= (Object
*)pGameObject
;
11969 pObjectQR
= &objmgr
.mGOQuestRelations
;
11970 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11976 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
11977 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
11979 if (itr
->second
== nextQuestID
)
11980 return objmgr
.GetQuestTemplate(nextQuestID
);
11986 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
11988 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
11989 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
11990 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
11991 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
11993 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
11999 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12001 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12002 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12003 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12004 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12005 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12006 && SatisfyQuestDay( pQuest
, msg
);
12009 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12011 if( !SatisfyQuestLog( msg
) )
12014 uint32 srcitem
= pQuest
->GetSrcItemId();
12017 uint32 count
= pQuest
->GetSrcItemCount();
12018 ItemPosCountVec dest
;
12019 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12021 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12022 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12024 else if( msg
!= EQUIP_ERR_OK
)
12026 SendEquipError( msg
, NULL
, NULL
);
12033 bool Player::CanCompleteQuest( uint32 quest_id
)
12037 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12038 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12039 return false; // not allow re-complete quest
12041 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12046 // auto complete quest
12047 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12050 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12053 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12055 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12057 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12062 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12064 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12066 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12069 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12074 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12077 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12080 if ( qInfo
->GetRewOrReqMoney() < 0 )
12082 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12086 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12087 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12096 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12098 // Solve problem that player don't have the quest and try complete it.
12099 // if repeatable she must be able to complete event if player don't have it.
12100 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12101 if( !CanTakeQuest(pQuest
, false) )
12104 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12105 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12106 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12109 if( !CanRewardQuest(pQuest
, false) )
12115 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12117 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12118 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12121 // daily quest can't be rewarded (10 daily quest already completed)
12122 if(!SatisfyQuestDay(pQuest
,true))
12125 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12126 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12129 // prevent receive reward with quest items in bank
12130 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12132 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12134 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12135 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12138 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12144 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12145 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12151 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12153 // prevent receive reward with quest items in bank or for not completed quest
12154 if(!CanRewardQuest(pQuest
,msg
))
12157 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12159 if( pQuest
->RewChoiceItemId
[reward
] )
12161 ItemPosCountVec dest
;
12162 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12163 if( res
!= EQUIP_ERR_OK
)
12165 SendEquipError( res
, NULL
, NULL
);
12171 if ( pQuest
->GetRewItemsCount() > 0 )
12173 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12175 if( pQuest
->RewItemId
[i
] )
12177 ItemPosCountVec dest
;
12178 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12179 if( res
!= EQUIP_ERR_OK
)
12181 SendEquipError( res
, NULL
, NULL
);
12191 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12193 uint16 log_slot
= FindQuestSlot( 0 );
12194 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12196 uint32 quest_id
= pQuest
->GetQuestId();
12198 // if not exist then created with set uState==NEW and rewarded=false
12199 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12200 if (questStatusData
.uState
!= QUEST_NEW
)
12201 questStatusData
.uState
= QUEST_CHANGED
;
12203 // check for repeatable quests status reset
12204 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12205 questStatusData
.m_explored
= false;
12207 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12209 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12210 questStatusData
.m_itemcount
[i
] = 0;
12213 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12215 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12216 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12219 GiveQuestSourceItem( pQuest
);
12220 AdjustQuestReqItemCount( pQuest
);
12222 if( pQuest
->GetRepObjectiveFaction() )
12223 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12226 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12228 uint32 limittime
= pQuest
->GetLimitTime();
12230 // shared timed quest
12231 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12232 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12234 AddTimedQuest( quest_id
);
12235 questStatusData
.m_timer
= limittime
* 1000;
12236 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12239 questStatusData
.m_timer
= 0;
12241 SetQuestSlot(log_slot
, quest_id
, qtime
);
12243 //starting initial quest script
12244 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12245 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12247 UpdateForQuestsGO();
12250 void Player::CompleteQuest( uint32 quest_id
)
12254 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12256 uint16 log_slot
= FindQuestSlot( quest_id
);
12257 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12258 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12260 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12262 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12263 RewardQuest(qInfo
,0,this,false);
12265 SendQuestComplete( quest_id
);
12270 void Player::IncompleteQuest( uint32 quest_id
)
12274 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12276 uint16 log_slot
= FindQuestSlot( quest_id
);
12277 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12278 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12282 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12284 uint32 quest_id
= pQuest
->GetQuestId();
12286 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12288 if ( pQuest
->ReqItemId
[i
] )
12289 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12292 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12293 // SetTimedQuest( 0 );
12294 m_timedquests
.erase(pQuest
->GetQuestId());
12296 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12298 if( pQuest
->RewChoiceItemId
[reward
] )
12300 ItemPosCountVec dest
;
12301 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12303 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12304 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12309 if ( pQuest
->GetRewItemsCount() > 0 )
12311 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12313 if( pQuest
->RewItemId
[i
] )
12315 ItemPosCountVec dest
;
12316 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12318 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12319 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12325 RewardReputation( pQuest
);
12327 if( pQuest
->GetRewSpellCast() > 0 )
12328 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12329 else if( pQuest
->GetRewSpell() > 0)
12330 CastSpell( this, pQuest
->GetRewSpell(), true);
12332 uint16 log_slot
= FindQuestSlot( quest_id
);
12333 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12334 SetQuestSlot(log_slot
,0);
12336 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12338 // Not give XP in case already completed once repeatable quest
12339 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12341 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12342 GiveXP( XP
, NULL
);
12344 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12346 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12347 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12350 if(pQuest
->GetRewHonorableKills())
12351 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12354 if(pQuest
->GetCharTitleId())
12356 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12357 SetFlag64(PLAYER__FIELD_KNOWN_TITLES
, (uint64(1) << titleEntry
->bit_index
));
12360 // Send reward mail
12361 if(pQuest
->GetRewMailTemplateId())
12363 MailMessageType mailType
;
12364 uint32 senderGuidOrEntry
;
12365 switch(questGiver
->GetTypeId())
12368 mailType
= MAIL_CREATURE
;
12369 senderGuidOrEntry
= questGiver
->GetEntry();
12371 case TYPEID_GAMEOBJECT
:
12372 mailType
= MAIL_GAMEOBJECT
;
12373 senderGuidOrEntry
= questGiver
->GetEntry();
12376 mailType
= MAIL_ITEM
;
12377 senderGuidOrEntry
= questGiver
->GetEntry();
12379 case TYPEID_PLAYER
:
12380 mailType
= MAIL_NORMAL
;
12381 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12384 mailType
= MAIL_NORMAL
;
12385 senderGuidOrEntry
= GetGUIDLow();
12389 Loot questMailLoot
;
12391 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12394 MailItemsInfo mi
; // item list preparing
12396 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12398 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12400 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12402 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12403 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12408 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12410 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12412 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12414 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12415 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12420 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12423 if(pQuest
->IsDaily())
12424 SetDailyQuestStatus(quest_id
);
12426 if ( !pQuest
->IsRepeatable() )
12427 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12429 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12431 q_status
.m_rewarded
= true;
12434 SendQuestReward( pQuest
, XP
, questGiver
);
12436 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12439 void Player::FailQuest( uint32 quest_id
)
12443 IncompleteQuest( quest_id
);
12445 uint16 log_slot
= FindQuestSlot( quest_id
);
12446 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12448 SetQuestSlotTimer(log_slot
, 1 );
12449 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12451 SendQuestFailed( quest_id
);
12455 void Player::FailTimedQuest( uint32 quest_id
)
12459 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12461 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12462 q_status
.m_timer
= 0;
12464 IncompleteQuest( quest_id
);
12466 uint16 log_slot
= FindQuestSlot( quest_id
);
12467 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12469 SetQuestSlotTimer(log_slot
, 1 );
12470 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12472 SendQuestTimerFailed( quest_id
);
12476 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12478 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12479 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12481 // skip zone zoneOrSort and 0 case skillOrClass
12482 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12485 int32 questSort
= -zoneOrSort
;
12486 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12488 // check class sort cases in zoneOrSort
12489 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12492 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12497 if( skillOrClass
< 0 )
12499 uint8 reqClass
= -int32(skillOrClass
);
12500 if(getClass() != reqClass
)
12503 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12508 else if( skillOrClass
> 0 )
12510 uint32 reqSkill
= skillOrClass
;
12511 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12514 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12522 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12524 if( getLevel() < qInfo
->GetMinLevel() )
12527 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12533 bool Player::SatisfyQuestLog( bool msg
)
12536 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12541 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12542 GetSession()->SendPacket( &data
);
12543 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12548 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12550 // No previous quest (might be first quest in a series)
12551 if( qInfo
->prevQuests
.empty())
12554 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12556 uint32 prevId
= abs(*iter
);
12558 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12559 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12561 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12563 // If any of the positive previous quests completed, return true
12564 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12566 // skip one-from-all exclusive group
12567 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12570 // each-from-all exclusive group ( < 0)
12571 // can be start if only all quests in prev quest exclusive group complited and rewarded
12572 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12573 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12575 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12577 for(; iter
!= end
; ++iter
)
12579 uint32 exclude_Id
= iter
->second
;
12581 // skip checked quest id, only state of other quests in group is interesting
12582 if(exclude_Id
== prevId
)
12585 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12587 // alternative quest from group also must be completed and rewarded(reported)
12588 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12591 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12597 // If any of the negative previous quests active, return true
12598 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12599 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12601 // skip one-from-all exclusive group
12602 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12605 // each-from-all exclusive group ( < 0)
12606 // can be start if only all quests in prev quest exclusive group active
12607 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12608 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12610 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12612 for(; iter
!= end
; ++iter
)
12614 uint32 exclude_Id
= iter
->second
;
12616 // skip checked quest id, only state of other quests in group is interesting
12617 if(exclude_Id
== prevId
)
12620 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12622 // alternative quest from group also must be active
12623 if( i_exstatus
== mQuestStatus
.end() ||
12624 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12625 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12628 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12637 // Has only positive prev. quests in non-rewarded state
12638 // and negative prev. quests in non-active state
12640 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12645 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12647 uint32 reqraces
= qInfo
->GetRequiredRaces();
12648 if ( reqraces
== 0 )
12650 if( (reqraces
& getRaceMask()) == 0 )
12653 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12659 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12661 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12662 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12665 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12669 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12670 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12673 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12680 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12682 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12683 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12686 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12692 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12694 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12697 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12703 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12705 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12706 if(qInfo
->GetExclusiveGroup() <= 0)
12709 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12710 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12712 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12714 for(; iter
!= end
; ++iter
)
12716 uint32 exclude_Id
= iter
->second
;
12718 // skip checked quest id, only state of other quests in group is interesting
12719 if(exclude_Id
== qInfo
->GetQuestId())
12722 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12724 // alternative quest already started or completed
12725 if( i_exstatus
!= mQuestStatus
.end()
12726 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12729 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12736 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12738 if(!qInfo
->GetNextQuestInChain())
12741 // next quest in chain already started or completed
12742 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12743 if( itr
!= mQuestStatus
.end()
12744 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12747 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12751 // check for all quests further up the chain
12752 // only necessary if there are quest chains with more than one quest that can be skipped
12753 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12757 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12759 // No previous quest in chain
12760 if( qInfo
->prevChainQuests
.empty())
12763 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12765 uint32 prevId
= *iter
;
12767 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12769 if( i_prevstatus
!= mQuestStatus
.end() )
12771 // If any of the previous quests in chain active, return false
12772 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12773 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12776 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12781 // check for all quests further down the chain
12782 // only necessary if there are quest chains with more than one quest that can be skipped
12783 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12787 // No previous quest in chain active
12791 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12793 if(!qInfo
->IsDaily())
12796 bool have_slot
= false;
12797 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12799 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12800 if(qInfo
->GetQuestId()==id
)
12810 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12817 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12819 uint32 srcitem
= pQuest
->GetSrcItemId();
12822 uint32 count
= pQuest
->GetSrcItemCount();
12826 ItemPosCountVec dest
;
12827 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12828 if( msg
== EQUIP_ERR_OK
)
12830 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12831 SendNewItem(item
, count
, true, false);
12834 // player already have max amount required item, just report success
12835 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12838 SendEquipError( msg
, NULL
, NULL
);
12845 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12847 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12850 uint32 srcitem
= qInfo
->GetSrcItemId();
12853 uint32 count
= qInfo
->GetSrcItemCount();
12857 // exist one case when destroy source quest item not possible:
12858 // non un-equippable item (equipped non-empty bag, for example)
12859 uint8 res
= CanUnequipItems(srcitem
,count
);
12860 if(res
!= EQUIP_ERR_OK
)
12863 SendEquipError( res
, NULL
, NULL
);
12867 DestroyItemCount(srcitem
, count
, true, true);
12873 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12875 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12878 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12879 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12880 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12881 && !qInfo
->IsRepeatable() )
12882 return itr
->second
.m_rewarded
;
12889 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12893 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12894 if( itr
!= mQuestStatus
.end() )
12895 return itr
->second
.m_status
;
12897 return QUEST_STATUS_NONE
;
12900 bool Player::CanShareQuest(uint32 quest_id
) const
12902 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12903 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
12905 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12906 if( itr
!= mQuestStatus
.end() )
12907 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
12912 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
12914 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12917 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
12919 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12920 m_timedquests
.erase(qInfo
->GetQuestId());
12923 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12925 q_status
.m_status
= status
;
12926 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12929 UpdateForQuestsGO();
12932 // not used in MaNGOS, but used in scripting code
12933 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
12935 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12939 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12940 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
12941 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
12946 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
12948 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12950 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12952 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
12953 if( reqitemcount
!= 0 )
12955 uint32 quest_id
= pQuest
->GetQuestId();
12956 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
12958 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12959 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
12960 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12966 uint16
Player::FindQuestSlot( uint32 quest_id
) const
12968 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12969 if ( GetQuestSlotQuestId(i
) == quest_id
)
12972 return MAX_QUEST_LOG_SIZE
;
12975 void Player::AreaExploredOrEventHappens( uint32 questId
)
12979 uint16 log_slot
= FindQuestSlot( questId
);
12980 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12982 QuestStatusData
& q_status
= mQuestStatus
[questId
];
12984 if(!q_status
.m_explored
)
12986 q_status
.m_explored
= true;
12987 if (q_status
.uState
!= QUEST_NEW
)
12988 q_status
.uState
= QUEST_CHANGED
;
12991 if( CanCompleteQuest( questId
) )
12992 CompleteQuest( questId
);
12996 //not used in mangosd, function for external script library
12997 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
12999 if( Group
*pGroup
= GetGroup() )
13001 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13003 Player
*pGroupGuy
= itr
->getSource();
13005 // for any leave or dead (with not released body) group member at appropriate distance
13006 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13007 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13011 AreaExploredOrEventHappens(questId
);
13014 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13016 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13018 uint32 questid
= GetQuestSlotQuestId(i
);
13019 if ( questid
== 0 )
13022 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13024 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13027 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13028 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13031 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13033 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13034 if ( reqitem
== entry
)
13036 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13037 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13038 if ( curitemcount
< reqitemcount
)
13040 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13041 q_status
.m_itemcount
[j
] += additemcount
;
13042 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13044 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13046 if ( CanCompleteQuest( questid
) )
13047 CompleteQuest( questid
);
13052 UpdateForQuestsGO();
13055 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13057 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13059 uint32 questid
= GetQuestSlotQuestId(i
);
13062 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13065 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13068 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13070 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13071 if ( reqitem
== entry
)
13073 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13075 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13076 uint32 curitemcount
;
13077 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13078 curitemcount
= q_status
.m_itemcount
[j
];
13080 curitemcount
= GetItemCount(entry
,true);
13081 if ( curitemcount
< reqitemcount
+ count
)
13083 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13084 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13085 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13087 IncompleteQuest( questid
);
13093 UpdateForQuestsGO();
13096 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13098 uint32 addkillcount
= 1;
13099 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13101 uint32 questid
= GetQuestSlotQuestId(i
);
13105 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13108 // just if !ingroup || !noraidgroup || raidgroup
13109 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13110 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13112 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13114 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13116 // skip GO activate objective or none
13117 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13120 // skip Cast at creature objective
13121 if(qInfo
->ReqSpell
[j
] !=0 )
13124 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13126 if ( reqkill
== entry
)
13128 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13129 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13130 if ( curkillcount
< reqkillcount
)
13132 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13133 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13135 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13137 if ( CanCompleteQuest( questid
) )
13138 CompleteQuest( questid
);
13140 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13149 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13151 bool isCreature
= IS_CREATURE_GUID(guid
);
13153 uint32 addCastCount
= 1;
13154 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13156 uint32 questid
= GetQuestSlotQuestId(i
);
13160 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13164 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13166 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13168 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13170 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13172 // skip kill creature objective (0) or wrong spell casts
13173 if(qInfo
->ReqSpell
[j
] != spell_id
)
13176 uint32 reqTarget
= 0;
13180 // creature activate objectives
13181 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13182 // checked at quest_template loading
13183 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13187 // GO activate objective
13188 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13189 // checked at quest_template loading
13190 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13193 // other not this creature/GO related objectives
13194 if( reqTarget
!= entry
)
13197 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13198 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13199 if ( curCastCount
< reqCastCount
)
13201 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13202 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13204 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13207 if ( CanCompleteQuest( questid
) )
13208 CompleteQuest( questid
);
13210 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13218 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13220 uint32 addTalkCount
= 1;
13221 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13223 uint32 questid
= GetQuestSlotQuestId(i
);
13227 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13231 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13233 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13235 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13237 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13239 // skip spell casts and Gameobject objectives
13240 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13243 uint32 reqTarget
= 0;
13245 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13246 // checked at quest_template loading
13247 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13251 if ( reqTarget
== entry
)
13253 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13254 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13255 if ( curTalkCount
< reqTalkCount
)
13257 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13258 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13260 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13262 if ( CanCompleteQuest( questid
) )
13263 CompleteQuest( questid
);
13265 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13274 void Player::MoneyChanged( uint32 count
)
13276 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13278 uint32 questid
= GetQuestSlotQuestId(i
);
13282 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13283 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13285 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13287 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13289 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13291 if ( CanCompleteQuest( questid
) )
13292 CompleteQuest( questid
);
13295 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13297 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13298 IncompleteQuest( questid
);
13304 bool Player::HasQuestForItem( uint32 itemid
) const
13306 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13308 QuestStatusData
const& q_status
= i
->second
;
13310 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13312 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13316 // hide quest if player is in raid-group and quest is no raid quest
13317 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13320 // There should be no mixed ReqItem/ReqSource drop
13321 // This part for ReqItem drop
13322 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13324 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13327 // This part - for ReqSource
13328 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13330 // examined item is a source item
13331 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13333 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13335 // total count of created ReqItems and SourceItems is less than ReqItemCount
13336 if(qinfo
->ReqItemId
[idx
] != 0 &&
13337 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13340 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13341 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13343 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13346 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13347 else if(qinfo
->ReqSpell
[idx
] != 0)
13349 // not casted and need more reagents/item for use.
13350 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13360 void Player::SendQuestComplete( uint32 quest_id
)
13364 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13366 GetSession()->SendPacket( &data
);
13367 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13371 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13373 // TODO: something really wrong here (there is only 5 x uint32 in client)
13374 uint32 questid
= pQuest
->GetQuestId();
13375 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13376 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4+4+pQuest
->GetRewItemsCount()*8) );
13378 data
<< uint32(0x03);
13380 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13383 data
<< uint32(pQuest
->GetRewOrReqMoney());
13388 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13390 data
<< uint32(0); // new 2.3.0, HonorPoints, HONORAWARD
13391 data
<< uint32(0); // added in WotLK, LEVEL_UP_CHAR_POINTS
13392 data
<< uint32( pQuest
->GetRewItemsCount() ); // max is 5
13394 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13396 if ( pQuest
->RewItemId
[i
] > 0 )
13397 data
<< pQuest
->RewItemId
[i
] << pQuest
->RewItemCount
[i
];
13399 data
<< uint32(0) << uint32(0);
13401 GetSession()->SendPacket( &data
);
13403 if (pQuest
->GetQuestCompleteScript() != 0)
13404 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13407 void Player::SendQuestFailed( uint32 quest_id
)
13411 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13413 data
<< uint32(0); // added in WotLK?
13414 GetSession()->SendPacket( &data
);
13415 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13419 void Player::SendQuestTimerFailed( uint32 quest_id
)
13423 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13425 GetSession()->SendPacket( &data
);
13426 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13430 void Player::SendCanTakeQuestResponse( uint32 msg
)
13432 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13433 data
<< uint32(msg
);
13434 GetSession()->SendPacket( &data
);
13435 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13438 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13442 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13443 data
<< uint64(pPlayer
->GetGUID());
13444 data
<< uint8(msg
); // valid values: 0-8
13445 GetSession()->SendPacket( &data
);
13446 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13450 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13452 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, (4+4) );
13453 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13454 data
<< pQuest
->ReqItemId
[item_idx
];
13456 GetSession()->SendPacket( &data
);
13459 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13461 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13463 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13465 // client expected gameobject template id in form (id|0x80000000)
13466 entry
= (-entry
) | 0x80000000;
13468 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13469 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13470 data
<< uint32(pQuest
->GetQuestId());
13471 data
<< uint32(entry
);
13472 data
<< uint32(old_count
+ add_count
);
13473 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13474 data
<< uint64(guid
);
13475 GetSession()->SendPacket(&data
);
13477 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13478 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13479 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13482 /*********************************************************/
13483 /*** LOAD SYSTEM ***/
13484 /*********************************************************/
13486 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13488 bool delete_result
= true;
13491 // 0 1 2 3 4 5 6 7 8
13492 result
= CharacterDatabase
.PQuery("SELECT data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13493 if(!result
) return false;
13495 else delete_result
= false;
13497 Field
*fields
= result
->Fetch();
13499 if(!LoadValues( fields
[0].GetString()))
13501 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13502 if(delete_result
) delete result
;
13506 // overwrite possible wrong/corrupted guid
13507 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13509 m_name
= fields
[1].GetCppString();
13511 Relocate(fields
[2].GetFloat(),fields
[3].GetFloat(),fields
[4].GetFloat());
13512 SetMapId(fields
[5].GetUInt32());
13513 // the instance id is not needed at character enum
13515 m_Played_time
[0] = fields
[6].GetUInt32();
13516 m_Played_time
[1] = fields
[7].GetUInt32();
13518 m_atLoginFlags
= fields
[8].GetUInt32();
13520 // I don't see these used anywhere ..
13523 _LoadBoundInstances();*/
13525 if (delete_result
) delete result
;
13527 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13530 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13531 m_deathState
= DEAD
;
13536 void Player::_LoadDeclinedNames(QueryResult
* result
)
13542 delete m_declinedname
;
13544 m_declinedname
= new DeclinedName
;
13545 Field
*fields
= result
->Fetch();
13546 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13547 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13552 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13554 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13558 Field
*fields
= result
->Fetch();
13560 x
= fields
[0].GetFloat();
13561 y
= fields
[1].GetFloat();
13562 z
= fields
[2].GetFloat();
13563 o
= fields
[3].GetFloat();
13564 mapid
= fields
[4].GetUInt32();
13565 in_flight
= !fields
[5].GetCppString().empty();
13571 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13573 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13577 Field
*fields
= result
->Fetch();
13579 data
= StrSplit(fields
[0].GetCppString(), " ");
13586 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13588 if(index
>= data
.size())
13591 return (uint32
)atoi(data
[index
].c_str());
13594 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13597 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13598 memcpy(&result
, &temp
, sizeof(result
));
13603 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13606 if(!LoadValuesArrayFromDB(data
,guid
))
13609 return GetUInt32ValueFromArray(data
,index
);
13612 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13615 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13616 memcpy(&result
, &temp
, sizeof(result
));
13621 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13623 //// 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
13624 //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 FROM characters WHERE guid = '%u'", guid);
13625 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13629 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13633 Field
*fields
= result
->Fetch();
13635 uint32 dbAccountId
= fields
[1].GetUInt32();
13637 // check if the character's account in the db and the logged in account match.
13638 // player should be able to load/delete character only with correct account!
13639 if( dbAccountId
!= GetSession()->GetAccountId() )
13641 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13646 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13648 m_name
= fields
[3].GetCppString();
13650 // check name limitations
13651 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13654 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13658 if(!LoadValues( fields
[2].GetString()))
13660 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13665 // overwrite possible wrong/corrupted guid
13666 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13668 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13669 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13671 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13672 SetVisibleItemSlot(slot
,NULL
);
13676 delete m_items
[slot
];
13677 m_items
[slot
] = NULL
;
13681 // update money limits
13682 if(GetMoney() > MAX_MONEY_AMOUNT
)
13683 SetMoney(MAX_MONEY_AMOUNT
);
13685 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13688 m_race
= fields
[4].GetUInt8();
13689 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13690 //Other way is to saves m_team into characters table.
13691 setFactionForRace(m_race
);
13694 m_class
= fields
[5].GetUInt8();
13696 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
13699 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
13704 InitPrimaryProffesions(); // to max set before any spell loaded
13706 uint32 transGUID
= fields
[24].GetUInt32();
13707 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13708 SetMapId(fields
[9].GetUInt32());
13709 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13711 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13713 // check arena teams integrity
13714 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13716 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13720 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13721 if(at
->HaveMember(GetGUID()))
13724 // arena team not exist or not member, cleanup fields
13725 for(int j
=0; j
< 6; ++j
)
13726 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13729 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13731 if(!IsPositionValid())
13733 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());
13735 SetMapId(info
->mapId
);
13736 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13740 m_movementInfo
.t_x
= 0.0f
;
13741 m_movementInfo
.t_y
= 0.0f
;
13742 m_movementInfo
.t_z
= 0.0f
;
13743 m_movementInfo
.t_o
= 0.0f
;
13746 // load the player's map here if it's not already loaded
13747 Map
*map
= GetMap();
13748 // since the player may not be bound to the map yet, make sure subsequent
13749 // getmap calls won't create new maps
13750 SetInstanceId(map
->GetInstanceId());
13752 SaveRecallPosition();
13754 if (transGUID
!= 0)
13756 m_movementInfo
.t_x
= fields
[20].GetFloat();
13757 m_movementInfo
.t_y
= fields
[21].GetFloat();
13758 m_movementInfo
.t_z
= fields
[22].GetFloat();
13759 m_movementInfo
.t_o
= fields
[23].GetFloat();
13761 if( !MaNGOS::IsValidMapCoord(
13762 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13763 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13764 // transport size limited
13765 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13767 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13768 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13769 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13771 SetMapId(info
->mapId
);
13772 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13774 m_movementInfo
.t_x
= 0.0f
;
13775 m_movementInfo
.t_y
= 0.0f
;
13776 m_movementInfo
.t_z
= 0.0f
;
13777 m_movementInfo
.t_o
= 0.0f
;
13783 if (transGUID
!= 0)
13785 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13787 if( (*iter
)->GetGUIDLow() == transGUID
)
13789 m_transport
= *iter
;
13790 m_transport
->AddPassenger(this);
13791 SetMapId(m_transport
->GetMapId());
13798 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13801 SetMapId(info
->mapId
);
13802 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13804 m_movementInfo
.t_x
= 0.0f
;
13805 m_movementInfo
.t_y
= 0.0f
;
13806 m_movementInfo
.t_z
= 0.0f
;
13807 m_movementInfo
.t_o
= 0.0f
;
13813 time_t now
= time(NULL
);
13814 time_t logoutTime
= time_t(fields
[16].GetUInt64());
13816 // since last logout (in seconds)
13817 uint64 time_diff
= uint64(now
- logoutTime
);
13819 // set value, including drunk invisibility detection
13820 // calculate sobering. after 15 minutes logged out, the player will be sober again
13822 if(time_diff
> 15*MINUTE
)
13825 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
13826 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
13827 SetDrunkValue(newDrunkenValue
);
13829 m_rest_bonus
= fields
[15].GetFloat();
13830 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13831 float bubble0
= 0.031;
13832 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13833 float bubble1
= 0.125;
13835 if((int32
)fields
[16].GetUInt32() > 0)
13837 float bubble
= fields
[17].GetUInt32() > 0
13838 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
13839 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
13841 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
13844 m_cinematic
= fields
[12].GetUInt32();
13845 m_Played_time
[0]= fields
[13].GetUInt32();
13846 m_Played_time
[1]= fields
[14].GetUInt32();
13848 m_resetTalentsCost
= fields
[18].GetUInt32();
13849 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
13851 // reserve some flags
13852 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
13854 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
13855 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
13857 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
13859 uint32 extraflags
= fields
[25].GetUInt32();
13861 m_stableSlots
= fields
[26].GetUInt32();
13862 if(m_stableSlots
> 4)
13864 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
13868 m_atLoginFlags
= fields
[27].GetUInt32();
13871 // Update Honor kills data
13872 m_lastHonorUpdateTime
= logoutTime
;
13873 UpdateHonorFields();
13875 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
13876 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
13877 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
13879 std::string taxi_nodes
= fields
[31].GetCppString();
13883 // clear channel spell data (if saved at channel spell casting)
13884 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
13885 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
13887 // clear charm/summon related fields
13888 SetUInt64Value(UNIT_FIELD_CHARM
,0);
13889 SetUInt64Value(UNIT_FIELD_SUMMON
,0);
13890 SetUInt64Value(UNIT_FIELD_CHARMEDBY
,0);
13891 SetUInt64Value(UNIT_FIELD_SUMMONEDBY
,0);
13892 SetUInt64Value(UNIT_FIELD_CREATEDBY
,0);
13894 // reset some aura modifiers before aura apply
13895 SetUInt64Value(PLAYER_FARSIGHT
, 0);
13896 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
13897 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
13899 // reset skill modifiers and set correct unlearn flags
13900 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
13902 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
13904 // set correct unlearn bit
13905 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
13908 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
13909 if(!pSkill
) continue;
13911 // enable unlearn button for primary professions only
13912 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
13913 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
13915 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
13918 // make sure the unit is considered out of combat for proper loading
13921 // make sure the unit is considered not in duel for proper loading
13922 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
13923 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
13925 // remember loaded power/health values to restore after stats initialization and modifier applying
13926 uint32 savedHealth
= GetHealth();
13927 uint32 savedPower
[MAX_POWERS
];
13928 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
13929 savedPower
[i
] = GetPower(Powers(i
));
13931 // reset stats before loading any modifiers
13932 InitStatsForLevel();
13933 InitTaxiNodesForLevel();
13934 InitGlyphsForLevel();
13936 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13938 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13941 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
13943 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13944 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13945 m_deathState
= DEAD
;
13947 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
13949 // after spell load
13950 InitTalentForLevel();
13951 learnSkillRewardedSpells();
13953 // after spell load, learn rewarded spell if need also
13954 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
13955 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
13957 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
13959 // must be before inventory (some items required reputation check)
13960 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
13962 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
13964 // update items with duration and realtime
13965 UpdateItemDuration(time_diff
, true);
13967 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
13969 // unread mails and next delivery time, actual mails not loaded
13970 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
13972 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
13974 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13977 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13978 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13979 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
13981 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES
,uint64(1) << curTitle
))
13982 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
13985 // Not finish taxi flight path
13986 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
))
13988 // problems with taxi path loading
13989 TaxiNodesEntry
const* nodeEntry
= NULL
;
13990 if(uint32 node_id
= m_taxi
.GetTaxiSource())
13991 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
13993 if(!nodeEntry
) // don't know taxi start node, to homebind
13995 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13996 SetMapId(m_homebindMapId
);
13997 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
13998 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14000 else // have start node, to it
14002 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14003 SetMapId(nodeEntry
->map_id
);
14004 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14005 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14007 m_taxi
.ClearTaxiDestinations();
14009 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14011 // save source node as recall coord to prevent recall and fall from sky
14012 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14013 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14014 m_recallMap
= nodeEntry
->map_id
;
14015 m_recallX
= nodeEntry
->x
;
14016 m_recallY
= nodeEntry
->y
;
14017 m_recallZ
= nodeEntry
->z
;
14019 // flight will started later
14022 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14024 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14025 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14027 RemoveAllAurasOnDeath();
14029 //apply all stat bonuses from items and auras
14030 SetCanModifyStats(true);
14033 // restore remembered power/health values (but not more max values)
14034 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14035 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14036 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14038 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14042 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14044 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14047 case 0: break; // disable
14048 case 1: SetGameMaster(true); break; // enable
14049 case 2: // save state
14050 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14051 SetGameMaster(true);
14055 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14058 case 0: break; // disable
14059 case 1: SetAcceptTicket(true); break; // enable
14060 case 2: // save state
14061 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14062 SetAcceptTicket(true);
14066 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14069 case 0: break; // disable
14070 case 1: SetGMChat(true); break; // enable
14071 case 2: // save state
14072 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14077 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14080 case 0: break; // disable
14081 case 1: SetAcceptWhispers(true); break; // enable
14082 case 2: // save state
14083 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14084 SetAcceptWhispers(true);
14089 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14091 m_achievementMgr
.LoadFromDB();
14092 m_achievementMgr
.CheckAllAchievementCriteria();
14096 bool Player::isAllowedToLoot(Creature
* creature
)
14098 if(Player
* recipient
= creature
->GetLootRecipient())
14100 if (recipient
== this)
14102 if( Group
* otherGroup
= recipient
->GetGroup())
14104 Group
* thisGroup
= GetGroup();
14107 return thisGroup
== otherGroup
;
14112 // prevent other players from looting if the recipient got disconnected
14113 return !creature
->hasLootRecipient();
14116 void Player::_LoadActions(QueryResult
*result
)
14118 m_actionButtons
.clear();
14120 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14126 Field
*fields
= result
->Fetch();
14128 uint8 button
= fields
[0].GetUInt8();
14130 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
14132 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14134 while( result
->NextRow() );
14140 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14143 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14144 m_modAuras
[i
].clear();
14146 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14152 Field
*fields
= result
->Fetch();
14153 uint64 caster_guid
= fields
[0].GetUInt64();
14154 uint32 spellid
= fields
[1].GetUInt32();
14155 uint32 effindex
= fields
[2].GetUInt32();
14156 int32 damage
= (int32
)fields
[3].GetUInt32();
14157 int32 maxduration
= (int32
)fields
[4].GetUInt32();
14158 int32 remaintime
= (int32
)fields
[5].GetUInt32();
14159 int32 remaincharges
= (int32
)fields
[6].GetUInt32();
14161 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14164 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14170 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14174 // negative effects should continue counting down after logout
14175 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14177 if(remaintime
<= int32(timediff
))
14180 remaintime
-= timediff
;
14183 // prevent wrong values of remaincharges
14184 if(spellproto
->procCharges
)
14186 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14187 remaincharges
= spellproto
->procCharges
;
14192 //do not load single target auras (unless they were cast by the player)
14193 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14196 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14198 damage
= aura
->GetModifier()->m_amount
;
14199 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14202 while( result
->NextRow() );
14207 if(m_class
== CLASS_WARRIOR
)
14208 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14211 void Player::LoadCorpse()
14215 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14219 if(Corpse
*corpse
= GetCorpse())
14221 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14225 //Prevent Dead Player login without corpse
14226 ResurrectPlayer(0.5f
);
14231 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14233 //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());
14234 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14235 //NOTE: the "order by `bag`" is important because it makes sure
14236 //the bagMap is filled before items in the bags are loaded
14237 //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
14238 //expected to be equipped before offhand items (TODO: fixme)
14240 uint32 zone
= GetZoneId();
14244 std::list
<Item
*> problematicItems
;
14246 // prevent items from being added to the queue when stored
14247 m_itemUpdateQueueBlocked
= true;
14250 Field
*fields
= result
->Fetch();
14251 uint32 bag_guid
= fields
[1].GetUInt32();
14252 uint8 slot
= fields
[2].GetUInt8();
14253 uint32 item_guid
= fields
[3].GetUInt32();
14254 uint32 item_id
= fields
[4].GetUInt32();
14256 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14260 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14261 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14262 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14266 Item
*item
= NewItemOrBag(proto
);
14268 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14270 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14271 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14272 item
->FSetState(ITEM_REMOVED
);
14273 item
->SaveToDB(); // it also deletes item object !
14277 // not allow have in alive state item limited to another map/zone
14278 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14280 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14281 item
->FSetState(ITEM_REMOVED
);
14282 item
->SaveToDB(); // it also deletes item object !
14286 // "Conjured items disappear if you are logged out for more than 15 minutes"
14287 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14289 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14290 item
->FSetState(ITEM_REMOVED
);
14291 item
->SaveToDB(); // it also deletes item object !
14295 bool success
= true;
14299 // the item is not in a bag
14300 item
->SetContainer( NULL
);
14301 item
->SetSlot(slot
);
14303 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14305 ItemPosCountVec dest
;
14306 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14307 item
= StoreItem(dest
, item
, true);
14311 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14314 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14315 QuickEquipItem(dest
, item
);
14319 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14321 ItemPosCountVec dest
;
14322 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14323 item
= BankItem(dest
, item
, true);
14330 // store bags that may contain items in them
14331 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14332 bagMap
[item_guid
] = (Bag
*)item
;
14337 item
->SetSlot(NULL_SLOT
);
14338 // the item is in a bag, find the bag
14339 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14340 if(itr
!= bagMap
.end())
14341 itr
->second
->StoreItem(slot
, item
, true );
14346 // item's state may have changed after stored
14348 item
->SetState(ITEM_UNCHANGED
, this);
14351 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
);
14352 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14353 problematicItems
.push_back(item
);
14355 } while (result
->NextRow());
14358 m_itemUpdateQueueBlocked
= false;
14360 // send by mail problematic items
14361 while(!problematicItems
.empty())
14364 MailItemsInfo mi
; // item list prepering
14366 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14368 Item
* item
= problematicItems
.front();
14369 problematicItems
.pop_front();
14371 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14374 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14376 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14380 _ApplyAllItemMods();
14383 // load mailed item which should receive current player
14384 void Player::_LoadMailedItems(Mail
*mail
)
14386 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail
->messageID
);
14392 Field
*fields
= result
->Fetch();
14393 uint32 item_guid_low
= fields
[0].GetUInt32();
14394 uint32 item_template
= fields
[1].GetUInt32();
14396 mail
->AddItem(item_guid_low
, item_template
);
14398 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14402 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
);
14403 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14404 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14408 Item
*item
= NewItemOrBag(proto
);
14410 if(!item
->LoadFromDB(item_guid_low
, 0))
14412 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14413 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14414 item
->FSetState(ITEM_REMOVED
);
14415 item
->SaveToDB(); // it also deletes item object !
14420 } while (result
->NextRow());
14425 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14427 //set a count of unread mails
14428 //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);
14431 Field
*fieldMail
= resultUnread
->Fetch();
14432 unReadMails
= fieldMail
[0].GetUInt8();
14433 delete resultUnread
;
14436 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14437 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14438 if (resultDelivery
)
14440 Field
*fieldMail
= resultDelivery
->Fetch();
14441 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14442 delete resultDelivery
;
14446 void Player::_LoadMail()
14449 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14450 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());
14455 Field
*fields
= result
->Fetch();
14456 Mail
*m
= new Mail
;
14457 m
->messageID
= fields
[0].GetUInt32();
14458 m
->messageType
= fields
[1].GetUInt8();
14459 m
->sender
= fields
[2].GetUInt32();
14460 m
->receiver
= fields
[3].GetUInt32();
14461 m
->subject
= fields
[4].GetCppString();
14462 m
->itemTextId
= fields
[5].GetUInt32();
14463 bool has_items
= fields
[6].GetBool();
14464 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14465 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14466 m
->money
= fields
[9].GetUInt32();
14467 m
->COD
= fields
[10].GetUInt32();
14468 m
->checked
= fields
[11].GetUInt32();
14469 m
->stationery
= fields
[12].GetUInt8();
14470 m
->mailTemplateId
= fields
[13].GetInt16();
14472 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14474 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14475 m
->mailTemplateId
= 0;
14478 m
->state
= MAIL_STATE_UNCHANGED
;
14481 _LoadMailedItems(m
);
14483 m_mail
.push_back(m
);
14484 } while( result
->NextRow() );
14487 m_mailsLoaded
= true;
14490 void Player::LoadPet()
14492 //fixme: the pet should still be loaded if the player is not in world
14493 // just not added to the map
14496 Pet
*pet
= new Pet
;
14497 if(!pet
->LoadPetFromDB(this,0,0,true))
14502 void Player::_LoadQuestStatus(QueryResult
*result
)
14504 mQuestStatus
.clear();
14508 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14509 //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());
14515 Field
*fields
= result
->Fetch();
14517 uint32 quest_id
= fields
[0].GetUInt32();
14518 // used to be new, no delete?
14519 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14523 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14525 uint32 qstatus
= fields
[1].GetUInt32();
14526 if(qstatus
< MAX_QUEST_STATUS
)
14527 questStatusData
.m_status
= QuestStatus(qstatus
);
14530 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14531 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14534 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14535 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14537 time_t quest_time
= time_t(fields
[4].GetUInt64());
14539 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14541 AddTimedQuest( quest_id
);
14543 if (quest_time
<= sWorld
.GetGameTime())
14544 questStatusData
.m_timer
= 1;
14546 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14551 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14552 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14553 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14554 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14555 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14556 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14557 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14558 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14560 questStatusData
.uState
= QUEST_UNCHANGED
;
14562 // add to quest log
14563 if( slot
< MAX_QUEST_LOG_SIZE
&&
14564 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14565 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&& !questStatusData
.m_rewarded
) )
14567 SetQuestSlot(slot
,quest_id
,quest_time
);
14569 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14570 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14572 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14573 if(questStatusData
.m_creatureOrGOcount
[idx
])
14574 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14579 if(questStatusData
.m_rewarded
)
14581 // learn rewarded spell if unknown
14582 learnQuestRewardedSpells(pQuest
);
14584 // set rewarded title if any
14585 if(pQuest
->GetCharTitleId())
14587 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14588 SetFlag64(PLAYER__FIELD_KNOWN_TITLES
, (uint64(1) << titleEntry
->bit_index
));
14592 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14595 while( result
->NextRow() );
14600 // clear quest log tail
14601 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14605 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14607 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14608 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14610 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14614 uint32 quest_daily_idx
= 0;
14618 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14620 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14624 Field
*fields
= result
->Fetch();
14626 uint32 quest_id
= fields
[0].GetUInt32();
14628 // save _any_ from daily quest times (it must be after last reset anyway)
14629 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14631 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14635 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14638 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14640 while( result
->NextRow() );
14645 m_DailyQuestChanged
= false;
14648 void Player::_LoadReputation(QueryResult
*result
)
14650 m_factions
.clear();
14652 // Set initial reputations (so everything is nifty before DB data load)
14653 SetInitialFactions();
14655 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14661 Field
*fields
= result
->Fetch();
14663 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
14664 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
14666 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
14668 // update standing to current
14669 faction
->Standing
= int32(fields
[1].GetUInt32());
14671 uint32 dbFactionFlags
= fields
[2].GetUInt32();
14673 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
14674 SetFactionVisible(faction
); // have internal checks for forced invisibility
14676 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
14677 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
14679 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
14680 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14681 else // DB not at war
14683 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14684 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
14685 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14688 // set atWar for hostile
14689 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
14690 SetFactionAtWar(faction
,true);
14692 // reset changed flag if values similar to saved in DB
14693 if(faction
->Flags
==dbFactionFlags
)
14694 faction
->Changed
= false;
14697 while( result
->NextRow() );
14703 void Player::_LoadSpells(QueryResult
*result
)
14705 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
14706 delete itr
->second
;
14709 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14715 Field
*fields
= result
->Fetch();
14717 addSpell(fields
[0].GetUInt16(), fields
[2].GetBool(), false, true, fields
[1].GetUInt16(), fields
[3].GetBool());
14719 while( result
->NextRow() );
14725 void Player::_LoadTutorials(QueryResult
*result
)
14727 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14733 Field
*fields
= result
->Fetch();
14735 for (int iI
=0; iI
<8; iI
++)
14736 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14738 while( result
->NextRow() );
14743 m_TutorialsChanged
= false;
14746 void Player::_LoadGroup(QueryResult
*result
)
14748 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14751 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14753 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14756 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14757 SetGroup(group
, subgroup
);
14758 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14760 // the group leader may change the instance difficulty while the player is offline
14761 SetDifficulty(group
->GetDifficulty());
14767 void Player::_LoadBoundInstances(QueryResult
*result
)
14769 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14770 m_boundInstances
[i
].clear();
14772 Group
*group
= GetGroup();
14774 //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));
14779 Field
*fields
= result
->Fetch();
14780 bool perm
= fields
[1].GetBool();
14781 uint32 mapId
= fields
[2].GetUInt32();
14782 uint32 instanceId
= fields
[0].GetUInt32();
14783 uint8 difficulty
= fields
[3].GetUInt8();
14784 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14785 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14786 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14787 // and in that case it is not used
14791 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
);
14792 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14796 // since non permanent binds are always solo bind, they can always be reset
14797 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
14798 if(save
) BindToInstance(save
, perm
, true);
14799 } while(result
->NextRow());
14804 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
14806 // some instances only have one difficulty
14807 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
14808 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
14810 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14811 if(itr
!= m_boundInstances
[difficulty
].end())
14812 return &itr
->second
;
14817 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
14819 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14820 UnbindInstance(itr
, difficulty
, unload
);
14823 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
14825 if(itr
!= m_boundInstances
[difficulty
].end())
14827 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
14828 itr
->second
.save
->RemovePlayer(this); // save can become invalid
14829 m_boundInstances
[difficulty
].erase(itr
++);
14833 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
14837 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
14840 // update the save when the group kills a boss
14841 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
14842 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());
14845 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
14847 if(bind
.save
!= save
)
14849 if(bind
.save
) bind
.save
->RemovePlayer(this);
14850 save
->AddPlayer(this);
14853 if(permanent
) save
->SetCanReset(false);
14856 bind
.perm
= permanent
;
14857 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());
14864 void Player::SendRaidInfo()
14866 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
14868 uint32 counter
= 0, i
;
14869 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14870 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
14871 if(itr
->second
.perm
) counter
++;
14874 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14876 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
14878 if(itr
->second
.perm
)
14880 InstanceSave
*save
= itr
->second
.save
;
14881 data
<< (save
->GetMapId());
14882 data
<< (uint32
)(save
->GetResetTime() - time(NULL
));
14883 data
<< save
->GetInstanceId();
14884 data
<< uint32(counter
);
14889 GetSession()->SendPacket(&data
);
14893 - called on every successful teleportation to a map
14895 void Player::SendSavedInstances()
14897 bool hasBeenSaved
= false;
14900 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14902 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14904 if(itr
->second
.perm
) // only permanent binds are sent
14906 hasBeenSaved
= true;
14912 //Send opcode 811. true or flase means, whether you have current raid/heroic instances
14913 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
14914 data
<< uint32(hasBeenSaved
);
14915 GetSession()->SendPacket(&data
);
14920 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14922 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14924 if(itr
->second
.perm
)
14926 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
14927 data
<< uint32(itr
->second
.save
->GetMapId());
14928 GetSession()->SendPacket(&data
);
14934 /// convert the player's binds to the group
14935 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
14937 bool has_binds
= false;
14938 bool has_solo
= false;
14940 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
14941 assert(player_guid
);
14943 // copy all binds to the group, when changing leader it's assumed the character
14944 // will not have any solo binds
14948 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14950 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
14953 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
14954 // permanent binds are not removed
14955 if(!itr
->second
.perm
)
14957 player
->UnbindInstance(itr
, i
, true); // increments itr
14966 // if the player's not online we don't know what binds it has
14967 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
));
14968 // the following should not get executed when changing leaders
14969 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
14972 bool Player::_LoadHomeBind(QueryResult
*result
)
14975 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14978 Field
*fields
= result
->Fetch();
14979 m_homebindMapId
= fields
[0].GetUInt32();
14980 m_homebindZoneId
= fields
[1].GetUInt16();
14981 m_homebindX
= fields
[2].GetFloat();
14982 m_homebindY
= fields
[3].GetFloat();
14983 m_homebindZ
= fields
[4].GetFloat();
14986 // accept saved data only for valid position (and non instanceable)
14987 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
14988 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
14993 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14998 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
14999 if(!info
) return false;
15001 m_homebindMapId
= info
->mapId
;
15002 m_homebindZoneId
= info
->zoneId
;
15003 m_homebindX
= info
->positionX
;
15004 m_homebindY
= info
->positionY
;
15005 m_homebindZ
= info
->positionZ
;
15007 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
);
15010 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15011 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15016 /*********************************************************/
15017 /*** SAVE SYSTEM ***/
15018 /*********************************************************/
15020 void Player::SaveToDB()
15022 // delay auto save at any saves (manual, in code, or autosave)
15023 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15025 // first save/honor gain after midnight will also update the player's honor fields
15026 UpdateHonorFields();
15028 // Must saved before enter into BattleGround
15029 if(InBattleGround())
15032 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15033 //save, far from tavern/city
15034 //save, but in tavern/city
15035 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15038 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15039 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15040 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15041 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15042 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15043 uint32 tmp_displayid
= GetDisplayId();
15045 // Set player sit state to standing on save, also stealth and shifted form
15046 SetByteValue(UNIT_FIELD_BYTES_1
, 0, 0); // stand state
15047 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15048 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0); // stand flags?
15049 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15050 SetDisplayId(GetNativeDisplayId());
15052 bool inworld
= IsInWorld();
15054 CharacterDatabase
.BeginTransaction();
15056 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15058 std::string sql_name
= m_name
;
15059 CharacterDatabase
.escape_string(sql_name
);
15061 std::ostringstream ss
;
15062 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15063 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15064 "taximask, online, cinematic, "
15065 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15066 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15067 "death_expire_time, taxi_path) VALUES ("
15068 << GetGUIDLow() << ", "
15069 << GetSession()->GetAccountId() << ", '"
15070 << sql_name
<< "', "
15072 << m_class
<< ", ";
15074 bool save_to_dest
= false;
15075 if(IsBeingTeleported())
15077 // don't save to battlegrounds or arenas
15078 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
15079 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
15080 save_to_dest
= true;
15085 ss
<< GetMapId() << ", "
15086 << (uint32
)GetDifficulty() << ", "
15087 << finiteAlways(GetPositionX()) << ", "
15088 << finiteAlways(GetPositionY()) << ", "
15089 << finiteAlways(GetPositionZ()) << ", "
15090 << finiteAlways(GetOrientation()) << ", '";
15094 ss
<< GetTeleportDest().mapid
<< ", "
15095 << (uint32
)GetDifficulty() << ", "
15096 << finiteAlways(GetTeleportDest().x
) << ", "
15097 << finiteAlways(GetTeleportDest().y
) << ", "
15098 << finiteAlways(GetTeleportDest().z
) << ", "
15099 << finiteAlways(GetTeleportDest().o
) << ", '";
15103 for( i
= 0; i
< m_valuesCount
; i
++ )
15105 ss
<< GetUInt32Value(i
) << " ";
15110 for( i
= 0; i
< 8; i
++ )
15111 ss
<< m_taxi
.GetTaximask(i
) << " ";
15114 ss
<< (inworld
? 1 : 0);
15120 ss
<< m_Played_time
[0];
15122 ss
<< m_Played_time
[1];
15125 ss
<< finiteAlways(m_rest_bonus
);
15127 ss
<< (uint64
)time(NULL
);
15129 ss
<< is_save_resting
;
15131 ss
<< m_resetTalentsCost
;
15133 ss
<< (uint64
)m_resetTalentsTime
;
15136 ss
<< finiteAlways(m_movementInfo
.t_x
);
15138 ss
<< finiteAlways(m_movementInfo
.t_y
);
15140 ss
<< finiteAlways(m_movementInfo
.t_z
);
15142 ss
<< finiteAlways(m_movementInfo
.t_o
);
15145 ss
<< m_transport
->GetGUIDLow();
15150 ss
<< m_ExtraFlags
;
15153 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15156 ss
<< uint32(m_atLoginFlags
);
15162 ss
<< (uint64
)m_deathExpireTime
;
15165 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15168 CharacterDatabase
.Execute( ss
.str().c_str() );
15170 if(m_mailsUpdated
) //save mails only when needed
15174 _SaveQuestStatus();
15175 _SaveDailyQuestStatus();
15178 _SaveSpellCooldowns();
15183 CharacterDatabase
.CommitTransaction();
15185 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15186 SetDisplayId(tmp_displayid
);
15187 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15188 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15189 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15190 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15192 // save pet (hunter pet level and experience and all type pets health/mana).
15193 if(Pet
* pet
= GetPet())
15194 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15195 m_achievementMgr
.SaveToDB();
15198 // fast save function for item/money cheating preventing - save only inventory and money state
15199 void Player::SaveInventoryAndGoldToDB()
15202 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE
,GetMoney(),GetGUID());
15205 void Player::_SaveActions()
15207 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15209 switch (itr
->second
.uState
)
15211 case ACTIONBUTTON_NEW
:
15212 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15213 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15214 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15217 case ACTIONBUTTON_CHANGED
:
15218 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15219 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15220 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15223 case ACTIONBUTTON_DELETED
:
15224 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15225 m_actionButtons
.erase(itr
++);
15234 void Player::_SaveAuras()
15236 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15238 AuraMap
const& auras
= GetAuras();
15239 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); ++itr
)
15241 SpellEntry
const *spellInfo
= itr
->second
->GetSpellProto();
15243 //skip all auras from spells that are passive or need a shapeshift
15244 if (itr
->second
->IsPassive() || itr
->second
->IsRemovedOnShapeLost())
15247 //do not save single target auras (unless they were cast by the player)
15248 if (itr
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
))
15252 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15253 for (i
= 0; i
< 3; i
++)
15254 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15255 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15260 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and effect_index= '%u'",GetGUIDLow(),(uint32
)(*itr
).second
->GetId(), (uint32
)(*itr
).second
->GetEffIndex());
15261 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
15262 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%d', '%d', '%d', '%d')",
15263 GetGUIDLow(), itr
->second
->GetCasterGUID(), (uint32
)(*itr
).second
->GetId(), (uint32
)(*itr
).second
->GetEffIndex(), (*itr
).second
->GetModifier()->m_amount
,int((*itr
).second
->GetAuraMaxDuration()),int((*itr
).second
->GetAuraDuration()),int((*itr
).second
->m_procCharges
));
15268 void Player::_SaveInventory()
15270 // force items in buyback slots to new state
15271 // and remove those that aren't already
15272 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15274 Item
*item
= m_items
[i
];
15275 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15276 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15277 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15278 m_items
[i
]->FSetState(ITEM_NEW
);
15281 // update enchantment durations
15282 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15284 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15288 if (m_itemUpdateQueue
.empty()) return;
15290 // do not save if the update queue is corrupt
15291 bool error
= false;
15292 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15294 Item
*item
= m_itemUpdateQueue
[i
];
15295 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15296 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15300 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());
15303 else if (test
!= item
)
15305 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());
15312 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15313 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15317 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15319 Item
*item
= m_itemUpdateQueue
[i
];
15320 if(!item
) continue;
15322 Bag
*container
= item
->GetContainer();
15323 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15325 switch(item
->GetState())
15328 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());
15331 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());
15334 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15336 case ITEM_UNCHANGED
:
15340 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15342 m_itemUpdateQueue
.clear();
15345 void Player::_SaveMail()
15347 if (!m_mailsLoaded
)
15350 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
15353 if (m
->state
== MAIL_STATE_CHANGED
)
15355 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'",
15356 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15357 if(m
->removedItems
.size())
15359 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15360 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15361 m
->removedItems
.clear();
15363 m
->state
= MAIL_STATE_UNCHANGED
;
15365 else if (m
->state
== MAIL_STATE_DELETED
)
15368 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15369 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15371 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15372 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15373 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15377 //deallocate deleted mails...
15378 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15380 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15385 itr
= m_mail
.begin();
15391 m_mailsUpdated
= false;
15394 void Player::_SaveQuestStatus()
15396 // we don't need transactions here.
15397 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15399 switch (i
->second
.uState
)
15402 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15403 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15404 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]);
15406 case QUEST_CHANGED
:
15407 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' ",
15408 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
);
15410 case QUEST_UNCHANGED
:
15413 i
->second
.uState
= QUEST_UNCHANGED
;
15417 void Player::_SaveDailyQuestStatus()
15419 if(!m_DailyQuestChanged
)
15422 m_DailyQuestChanged
= false;
15424 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15426 // we don't need transactions here.
15427 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15428 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15429 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15430 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15431 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15434 void Player::_SaveReputation()
15436 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15438 if (itr
->second
.Changed
)
15440 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15441 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
);
15442 itr
->second
.Changed
= false;
15447 void Player::_SaveSpells()
15449 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
15452 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15453 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15454 if (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15455 CharacterDatabase
.PExecute("INSERT INTO character_spell (guid,spell,slot,active,disabled) VALUES ('%u', '%u', '%u','%u','%u')", GetGUIDLow(), itr
->first
, itr
->second
->slotId
,itr
->second
->active
? 1 : 0,itr
->second
->disabled
? 1 : 0);
15457 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15458 _removeSpell(itr
->first
);
15460 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15464 void Player::_SaveTutorials()
15466 if(!m_TutorialsChanged
)
15470 // it's better than rebuilding indexes multiple times
15471 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15474 Rows
= result
->Fetch()[0].GetUInt32();
15480 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'",
15481 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
);
15485 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]);
15488 m_TutorialsChanged
= false;
15491 void Player::outDebugValues() const
15493 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15496 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15497 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15498 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15499 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15500 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15501 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15502 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15503 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15504 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15505 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15506 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15507 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15510 /*********************************************************/
15511 /*** FLOOD FILTER SYSTEM ***/
15512 /*********************************************************/
15514 void Player::UpdateSpeakTime()
15516 // ignore chat spam protection for GMs in any mode
15517 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15520 time_t current
= time (NULL
);
15521 if(m_speakTime
> current
)
15523 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15528 if(m_speakCount
>= max_count
)
15530 // prevent overwrite mute time, if message send just before mutes set, for example.
15531 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15532 if(GetSession()->m_muteTime
< new_mute
)
15533 GetSession()->m_muteTime
= new_mute
;
15541 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15544 bool Player::CanSpeak() const
15546 return GetSession()->m_muteTime
<= time (NULL
);
15549 /*********************************************************/
15550 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15551 /*********************************************************/
15553 void Player::SendAttackSwingNotInRange()
15555 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15556 GetSession()->SendPacket( &data
);
15559 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15561 std::ostringstream ss
;
15562 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15563 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15564 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15565 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15566 sLog
.outDebug(ss
.str().c_str());
15567 CharacterDatabase
.Execute(ss
.str().c_str());
15570 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15572 std::ostringstream ss2
;
15573 ss2
<<"UPDATE characters SET data='";
15575 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15577 ss2
<<tokens
[i
]<<" ";
15579 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15581 return CharacterDatabase
.Execute(ss2
.str().c_str());
15584 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15587 snprintf(buf
,11,"%u",value
);
15589 if(index
>= tokens
.size())
15592 tokens
[index
] = buf
;
15595 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15598 if(!LoadValuesArrayFromDB(tokens
,guid
))
15601 if(index
>= tokens
.size())
15605 snprintf(buf
,11,"%u",value
);
15606 tokens
[index
] = buf
;
15608 SaveValuesArrayInDB(tokens
,guid
);
15611 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15614 memcpy(&temp
, &value
, sizeof(value
));
15615 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15618 void Player::SendAttackSwingNotStanding()
15620 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15621 GetSession()->SendPacket( &data
);
15624 void Player::SendAttackSwingDeadTarget()
15626 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15627 GetSession()->SendPacket( &data
);
15630 void Player::SendAttackSwingCantAttack()
15632 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15633 GetSession()->SendPacket( &data
);
15636 void Player::SendAttackSwingCancelAttack()
15638 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15639 GetSession()->SendPacket( &data
);
15642 void Player::SendAttackSwingBadFacingAttack()
15644 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15645 GetSession()->SendPacket( &data
);
15648 void Player::SendAutoRepeatCancel()
15650 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15651 data
.append(GetPackGUID()); // may be it's target guid
15652 GetSession()->SendPacket( &data
);
15655 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
15657 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
15660 GetSession()->SendPacket( &data
);
15662 SendMessageToSet( &data
, true );
15665 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15667 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15669 data
<< Experience
;
15670 GetSession()->SendPacket(&data
);
15673 void Player::SendDungeonDifficulty(bool IsInGroup
)
15675 uint8 val
= 0x00000001;
15676 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15677 data
<< (uint32
)GetDifficulty();
15678 data
<< uint32(val
);
15679 data
<< uint32(IsInGroup
);
15680 GetSession()->SendPacket(&data
);
15683 void Player::SendResetFailedNotify(uint32 mapid
)
15685 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15686 data
<< uint32(mapid
);
15687 GetSession()->SendPacket(&data
);
15690 /// Reset all solo instances and optionally send a message on success for each
15691 void Player::ResetInstances(uint8 method
)
15693 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15695 // we assume that when the difficulty changes, all instances that can be reset will be
15696 uint8 dif
= GetDifficulty();
15698 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15700 InstanceSave
*p
= itr
->second
.save
;
15701 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15702 if(!entry
|| !p
->CanReset())
15708 if(method
== INSTANCE_RESET_ALL
)
15710 // the "reset all instances" method can only reset normal maps
15711 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15718 // if the map is loaded, reset it
15719 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15720 if(map
&& map
->IsDungeon())
15721 ((InstanceMap
*)map
)->Reset(method
);
15723 // since this is a solo instance there should not be any players inside
15724 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15725 SendResetInstanceSuccess(p
->GetMapId());
15728 m_boundInstances
[dif
].erase(itr
++);
15730 // the following should remove the instance save from the manager and delete it as well
15731 p
->RemovePlayer(this);
15735 void Player::SendResetInstanceSuccess(uint32 MapId
)
15737 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
15739 GetSession()->SendPacket(&data
);
15742 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
15744 // TODO: find what other fail reasons there are besides players in the instance
15745 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
15748 GetSession()->SendPacket(&data
);
15751 /*********************************************************/
15752 /*** Update timers ***/
15753 /*********************************************************/
15755 ///checks the 15 afk reports per 5 minutes limit
15756 void Player::UpdateAfkReport(time_t currTime
)
15758 if(m_bgAfkReportedTimer
<= currTime
)
15760 m_bgAfkReportedCount
= 0;
15761 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
15765 void Player::UpdateContestedPvP(uint32 diff
)
15767 if(!m_contestedPvPTimer
||isInCombat())
15769 if(m_contestedPvPTimer
<= diff
)
15771 ResetContestedPvP();
15774 m_contestedPvPTimer
-= diff
;
15777 void Player::UpdatePvPFlag(time_t currTime
)
15781 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
15787 void Player::UpdateDuelFlag(time_t currTime
)
15789 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
15792 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
15793 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
15795 duel
->startTimer
= 0;
15796 duel
->startTime
= currTime
;
15797 duel
->opponent
->duel
->startTimer
= 0;
15798 duel
->opponent
->duel
->startTime
= currTime
;
15801 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
15806 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
15808 //returning of reagents only for players, so best done here
15809 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
15810 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
15814 for(uint32 i
= 0; i
< 7; ++i
)
15816 if(spellInfo
->Reagent
[i
] > 0)
15818 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15819 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
15820 if( msg
== EQUIP_ERR_OK
)
15822 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
15824 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
15829 m_temporaryUnsummonedPetNumber
= 0;
15832 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
15835 // only if current pet in slot
15836 switch(pet
->getPetType())
15842 m_guardianPets
.erase(pet
->GetGUID());
15845 if(GetPetGUID()==pet
->GetGUID())
15854 switch(pet
->GetEntry())
15856 //warlock pets except imp are removed(?) when logging out
15861 mode
= PET_SAVE_NOT_IN_SLOT
;
15866 pet
->SavePetToDB(mode
);
15868 pet
->CleanupsBeforeDelete();
15869 pet
->AddObjectToRemoveList();
15870 pet
->m_removed
= true;
15872 if(pet
->isControlled())
15874 WorldPacket
data(SMSG_PET_SPELLS
, 8);
15877 GetSession()->SendPacket(&data
);
15880 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
15884 void Player::RemoveMiniPet()
15886 if(Pet
* pet
= GetMiniPet())
15888 pet
->Remove(PET_SAVE_AS_DELETED
);
15893 Pet
* Player::GetMiniPet()
15897 return ObjectAccessor::GetPet(m_miniPet
);
15900 void Player::RemoveGuardians()
15902 while(!m_guardianPets
.empty())
15904 uint64 guid
= *m_guardianPets
.begin();
15905 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
15906 pet
->Remove(PET_SAVE_AS_DELETED
);
15908 m_guardianPets
.erase(guid
);
15912 bool Player::HasGuardianWithEntry(uint32 entry
)
15914 // pet guid middle part is entry (and creature also)
15915 // and in guardian list must be guardians with same entry _always_
15916 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
15917 if(GUID_ENPART(*itr
)==entry
)
15923 void Player::Uncharm()
15925 Unit
* charm
= GetCharm();
15929 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
15930 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
15933 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, std::string text
, uint32 language
) const
15935 *data
<< (uint8
)msgtype
;
15936 *data
<< (uint32
)language
;
15937 *data
<< (uint64
)GetGUID();
15938 *data
<< (uint32
)language
; //language 2.1.0 ?
15939 *data
<< (uint64
)GetGUID();
15940 *data
<< (uint32
)(text
.length()+1);
15942 *data
<< (uint8
)chatTag();
15945 void Player::Say(const std::string text
, const uint32 language
)
15947 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15948 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
15949 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
15952 void Player::Yell(const std::string text
, const uint32 language
)
15954 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15955 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
15956 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
15959 void Player::TextEmote(const std::string text
)
15961 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15962 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
15963 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
15966 void Player::Whisper(std::string text
, uint32 language
,uint64 receiver
)
15968 if (language
!= LANG_ADDON
) // if not addon data
15969 language
= LANG_UNIVERSAL
; // whispers should always be readable
15971 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
15973 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15974 if(!rPlayer
->isDND() || isGameMaster())
15976 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15977 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
15978 rPlayer
->GetSession()->SendPacket(&data
);
15980 data
.Initialize(SMSG_MESSAGECHAT
, 200);
15981 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
15982 GetSession()->SendPacket(&data
);
15986 // announce to player that player he is whispering to is dnd and cannot receive his message
15987 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
15990 if(!isAcceptWhispers())
15992 SetAcceptWhispers(true);
15993 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
15996 // announce to player that player he is whispering to is afk
15997 if(rPlayer
->isAFK())
15998 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16000 // if player whisper someone, auto turn of dnd to be able to receive an answer
16001 if(isDND() && !rPlayer
->isGameMaster())
16005 void Player::PetSpellInitialize()
16007 Pet
* pet
= GetPet();
16013 sLog
.outDebug("Pet Spells Groups");
16015 CreatureInfo
const *cinfo
= pet
->GetCreatureInfo();
16017 if(pet
->isControlled() && (pet
->getPetType() == HUNTER_PET
|| cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
))
16019 for(PetSpellMap::iterator itr
= pet
->m_spells
.begin();itr
!= pet
->m_spells
.end();itr
++)
16021 if(itr
->second
->state
== PETSPELL_REMOVED
)
16027 // first line + actionbar + spellcount + spells + last adds
16028 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);
16030 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16033 data
<< uint64(pet
->GetGUID());
16034 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16035 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16038 for(uint32 i
= 0; i
< 10; i
++) //40
16040 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16043 data
<< uint8(addlist
); //1
16045 if(addlist
&& pet
->isControlled())
16047 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16049 if(itr
->second
->state
== PETSPELL_REMOVED
)
16052 data
<< uint16(itr
->first
);
16053 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16057 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
16058 uint8 count
= 3; //1+8+8+8=25
16060 // if count = 0, then end of packet...
16062 // uint32 value is spell id...
16063 // uint64 value is constant 0, unknown...
16064 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16065 //data << uint32(0x5fd1) << uint64(0); // if count = 2
16066 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
16067 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
16069 GetSession()->SendPacket(&data
);
16073 void Player::PossessSpellInitialize()
16075 Unit
* charm
= GetCharm();
16080 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16084 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16089 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16092 data
<< uint64(charm
->GetGUID());
16093 data
<< uint32(0x00000000);
16094 data
<< uint8(0) << uint8(0) << uint16(0);
16097 for(uint32 i
= 0; i
< 10; i
++) //40
16099 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16102 data
<< uint8(addlist
); //1
16106 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16107 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
16108 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
16110 GetSession()->SendPacket(&data
);
16113 void Player::CharmSpellInitialize()
16115 Unit
* charm
= GetCharm();
16120 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16123 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16129 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16131 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16133 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16135 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16137 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16143 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16145 data
<< (uint64
)charm
->GetGUID() << uint32(0x00000000);
16147 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16148 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16150 data
<< uint8(0) << uint8(0);
16155 for(uint32 i
= 0; i
< 10; i
++) //40
16157 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16160 data
<< uint8(addlist
); //1
16164 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16166 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16167 if(cspell
->spellId
)
16169 data
<< uint16(cspell
->spellId
);
16170 data
<< uint16(cspell
->active
);
16177 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
16178 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
16179 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
16181 GetSession()->SendPacket(&data
);
16184 int32
Player::GetTotalFlatMods(uint32 spellId
, SpellModOp op
)
16186 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16187 if (!spellInfo
) return 0;
16189 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16191 SpellModifier
*mod
= *itr
;
16193 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16196 if (mod
->type
== SPELLMOD_FLAT
)
16197 total
+= mod
->value
;
16202 int32
Player::GetTotalPctMods(uint32 spellId
, SpellModOp op
)
16204 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16205 if (!spellInfo
) return 0;
16207 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16209 SpellModifier
*mod
= *itr
;
16211 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16214 if (mod
->type
== SPELLMOD_PCT
)
16215 total
+= mod
->value
;
16220 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16222 if (!mod
|| !spellInfo
)
16225 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16227 // prevent apply to any spell except spell that trigger expire
16230 if(mod
->lastAffected
!= spell
)
16233 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16237 return spellmgr
.IsAffectedBySpell(spellInfo
,mod
->spellId
,mod
->effectId
,mod
->mask
);
16240 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16242 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16244 for(int eff
=0;eff
<64;++eff
)
16246 uint64 _mask
= uint64(1) << eff
;
16247 if ( mod
->mask
& _mask
)
16250 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16252 if ((*itr
)->type
== mod
->type
&& (*itr
)->mask
& _mask
)
16253 val
+= (*itr
)->value
;
16255 val
+= apply
? mod
->value
: -(mod
->value
);
16256 WorldPacket
data(Opcode
, (1+1+4));
16257 data
<< uint8(eff
);
16258 data
<< uint8(mod
->op
);
16259 data
<< int32(val
);
16260 SendDirectMessage(&data
);
16265 m_spellMods
[mod
->op
].push_back(mod
);
16268 if (mod
->charges
== -1)
16269 --m_SpellModRemoveCount
;
16270 m_spellMods
[mod
->op
].remove(mod
);
16275 void Player::RemoveSpellMods(Spell
const* spell
)
16277 if(!spell
|| (m_SpellModRemoveCount
== 0))
16280 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16282 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16284 SpellModifier
*mod
= *itr
;
16287 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16289 RemoveAurasDueToSpell(mod
->spellId
);
16290 if (m_spellMods
[i
].empty())
16293 itr
= m_spellMods
[i
].begin();
16299 // send Proficiency
16300 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16302 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16303 data
<< pr1
<< pr2
;
16304 GetSession()->SendPacket (&data
);
16307 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16309 QueryResult
*result
= NULL
;
16311 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16313 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16316 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.
16317 { // and SendPetitionQueryOpcode reads data from the DB
16318 Field
*fields
= result
->Fetch();
16319 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16320 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16322 // send update if charter owner in game
16323 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16325 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16327 } while ( result
->NextRow() );
16332 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16334 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16337 CharacterDatabase
.BeginTransaction();
16340 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16341 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16345 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16346 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16348 CharacterDatabase
.CommitTransaction();
16351 void Player::SetRestBonus (float rest_bonus_new
)
16353 // Prevent resting on max level
16354 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16355 rest_bonus_new
= 0;
16357 if(rest_bonus_new
< 0)
16358 rest_bonus_new
= 0;
16360 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16362 if(rest_bonus_new
> rest_bonus_max
)
16363 m_rest_bonus
= rest_bonus_max
;
16365 m_rest_bonus
= rest_bonus_new
;
16367 // update data for client
16368 if(m_rest_bonus
>10)
16369 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16370 else if(m_rest_bonus
<=1)
16371 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16374 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16377 void Player::HandleStealthedUnitsDetection()
16379 std::list
<Unit
*> stealthedUnits
;
16381 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16383 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16384 cell
.SetNoCreate();
16386 MaNGOS::AnyStealthedCheck u_check
;
16387 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(stealthedUnits
, u_check
);
16389 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16390 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16392 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16393 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *MapManager::Instance().GetMap(GetMapId(), this));
16394 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *MapManager::Instance().GetMap(GetMapId(), this));
16396 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16400 i
= stealthedUnits
.erase(i
);
16404 if ((*i
)->isVisibleForOrDetect(this,true))
16407 (*i
)->SendUpdateToPlayer(this);
16408 m_clientGUIDs
.insert((*i
)->GetGUID());
16410 #ifdef MANGOS_DEBUG
16411 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16412 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16415 // target aura duration for caster show only if target exist at caster client
16416 // send data at target visibility change (adding to client)
16417 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16418 SendAurasForTarget(*i
);
16420 i
= stealthedUnits
.erase(i
);
16428 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16430 if(nodes
.size() < 2)
16433 // not let cheating with start flight mounted
16436 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16437 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16438 GetSession()->SendPacket(&data
);
16442 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16444 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16445 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16446 GetSession()->SendPacket(&data
);
16450 // 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
16451 if(GetSession()->isLogingOut() ||
16452 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16453 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16454 IsNonMeleeSpellCasted(false) ||
16457 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16458 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16459 GetSession()->SendPacket(&data
);
16463 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16466 uint32 sourcenode
= nodes
[0];
16468 // starting node too far away (cheat?)
16469 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16470 if( !node
|| node
->map_id
!= GetMapId() ||
16471 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16472 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16473 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16474 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16476 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16477 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16478 GetSession()->SendPacket(&data
);
16482 // Prepare to flight start now
16484 // stop combat at start taxi flight if any
16487 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16490 // clean not finished taxi path if any
16491 m_taxi
.ClearTaxiDestinations();
16493 // 0 element current node
16494 m_taxi
.AddTaxiDestination(sourcenode
);
16496 // fill destinations path tail
16497 uint32 sourcepath
= 0;
16498 uint32 totalcost
= 0;
16500 uint32 prevnode
= sourcenode
;
16501 uint32 lastnode
= 0;
16503 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16507 lastnode
= nodes
[i
];
16508 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16512 m_taxi
.ClearTaxiDestinations();
16518 if(prevnode
== sourcenode
)
16521 m_taxi
.AddTaxiDestination(lastnode
);
16523 prevnode
= lastnode
;
16526 if(!mount_id
) // if not provide then attempt use default.
16527 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16529 if (mount_id
== 0 || sourcepath
== 0)
16531 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16532 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16533 GetSession()->SendPacket(&data
);
16534 m_taxi
.ClearTaxiDestinations();
16538 uint32 money
= GetMoney();
16542 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16545 if(money
< totalcost
)
16547 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16548 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16549 GetSession()->SendPacket(&data
);
16550 m_taxi
.ClearTaxiDestinations();
16554 //Checks and preparations done, DO FLIGHT
16555 ModifyMoney(-(int32
)totalcost
);
16557 // prevent stealth flight
16558 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16560 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16561 data
<< uint32(ERR_TAXIOK
);
16562 GetSession()->SendPacket(&data
);
16564 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16566 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16571 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16573 // last check 2.0.10
16574 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16576 data
<< uint8(0x0); // flags (0x1, 0x2)
16577 time_t curTime
= time(NULL
);
16578 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16580 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16582 uint32 unSpellId
= itr
->first
;
16583 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16590 // Not send cooldown for this spells
16591 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16594 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16597 data
<< unTimeMs
; // in m.secs
16598 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
16601 GetSession()->SendPacket(&data
);
16604 void Player::InitDataForForm(bool reapplyMods
)
16606 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16607 if(ssEntry
&& ssEntry
->attackSpeed
)
16609 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16610 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16611 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16614 SetRegularAttackTime();
16620 if(getPowerType()!=POWER_ENERGY
)
16621 setPowerType(POWER_ENERGY
);
16625 case FORM_DIREBEAR
:
16627 if(getPowerType()!=POWER_RAGE
)
16628 setPowerType(POWER_RAGE
);
16631 default: // 0, for example
16633 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16634 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16635 setPowerType(Powers(cEntry
->powerType
));
16640 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16642 UpdateEquipSpellsAtFormChange();
16644 UpdateAttackPowerAndDamage();
16645 UpdateAttackPowerAndDamage(true);
16648 // Return true is the bought item has a max count to force refresh of window by caller
16649 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16651 // cheating attempt
16652 if(count
< 1) count
= 1;
16657 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16660 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16664 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16667 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16668 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16672 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16673 if(!vItems
|| vItems
->Empty())
16675 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16679 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16680 if(vendor_slot
>= vItems
->GetItemCount())
16682 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16686 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16688 // check current item amount if it limited
16689 if( crItem
->maxcount
!= 0 )
16691 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16693 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16698 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16700 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16704 if(crItem
->ExtendedCost
)
16706 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16709 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16713 // honor points price
16714 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16716 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16720 // arena points price
16721 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16723 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16728 for (uint8 i
= 0; i
< 5; ++i
)
16730 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16732 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16737 // check for personal arena rating requirement
16738 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16740 // probably not the proper equip err
16741 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
16746 uint32 price
= pProto
->BuyPrice
* count
;
16748 // reputation discount
16749 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
16751 if( GetMoney() < price
)
16753 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
16757 uint8 bag
= 0; // init for case invalid bagGUID
16759 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
16762 if( bagguid
== GetGUID() )
16764 bag
= INVENTORY_SLOT_BAG_0
;
16768 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
16770 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
16773 if( bagguid
== pBag
->GetGUID() )
16783 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
16785 ItemPosCountVec dest
;
16786 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
16787 if( msg
!= EQUIP_ERR_OK
)
16789 SendEquipError( msg
, NULL
, NULL
);
16793 ModifyMoney( -(int32
)price
);
16794 if(crItem
->ExtendedCost
) // case for new honor system
16796 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16797 if(iece
->reqhonorpoints
)
16798 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
16799 if(iece
->reqarenapoints
)
16800 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
16801 for (uint8 i
= 0; i
< 5; ++i
)
16803 if(iece
->reqitem
[i
])
16804 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
16808 if(Item
*it
= StoreNewItem( dest
, item
, true ))
16810 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16812 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16813 data
<< pCreature
->GetGUID();
16814 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16815 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16816 data
<< (uint32
)count
;
16817 GetSession()->SendPacket(&data
);
16819 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16822 else if( IsEquipmentPos( bag
, slot
) )
16825 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, pProto
->BuyCount
* count
, false );
16826 if( msg
!= EQUIP_ERR_OK
)
16828 SendEquipError( msg
, NULL
, NULL
);
16832 ModifyMoney( -(int32
)price
);
16833 if(crItem
->ExtendedCost
) // case for new honor system
16835 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16836 if(iece
->reqhonorpoints
)
16837 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
16838 if(iece
->reqarenapoints
)
16839 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
16840 for (uint8 i
= 0; i
< 5; ++i
)
16842 if(iece
->reqitem
[i
])
16843 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
16847 if(Item
*it
= EquipNewItem( dest
, item
, pProto
->BuyCount
* count
, true ))
16849 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16851 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16852 data
<< pCreature
->GetGUID();
16853 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16854 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16855 data
<< (uint32
)count
;
16856 GetSession()->SendPacket(&data
);
16858 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16860 AutoUnequipOffhandIfNeed();
16865 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
16869 return crItem
->maxcount
!=0;
16872 uint32
Player::GetMaxPersonalArenaRatingRequirement()
16874 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16875 // the personal rating of the arena team must match the required limit as well
16876 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16877 uint32 max_personal_rating
= 0;
16878 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
16880 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
16882 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
16883 uint32 t_rating
= at
->GetRating();
16884 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
16885 if(max_personal_rating
< p_rating
)
16886 max_personal_rating
= p_rating
;
16889 return max_personal_rating
;
16892 void Player::UpdateHomebindTime(uint32 time
)
16894 // GMs never get homebind timer online
16895 if (m_InstanceValid
|| isGameMaster())
16897 if(m_HomebindTimer
) // instance valid, but timer not reset
16900 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16903 GetSession()->SendPacket(&data
);
16905 // instance is valid, reset homebind timer
16906 m_HomebindTimer
= 0;
16908 else if (m_HomebindTimer
> 0)
16910 if (time
>= m_HomebindTimer
)
16912 // teleport to homebind location
16913 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
16916 m_HomebindTimer
-= time
;
16920 // instance is invalid, start homebind timer
16921 m_HomebindTimer
= 60000;
16922 // send message to player
16923 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16924 data
<< m_HomebindTimer
;
16926 GetSession()->SendPacket(&data
);
16927 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16931 void Player::UpdatePvP(bool state
, bool ovrride
)
16933 if(!state
|| ovrride
)
16936 if(Pet
* pet
= GetPet())
16937 pet
->SetPvP(state
);
16938 if(Unit
* charmed
= GetCharm())
16939 charmed
->SetPvP(state
);
16941 pvpInfo
.endTimer
= 0;
16945 if(pvpInfo
.endTimer
!= 0)
16946 pvpInfo
.endTimer
= time(NULL
);
16951 if(Pet
* pet
= GetPet())
16952 pet
->SetPvP(state
);
16953 if(Unit
* charmed
= GetCharm())
16954 charmed
->SetPvP(state
);
16959 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
16963 sc
.itemid
= itemid
;
16964 m_spellCooldowns
[spellid
] = sc
;
16967 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
16969 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
16972 // Get spell cooldwn
16973 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
16975 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
16979 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
16981 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
16982 data
<< spellInfo
->Id
;
16984 SendDirectMessage(&data
);
16986 //slot to be excluded while counting
16987 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
16989 if(!enchantmentcondition
)
16992 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
16997 uint8 curcount
[4] = {0, 0, 0, 0};
16999 //counting current equipped gem colors
17000 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17004 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17005 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17007 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17009 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17013 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17017 uint32 gemid
= enchantEntry
->GemID
;
17021 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17025 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17029 uint8 GemColor
= gemProperty
->color
;
17031 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17033 if(tmpcolormask
& GemColor
)
17040 bool activate
= true;
17042 for(int i
= 0; i
< 5; i
++)
17044 if(!Condition
->Color
[i
])
17047 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17049 // if have <CompareColor> use them as count, else use <value> from Condition
17050 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17052 switch(Condition
->Comparator
[i
])
17054 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17055 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17057 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17058 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17060 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17061 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17066 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");
17071 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17073 //cycle all equipped items
17074 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17076 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17077 if(slot
== exceptslot
)
17080 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17082 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17085 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17087 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17091 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17095 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17098 //was enchant active with/without item?
17099 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17100 //should it now be?
17101 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17103 // ignore item gem conditions
17104 //if state changed, (dis)apply enchant
17105 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17112 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17113 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17115 //cycle all equipped items
17116 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17118 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17119 if(slot
== exceptslot
)
17122 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17124 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17127 //cycle all (gem)enchants
17128 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17130 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17131 if(!enchant_id
) //if no enchant go to next enchant(slot)
17134 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17138 //only metagems to be (de)activated, so only enchants with condition
17139 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17141 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17146 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17148 if(BattleGround
*bg
= GetBattleGround())
17150 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
17152 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17154 // call after remove to be sure that player resurrected for correct cast
17156 CastSpell(this, 26013, true); // Deserter
17160 bool Player::CanJoinToBattleground() const
17162 // check Deserter debuff
17163 if(GetDummyAura(26013))
17169 bool Player::CanReportAfkDueToLimit()
17171 // a player can complain about 15 people per 5 minutes
17172 if(m_bgAfkReportedCount
>= 15)
17174 ++m_bgAfkReportedCount
;
17178 ///This player has been blamed to be inactive in a battleground
17179 void Player::ReportedAfkBy(Player
* reporter
)
17181 BattleGround
*bg
= GetBattleGround();
17182 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17185 // check if player has 'Idle' or 'Inactive' debuff
17186 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17188 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17189 // 3 players have to complain to apply debuff
17190 if(m_bgAfkReporter
.size() >= 3)
17192 // cast 'Idle' spell
17193 CastSpell(this, 43680, true);
17194 m_bgAfkReporter
.clear();
17199 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17201 // gamemaster in GM mode see all, including ghosts
17202 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17205 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17206 if (InBattleGround())
17208 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17213 // Live player see live player or dead player with not realized corpse
17214 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17216 return isAlive() || m_deathTimer
> 0;
17219 // Ghost see other friendly ghosts, that's for sure
17220 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17223 // Dead player see live players near own corpse
17226 Corpse
*corpse
= pl
->GetCorpse();
17229 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17230 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17235 // and not see any other
17239 bool Player::IsVisibleGloballyFor( Player
* u
) const
17244 // Always can see self
17248 // Visible units, always are visible for all players
17249 if (GetVisibility() == VISIBILITY_ON
)
17252 // GMs are visible for higher gms (or players are visible for gms)
17253 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17254 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17256 // non faction visibility non-breakable for non-GMs
17257 if (GetVisibility() == VISIBILITY_OFF
)
17260 // non-gm stealth/invisibility not hide from global player lists
17264 void Player::UpdateVisibilityOf(WorldObject
* target
)
17266 if(HaveAtClient(target
))
17268 if(!target
->isVisibleForInState(this,true))
17270 target
->DestroyForPlayer(this);
17271 m_clientGUIDs
.erase(target
->GetGUID());
17273 #ifdef MANGOS_DEBUG
17274 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17275 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17281 if(target
->isVisibleForInState(this,false))
17283 target
->SendUpdateToPlayer(this);
17284 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17285 m_clientGUIDs
.insert(target
->GetGUID());
17287 #ifdef MANGOS_DEBUG
17288 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17289 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17292 // target aura duration for caster show only if target exist at caster client
17293 // send data at target visibility change (adding to client)
17294 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17295 SendAurasForTarget((Unit
*)target
);
17297 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17298 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17304 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17306 s64
.insert(target
->GetGUID());
17310 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17312 if(!target
->IsTransport())
17313 s64
.insert(target
->GetGUID());
17317 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17319 if(HaveAtClient(target
))
17321 if(!target
->isVisibleForInState(this,true))
17323 target
->BuildOutOfRangeUpdateBlock(&data
);
17324 m_clientGUIDs
.erase(target
->GetGUID());
17326 #ifdef MANGOS_DEBUG
17327 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17328 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
));
17334 if(target
->isVisibleForInState(this,false))
17336 visibleNow
.insert(target
);
17337 target
->BuildUpdate(data_updates
);
17338 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17339 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17341 #ifdef MANGOS_DEBUG
17342 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17343 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
));
17349 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17350 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17351 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17352 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17353 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17355 void Player::InitPrimaryProffesions()
17357 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17360 void Player::SendComboPoints()
17362 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17365 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17366 data
.append(combotarget
->GetPackGUID());
17367 data
<< uint8(m_comboPoints
);
17368 GetSession()->SendPacket(&data
);
17372 void Player::AddComboPoints(Unit
* target
, int8 count
)
17377 // without combo points lost (duration checked in aura)
17378 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17380 if(target
->GetGUID() == m_comboTarget
)
17382 m_comboPoints
+= count
;
17387 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17388 target
->RemoveComboPointHolder(GetGUIDLow());
17390 m_comboTarget
= target
->GetGUID();
17391 m_comboPoints
= count
;
17393 target
->AddComboPointHolder(GetGUIDLow());
17396 if (m_comboPoints
> 5) m_comboPoints
= 5;
17397 if (m_comboPoints
< 0) m_comboPoints
= 0;
17402 void Player::ClearComboPoints()
17407 // without combopoints lost (duration checked in aura)
17408 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17414 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17415 target
->RemoveComboPointHolder(GetGUIDLow());
17420 void Player::SetGroup(Group
*group
, int8 subgroup
)
17422 if(group
== NULL
) m_group
.unlink();
17425 // never use SetGroup without a subgroup unless you specify NULL for group
17426 assert(subgroup
>= 0);
17427 m_group
.link(group
, this);
17428 m_group
.setSubGroup((uint8
)subgroup
);
17432 void Player::SendInitialPacketsBeforeAddToMap()
17434 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17435 data
<< uint32(0); // unknown, may be rest state time or expirience
17436 GetSession()->SendPacket(&data
);
17439 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17440 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17441 data
<< (uint32
) m_homebindMapId
;
17442 data
<< (uint32
) m_homebindZoneId
;
17443 GetSession()->SendPacket(&data
);
17445 // SMSG_SET_PROFICIENCY
17446 // SMSG_UPDATE_AURA_DURATION
17449 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17450 for (int i
= 0; i
< 8; ++i
)
17451 data
<< uint32( GetTutorialInt(i
) );
17452 GetSession()->SendPacket(&data
);
17454 SendInitialSpells();
17456 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17457 data
<< uint32(0); // count, for(count) uint32;
17458 GetSession()->SendPacket(&data
);
17460 SendInitialActionButtons();
17461 SendInitialReputations();
17462 m_achievementMgr
.SendAllAchievementData();
17463 UpdateZone(GetZoneId());
17464 SendInitWorldStates();
17466 // SMSG_SET_AURA_SINGLE
17468 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17469 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17470 data
<< (float)0.01666667f
; // game speed
17471 GetSession()->SendPacket( &data
);
17473 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17474 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17475 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17478 void Player::SendInitialPacketsAfterAddToMap()
17480 CastSpell(this, 836, true); // LOGINEFFECT
17482 // set some aura effects that send packet to player client after add player to map
17483 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17484 // same auras state lost at far teleport, send it one more time in this case also
17485 static const AuraType auratypes
[] =
17487 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17488 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17489 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17491 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17493 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17494 if(!auraList
.empty())
17495 auraList
.front()->ApplyModifier(true,true);
17498 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17499 SetMovement(MOVE_ROOT
);
17501 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17502 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17504 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
17505 data
.append(GetPackGUID());
17507 SendMessageToSet(&data
,true);
17510 SendAurasForTarget(this);
17511 SendEnchantmentDurations(); // must be after add to map
17512 SendItemDurations(); // must be after add to map
17515 void Player::SendUpdateToOutOfRangeGroupMembers()
17517 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17519 if(Group
* group
= GetGroup())
17520 group
->UpdatePlayerOutOfRange(this);
17522 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17523 m_auraUpdateMask
= 0;
17524 if(Pet
*pet
= GetPet())
17525 pet
->ResetAuraUpdateMask();
17528 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
17530 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17531 data
<< uint32(mapid
);
17532 data
<< uint8(reason
); // transfer abort reason
17535 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
17536 case TRANSFER_ABORT_DIFFICULTY
:
17537 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
17538 data
<< uint8(arg
);
17541 GetSession()->SendPacket(&data
);
17544 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17546 // type of warning, based on the time remaining until reset
17549 type
= RAID_INSTANCE_WELCOME
;
17550 else if(time
> 900 && time
<= 3600)
17551 type
= RAID_INSTANCE_WARNING_HOURS
;
17552 else if(time
> 300 && time
<= 900)
17553 type
= RAID_INSTANCE_WARNING_MIN
;
17555 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17556 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17557 data
<< uint32(type
);
17558 data
<< uint32(mapid
);
17559 data
<< uint32(time
);
17560 GetSession()->SendPacket(&data
);
17563 void Player::ApplyEquipCooldown( Item
* pItem
)
17565 for(int i
= 0; i
<5; ++i
)
17567 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17570 if( !spellData
.SpellId
)
17573 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17574 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17577 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17579 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17580 data
<< pItem
->GetGUID();
17581 data
<< uint32(spellData
.SpellId
);
17582 GetSession()->SendPacket(&data
);
17586 void Player::resetSpells()
17588 // not need after this call
17589 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17591 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17592 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17595 // make full copy of map (spells removed and marked as deleted at another spell remove
17596 // and we can't use original map for safe iterative with visit each spell at loop end
17597 PlayerSpellMap smap
= GetSpellMap();
17599 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17600 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17602 learnDefaultSpells();
17603 learnQuestRewardedSpells();
17606 void Player::learnDefaultSpells(bool loading
)
17608 // learn default race/class spells
17609 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17610 std::list
<CreateSpellPair
>::const_iterator spell_itr
;
17611 for (spell_itr
= info
->spell
.begin(); spell_itr
!=info
->spell
.end(); ++spell_itr
)
17613 uint16 tspell
= spell_itr
->first
;
17616 sLog
.outDebug("PLAYER: Adding initial spell, id = %u",tspell
);
17617 if(loading
|| !spell_itr
->second
) // not care about passive spells or loading case
17618 addSpell(tspell
,spell_itr
->second
);
17619 else // but send in normal spell in game learn case
17620 learnSpell(tspell
);
17625 void Player::learnQuestRewardedSpells(Quest
const* quest
)
17627 uint32 spell_id
= quest
->GetRewSpellCast();
17629 // skip quests without rewarded spell
17633 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
17637 // check learned spells state
17638 bool found
= false;
17639 for(int i
=0; i
< 3; ++i
)
17641 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
17648 // skip quests with not teaching spell or already known spell
17652 // prevent learn non first rank unknown profession and second specialization for same profession)
17653 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
17654 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
17656 // not have first rank learned (unlearned prof?)
17657 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
17658 if( !HasSpell(first_spell
) )
17661 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
17666 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
17668 // search other specialization for same prof
17669 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17671 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
17674 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
17678 // compare only specializations
17679 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
17682 // compare same chain spells
17683 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
17686 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17687 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
17693 CastSpell( this, spell_id
, true);
17696 void Player::learnQuestRewardedSpells()
17698 // learn spells received from quest completing
17699 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
17701 // skip no rewarded quests
17702 if(!itr
->second
.m_rewarded
)
17705 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
17709 learnQuestRewardedSpells(quest
);
17713 void Player::learnSkillRewardedSpells(uint32 skill_id
)
17715 uint32 raceMask
= getRaceMask();
17716 uint32 classMask
= getClassMask();
17717 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
17719 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
17720 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
17722 // Check race if set
17723 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
17725 // Check class if set
17726 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
17729 if (SpellEntry
const* spellentry
= sSpellStore
.LookupEntry(pAbility
->spellId
))
17731 // Ok need learn spell
17732 learnSpell(pAbility
->spellId
);
17737 void Player::learnSkillRewardedSpells()
17739 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
17741 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
17744 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
17746 learnSkillRewardedSpells(pskill
);
17750 void Player::SendAurasForTarget(Unit
*target
)
17752 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
17753 data
.append(target
->GetPackGUID());
17755 for(Unit::AuraMap::const_iterator itr
= target
->GetAuras().begin(); itr
!= target
->GetAuras().end(); ++itr
)
17757 Aura
* aura
= itr
->second
;
17758 if(aura
->GetAuraSlot() >= MAX_AURAS
|| aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
17761 data
<< uint8(aura
->GetAuraSlot());
17762 data
<< uint32(aura
->GetId());
17766 uint8 auraFlags
= aura
->GetAuraFlags();
17767 data
<< uint8(auraFlags
); // flags
17768 data
<< uint8(aura
->GetAuraLevel()); // level
17769 data
<< uint8(aura
->m_procCharges
); // charges
17771 /*if(!(auraFlags & AFLAG_NOT_GUID))
17773 data << uint8(0) // packed GUID of someone (caster?)
17776 if(auraFlags
& AFLAG_DURATION
) // include aura duration
17778 data
<< uint32(aura
->GetAuraMaxDuration());
17779 data
<< uint32(aura
->GetAuraDuration());
17784 GetSession()->SendPacket(&data
);
17787 void Player::SetDailyQuestStatus( uint32 quest_id
)
17789 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17791 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
17793 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
17794 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
17795 m_DailyQuestChanged
= true;
17801 void Player::ResetDailyQuestStatus()
17803 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17804 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
17806 // DB data deleted in caller
17807 m_DailyQuestChanged
= false;
17808 m_lastDailyQuestTime
= 0;
17811 BattleGround
* Player::GetBattleGround() const
17813 if(GetBattleGroundId()==0)
17816 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
17819 bool Player::InArena() const
17821 BattleGround
*bg
= GetBattleGround();
17822 if(!bg
|| !bg
->isArena())
17828 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
17830 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(bgTypeId
);
17834 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
17840 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
17848 return 10*(queue_id
+1);
17851 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
17854 return 255; // hardcoded max level
17856 return 10*(queue_id
+2)-1;
17859 uint32
Player::GetBattleGroundQueueIdFromLevel() const
17861 uint32 level
= getLevel();
17864 else if (level
> 69)
17867 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17870 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
17872 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
17873 if(!vendor_faction
)
17876 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
17877 if(rank
<= REP_NEUTRAL
)
17880 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
17883 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
17885 uint32 racemask
= getRaceMask();
17886 uint32 classmask
= getClassMask();
17888 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
17889 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
17891 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
17893 // skip wrong race skills
17894 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
17897 // skip wrong class skills
17898 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
17904 bool Player::HasQuestForGO(int32 GOId
)
17906 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
17908 QuestStatusData qs
=i
->second
;
17909 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
17911 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
17915 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
17918 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
17920 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
17923 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
17931 void Player::UpdateForQuestsGO()
17933 if(m_clientGUIDs
.empty())
17937 WorldPacket packet
;
17938 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
17940 if(IS_GAMEOBJECT_GUID(*itr
))
17942 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
17944 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
17947 udata
.BuildPacket(&packet
);
17948 GetSession()->SendPacket(&packet
);
17951 void Player::SummonIfPossible(bool agree
)
17955 m_summon_expire
= 0;
17959 // expire and auto declined
17960 if(m_summon_expire
< time(NULL
))
17963 // stop taxi flight at summon
17966 GetMotionMaster()->MovementExpired();
17967 m_taxi
.ClearTaxiDestinations();
17970 // drop flag at summon
17971 if(BattleGround
*bg
= GetBattleGround())
17972 bg
->EventPlayerDroppedFlag(this);
17974 m_summon_expire
= 0;
17976 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
17979 void Player::RemoveItemDurations( Item
*item
)
17981 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
17985 m_itemDuration
.erase(itr
);
17991 void Player::AddItemDurations( Item
*item
)
17993 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
17995 m_itemDuration
.push_back(item
);
17996 item
->SendTimeUpdate(this);
18000 void Player::AutoUnequipOffhandIfNeed()
18002 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18006 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
18008 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
18011 ItemPosCountVec off_dest
;
18012 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18013 if( off_msg
== EQUIP_ERR_OK
)
18015 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18016 StoreItem( off_dest
, offItem
, true );
18020 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18024 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18026 if(spellInfo
->EquippedItemClass
< 0)
18029 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18030 // for optimize check 2 used cases only
18031 switch(spellInfo
->EquippedItemClass
)
18033 case ITEM_CLASS_WEAPON
:
18035 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18036 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18037 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18041 case ITEM_CLASS_ARMOR
:
18043 // tabard not have dependent spells
18044 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18045 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18046 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18049 // shields can be equipped to offhand slot
18050 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18051 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18054 // ranged slot can have some armor subclasses
18055 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18056 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18062 sLog
.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo
->EquippedItemClass
);
18069 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18071 AuraMap
& auras
= GetAuras();
18072 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18074 Aura
* aura
= itr
->second
;
18076 // skip passive (passive item dependent spells work in another way) and not self applied auras
18077 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18078 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18084 // skip if not item dependent or have alternative item
18085 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18091 // no alt item, remove aura, restart check
18092 RemoveAurasDueToSpell(aura
->GetId());
18093 itr
= auras
.begin();
18096 // currently casted spells can be dependent from item
18097 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18099 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18100 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18105 uint32
Player::GetResurrectionSpellId()
18107 // search priceless resurrection possabilities
18109 uint32 spell_id
= 0;
18110 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18111 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18113 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18114 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
== 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18116 switch((*itr
)->GetId())
18118 case 20707: spell_id
= 3026; break; // rank 1
18119 case 20762: spell_id
= 20758; break; // rank 2
18120 case 20763: spell_id
= 20759; break; // rank 3
18121 case 20764: spell_id
= 20760; break; // rank 4
18122 case 20765: spell_id
= 20761; break; // rank 5
18123 case 27239: spell_id
= 27240; break; // rank 6
18125 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18131 // Twisting Nether // prio: 2 (max)
18132 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18139 // Reincarnation (passive spell) // prio: 1
18140 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18146 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18148 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18150 // prepare data for near group iteration (PvP and !PvP cases)
18152 bool honored_kill
= false;
18154 if(Group
*pGroup
= GetGroup())
18157 uint32 sum_level
= 0;
18158 Player
* member_with_max_level
= NULL
;
18159 Player
* not_gray_member_with_max_level
= NULL
;
18161 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18163 if(member_with_max_level
)
18165 /// not get Xp in PvP or no not gray players in group
18166 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18168 /// skip in check PvP case (for speed, not used)
18169 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18170 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18171 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18173 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18175 Player
* pGroupGuy
= itr
->getSource();
18179 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18180 continue; // member (alive or dead) or his corpse at req. distance
18182 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18183 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18184 honored_kill
= true;
18186 // xp and reputation only in !PvP case
18189 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18191 // if is in dungeon then all receive full reputation at kill
18192 // rewarded any alive/dead/near_corpse group member
18193 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18195 // XP updated only for alive group member
18196 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18197 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18199 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18201 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18202 if(Pet
* pet
= pGroupGuy
->GetPet())
18203 pet
->GivePetXP(itr_xp
/2);
18206 // quest objectives updated only for alive group member or dead but with not released body
18207 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18209 // normal creature (not pet/etc) can be only in !PvP case
18210 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18211 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18217 else // if (!pGroup)
18219 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18221 // honor can be in PvP and !PvP (racial leader) cases
18222 if(RewardHonor(pVictim
,1))
18223 honored_kill
= true;
18225 // xp and reputation only in !PvP case
18228 RewardReputation(pVictim
,1);
18229 GiveXP(xp
, pVictim
);
18231 if(Pet
* pet
= GetPet())
18232 pet
->GivePetXP(xp
);
18234 // normal creature (not pet/etc) can be only in !PvP case
18235 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18236 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18239 return xp
|| honored_kill
;
18242 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18244 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18250 Corpse
* corpse
= GetCorpse();
18254 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18257 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18259 Item
* item
= GetWeaponForAttack(attType
,true);
18261 // unarmmed only with base attack
18262 if(attType
!= BASE_ATTACK
&& !item
)
18265 // weapon skill or (unarmed for base attack)
18266 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18267 return GetBaseSkillValue(skill
);
18270 void Player::ResurectUsingRequestData()
18272 ResurrectPlayer(0.0f
,false);
18274 if(GetMaxHealth() > m_resurrectHealth
)
18275 SetHealth( m_resurrectHealth
);
18277 SetHealth( GetMaxHealth() );
18279 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18280 SetPower(POWER_MANA
, m_resurrectMana
);
18282 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18284 SetPower(POWER_RAGE
, 0 );
18286 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18288 SpawnCorpseBones();
18290 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18293 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18295 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18296 data
.append(target
->GetPackGUID());
18297 data
<< uint8(allowMove
);
18298 GetSession()->SendPacket(&data
);
18301 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18303 // remove new continent flight forms
18304 if( !isGameMaster() &&
18305 GetVirtualMapForMapAndZone(GetMapId(),newZone
) != 530)
18307 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18308 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18311 // Some spells applied at enter into zone (with subzones)
18313 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18314 if ( newZone
== 2367 ) // Old Hillsbrad Foothills
18316 uint32 spellid
= 0;
18318 if( GetTeam() == HORDE
)
18319 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18320 // and some alliance races
18321 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18322 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
18324 if(spellid
&& !HasAura(spellid
,0) )
18325 CastSpell(this,spellid
,true);
18329 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18331 // remove auras from spells with area limitations
18332 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18334 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18335 if(!IsSpellAllowedInLocation(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
))
18341 // unmount if enter in this subzone
18343 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
18344 // Dragonmaw Illusion
18345 else if( newArea
== 3759 || newArea
== 3966 || newArea
== 3939 )
18347 if( GetDummyAura(40214) )
18349 if( !HasAura(40216,0) )
18350 CastSpell(this,40216,true);
18351 if( !HasAura(42016,0) )
18352 CastSpell(this,42016,true);
18357 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18359 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18360 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18362 return copseReclaimDelay
[0];
18365 time_t now
= time(NULL
);
18366 // 0..2 full period
18367 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18368 return copseReclaimDelay
[count
];
18371 void Player::UpdateCorpseReclaimDelay()
18373 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18375 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18376 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18379 time_t now
= time(NULL
);
18380 if(now
< m_deathExpireTime
)
18382 // full and partly periods 1..3
18383 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18384 if(count
< MAX_DEATH_COUNT
)
18385 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18387 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18390 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18393 void Player::SendCorpseReclaimDelay(bool load
)
18395 Corpse
* corpse
= GetCorpse();
18402 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18405 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18408 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18409 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18411 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18412 if(count
>=MAX_DEATH_COUNT
)
18413 count
= MAX_DEATH_COUNT
-1;
18418 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18420 time_t now
= time(NULL
);
18421 if(now
>= expected_time
)
18424 delay
= expected_time
-now
;
18427 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18429 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18430 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18431 data
<< uint32(delay
*1000);
18432 GetSession()->SendPacket( &data
);
18435 Player
* Player::GetNextRandomRaidMember(float radius
)
18437 Group
*pGroup
= GetGroup();
18441 std::vector
<Player
*> nearMembers
;
18442 nearMembers
.reserve(pGroup
->GetMembersCount());
18444 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18446 Player
* Target
= itr
->getSource();
18448 // IsHostileTo check duel and controlled by enemy
18449 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18450 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18451 nearMembers
.push_back(Target
);
18454 if (nearMembers
.empty())
18457 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18458 return nearMembers
[randTarget
];
18461 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18463 float water_z
= m
->GetWaterLevel(x
,y
);
18464 float height_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
18465 uint8 flag1
= m
->GetTerrainType(x
,y
);
18467 //!Underwater check, not in water if underground or above water level
18468 if (height_z
<= INVALID_HEIGHT
|| z
< (height_z
-2) || z
> (water_z
- 2) )
18469 m_isunderwater
&= 0x7A;
18470 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
18471 m_isunderwater
|= 0x01;
18473 //!in lava check, anywhere under lava level
18474 if ((height_z
<= INVALID_HEIGHT
|| z
< (height_z
- 0)) && (flag1
== 0x00) && IsInWater())
18475 m_isunderwater
|= 0x80;
18478 void Player::SetCanParry( bool value
)
18480 if(m_canParry
==value
)
18483 m_canParry
= value
;
18484 UpdateParryPercentage();
18487 void Player::SetCanBlock( bool value
)
18489 if(m_canBlock
==value
)
18492 m_canBlock
= value
;
18493 UpdateBlockPercentage();
18496 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
18498 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
18499 if(itr
->pos
== this->pos
)
18505 bool Player::isAllowUseBattleGroundObject()
18507 return ( //InBattleGround() && // in battleground - not need, check in other cases
18508 !IsMounted() && // not mounted
18509 !HasStealthAura() && // not stealthed
18510 !HasInvisibilityAura() && // not invisible
18511 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
18512 isAlive() // live player
18516 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
18518 uint32 level
= getLevel();
18520 if(level
> sGtBarberShopCostBaseStore
.GetNumRows())
18521 level
= GT_MAX_LEVEL
; // max level in this dbc
18523 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
18524 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
18525 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
18527 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
18530 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
18532 if(!bsc
) // shouldn't happen
18537 if(hairstyle
!= newhairstyle
)
18538 cost
+= bsc
->cost
; // full price
18540 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
18541 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
18543 if(facialhair
!= newfacialhair
)
18544 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
18546 return uint32(cost
);
18549 void Player::InitGlyphsForLevel()
18551 uint32 level
= getLevel();
18554 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18556 value
|= (0x01 | 0x02);
18566 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);