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 chrClass
, uint32 level
)
132 // capital and taxi hub masks
135 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
136 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF
: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
150 case CLASS_DEATH_KNIGHT
: // TODO: figure out initial known nodes
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race
))
157 case ALLIANCE
: SetTaximaskNode(100); break;
158 case HORDE
: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data
)
167 Tokens tokens
= StrSplit(data
, " ");
170 Tokens::iterator iter
;
171 for (iter
= tokens
.begin(), index
= 0;
172 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
174 // load and set bits only for existed taxi nodes
175 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
183 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
184 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
188 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
189 data
<< uint32(m_taximask
[i
]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values
)
195 ClearTaxiDestinations();
197 Tokens tokens
= StrSplit(values
," ");
199 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
201 uint32 node
= uint32(atol(iter
->c_str()));
202 AddTaxiDestination(node
);
205 if(m_TaxiDestinations
.empty())
209 if(m_TaxiDestinations
.size() < 2)
212 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
216 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
224 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
226 if(m_TaxiDestinations
.empty())
229 std::ostringstream ss
;
231 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
232 ss
<< m_TaxiDestinations
[i
] << " ";
237 uint32
PlayerTaxi::GetCurrentTaxiPath() const
239 if(m_TaxiDestinations
.size() < 2)
245 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
250 //== Player ====================================================
252 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
254 UpdateMask
Player::updateVisualBits
;
256 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this)
263 m_objectType
|= TYPEMASK_PLAYER
;
264 m_objectTypeId
= TYPEID_PLAYER
;
266 m_valuesCount
= PLAYER_END
;
273 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
274 SetAcceptTicket(true);
276 // players always accept
277 if(GetSession()->GetSecurity() == SEC_PLAYER
)
278 SetAcceptWhispers(true);
286 m_usedTalentCount
= 0;
289 m_weaponChangeTimer
= 0;
292 m_zoneUpdateTimer
= 0;
296 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
298 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
299 // this must help in case next save after mass player load after server startup
300 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
302 clearResurrectRequestData();
304 m_SpellModRemoveCount
= 0;
306 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
310 // group is initialized in the reference constructor
311 SetGroupInvite(NULL
);
312 m_groupUpdateMask
= 0;
313 m_auraUpdateMask
= 0;
317 m_GuildIdInvited
= 0;
318 m_ArenaTeamIdInvited
= 0;
320 m_atLoginFlags
= AT_LOGIN_NONE
;
329 PlayerTalkClass
= new PlayerMenu( GetSession() );
330 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
332 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
333 m_Tutorials
[ aX
] = 0x00;
334 m_TutorialsChanged
= false;
336 m_DailyQuestChanged
= false;
337 m_lastDailyQuestTime
= 0;
340 m_weaponChangeTimer
= 0;
348 m_deathExpireTime
= 0;
352 m_DetectInvTimer
= 1000;
354 m_bgBattleGroundID
= 0;
355 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
357 m_bgBattleGroundQueueID
[j
].bgType
= 0;
358 m_bgBattleGroundQueueID
[j
].invited
= false;
362 m_logintime
= time(NULL
);
363 m_Last_tick
= m_logintime
;
364 m_WeaponProficiency
= 0;
365 m_ArmorProficiency
= 0;
368 m_canDualWield
= false;
371 m_temporaryUnsummonedPetNumber
= 0;
372 //cache for UNIT_CREATED_BY_SPELL to allow
373 //returning reagents for temporarily removed pets
374 //when dying/logging out
377 ////////////////////Rest System/////////////////////
384 rest_type
=REST_TYPE_NO
;
385 ////////////////////Rest System/////////////////////
387 m_mailsLoaded
= false;
388 m_mailsUpdated
= false;
390 m_nextMailDelivereTime
= 0;
392 m_resetTalentsCost
= 0;
393 m_resetTalentsTime
= 0;
394 m_itemUpdateQueueBlocked
= false;
396 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
397 m_forced_speed_changes
[i
] = 0;
401 /////////////////// Instance System /////////////////////
404 m_InstanceValid
= true;
405 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
407 for (int i
= 0; i
< BASEMOD_END
; i
++)
409 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
410 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
414 m_lastHonorUpdateTime
= time(NULL
);
423 //Default movement to run mode
424 m_unit_movement_flags
= 0;
429 m_bgAfkReportedTimer
= 0;
430 m_contestedPvPTimer
= 0;
432 m_declinedname
= NULL
;
438 CleanupsBeforeDelete();
440 // it must be unloaded already in PlayerLogout and accessed only for loggined player
443 // Note: buy back item already deleted from DB when player was saved
444 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
451 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
454 //all mailed items should be deleted, also all mail should be deallocated
455 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
458 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
459 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
461 delete PlayerTalkClass
;
465 m_transport
->RemovePassenger(this);
468 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
470 delete ItemSetEff
[x
];
472 // clean up player-instance binds, may unload some instance saves
473 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
474 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
475 itr
->second
.save
->RemovePlayer(this);
477 delete m_declinedname
;
481 void Player::CleanupsBeforeDelete()
483 if(m_uint32Values
) // only for fully created Object
486 DuelComplete(DUEL_INTERUPTED
);
488 Unit::CleanupsBeforeDelete();
491 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
)
493 //FIXME: outfitId not used in player creating
495 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
499 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
502 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
506 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
512 SetMapId(info
->mapId
);
513 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
515 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
518 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
522 uint8 powertype
= cEntry
->powerType
;
530 unitfield = 0x00000000;
533 unitfield = 0x00110000;
535 case POWER_RUNIC_POWER:
536 unitfield = 0x0000EE00; //TODO: find correct unitfield here
539 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
543 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
544 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
549 SetDisplayId(info
->displayId_f
);
550 SetNativeDisplayId(info
->displayId_f
);
553 SetDisplayId(info
->displayId_m
);
554 SetNativeDisplayId(info
->displayId_m
);
557 sLog
.outError("Invalid gender %u for player",gender
);
562 setFactionForRace(m_race
);
564 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
566 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
567 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
568 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
569 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
570 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
571 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
572 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
574 // -1 is default value
575 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
577 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
578 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
579 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
581 SetUInt32Value( PLAYER_GUILDID
, 0 );
582 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
583 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
585 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
586 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
587 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
588 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
589 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
590 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
591 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
593 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
595 GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
);
597 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
600 // set starting level
601 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
602 SetUInt32Value(UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_GM_LEVEL
));
605 if(getClass() == CLASS_DEATH_KNIGHT
)
606 SetUInt32Value(UNIT_FIELD_LEVEL
, 55);
608 SetUInt32Value(UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
));
613 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
614 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
615 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
618 m_Last_tick
= time(NULL
);
619 m_Played_time
[0] = 0;
620 m_Played_time
[1] = 0;
622 // base stats and related field values
624 InitTaxiNodesForLevel();
625 InitGlyphsForLevel();
626 InitTalentForLevel();
627 InitPrimaryProffesions(); // to max set before any spell added
629 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
630 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
631 SetHealth(GetMaxHealth());
632 if (getPowerType()==POWER_MANA
)
634 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
635 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
638 if(getPowerType() == POWER_RUNIC_POWER
)
640 SetPower(POWER_RUNE
, 8);
641 SetMaxPower(POWER_RUNE
, 8);
642 SetPower(POWER_RUNIC_POWER
, 0);
643 SetMaxPower(POWER_RUNIC_POWER
, 1000);
647 learnDefaultSpells(true);
649 // original action bar
650 std::list
<uint16
>::const_iterator action_itr
[4];
651 for(int i
=0; i
<4; i
++)
652 action_itr
[i
] = info
->action
[i
].begin();
654 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
657 for(int i
=0; i
<4 ;i
++)
658 taction
[i
] = (*action_itr
[i
]);
660 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
662 for(int i
=0; i
<4 ;i
++)
667 CharStartOutfitEntry
const* oEntry
= NULL
;
668 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
670 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
672 if(entry
->RaceClassGender
== RaceClassGender
)
682 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
684 if(oEntry
->ItemId
[j
] <= 0)
687 uint32 item_id
= oEntry
->ItemId
[j
];
689 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
692 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
696 uint32 count
= iProto
->Stackable
; // max stack by default (mostly 1)
697 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
699 switch(iProto
->Spells
[0].SpellCategory
)
702 if(iProto
->Stackable
> 4)
706 if(iProto
->Stackable
> 2)
712 StoreNewItemInBestSlot(item_id
, count
);
716 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
717 StoreNewItemInBestSlot(item_id_itr
->item_id
, item_id_itr
->item_amount
);
719 // bags and main-hand weapon must equipped at this moment
720 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
721 // or ammo not equipped in special bag
722 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
724 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
727 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
728 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
729 if( msg
== EQUIP_ERR_OK
)
731 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
732 EquipItem( eDest
, pItem
, true);
734 // move other items to more appropriate slots (ammo not equipped in special bag)
737 ItemPosCountVec sDest
;
738 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
739 if( msg
== EQUIP_ERR_OK
)
741 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
742 pItem
= StoreItem( sDest
, pItem
, true);
745 // if this is ammo then use it
746 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
747 if( msg
== EQUIP_ERR_OK
)
748 SetAmmo( pItem
->GetProto()->ItemId
);
752 // all item positions resolved
757 bool Player::StoreNewItemInBestSlot(uint32 titem_id
, uint32 titem_amount
)
759 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
763 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, titem_amount
, false );
764 if( msg
== EQUIP_ERR_OK
)
766 EquipNewItem( eDest
, titem_id
, titem_amount
, true);
767 AutoUnequipOffhandIfNeed();
768 return true; // equipped
772 ItemPosCountVec sDest
;
773 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
774 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
775 if( msg
== EQUIP_ERR_OK
)
777 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
778 return true; // stored
781 // item can't be added
782 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
786 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
788 uint32 BreathRegen
= (uint32
)-1;
790 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
791 data
<< (uint32
)Type
;
796 data
<< (uint32
)0; // spell id
797 GetSession()->SendPacket(&data
);
800 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
802 if(Type
==BREATH_TIMER
)
803 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
805 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
806 data
<< (uint32
)Type
;
807 data
<< CurrentValue
;
811 data
<< (uint32
)0; // spell id
812 GetSession()->SendPacket( &data
);
815 void Player::StopMirrorTimer(MirrorTimerType Type
)
817 if(Type
==BREATH_TIMER
)
820 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
821 data
<< (uint32
)Type
;
822 GetSession()->SendPacket( &data
);
825 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
827 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
828 data
<< (uint64
)guid
;
829 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
830 data
<< (uint32
)damage
;
833 SendMessageToSet(&data
, true);
835 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
837 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
839 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
840 DurabilityLossAll(0.10f
,false);
841 // durability lost message
842 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
843 GetSession()->SendPacket(&data
);
847 void Player::HandleDrowning()
852 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
853 if(waterbreath
|| isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
855 StopMirrorTimer(BREATH_TIMER
);
860 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default length 1 min
862 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
863 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
864 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
866 if ((m_isunderwater
& 0x01) && !(m_isunderwater
& 0x80) && isAlive())
868 //single trigger timer
869 if (!(m_isunderwater
& 0x02))
871 m_isunderwater
|= 0x02;
872 m_breathTimer
= UnderWaterTime
+ 1000;
874 //single trigger "Breathbar"
875 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& 0x04))
877 m_isunderwater
|= 0x04;
878 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
880 //continuous trigger drowning "Damage"
881 if ((m_breathTimer
== 0) && (m_isunderwater
& 0x01))
883 //TODO: Check this formula
884 uint64 guid
= GetGUID();
885 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
887 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
888 m_breathTimer
= 2000;
891 //single trigger retract bar
892 else if (!(m_isunderwater
& 0x01) && !(m_isunderwater
& 0x08) && (m_isunderwater
& 0x02) && (m_breathTimer
> 0) && isAlive())
894 m_isunderwater
= 0x08;
896 uint32 BreathRegen
= 10;
897 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
898 m_isunderwater
= 0x10;
901 else if ((m_breathTimer
< 50) && !(m_isunderwater
& 0x01) && (m_isunderwater
== 0x10))
903 StopMirrorTimer(BREATH_TIMER
);
908 void Player::HandleLava()
910 bool ValidArea
= false;
912 if ((m_isunderwater
& 0x80) && isAlive())
914 //Single trigger Set BreathTimer
915 if (!(m_isunderwater
& 0x80))
917 m_isunderwater
|= 0x04;
918 m_breathTimer
= 1000;
920 //Reset BreathTimer and still in the lava
923 uint64 guid
= GetGUID();
924 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
925 uint32 dmgZone
= GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
927 // Deal lava damage only in lava zones.
943 if (dmgZone
/ 5 & 0x408)
947 // if is valid area and is not gamemaster then deal damage
948 if ( ValidArea
&& !isGameMaster() )
949 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
951 m_breathTimer
= 1000;
955 //Death timer disabled and WaterFlags reset
956 else if (m_deathState
== DEAD
)
963 ///The player sobers by 256 every 10 seconds
964 void Player::HandleSobering()
968 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
969 SetDrunkValue(drunk
);
972 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
975 return DRUNKEN_SMASHED
;
977 return DRUNKEN_DRUNK
;
979 return DRUNKEN_TIPSY
;
980 return DRUNKEN_SOBER
;
983 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
985 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
987 m_drunk
= newDrunkenValue
;
988 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
990 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
992 // special drunk invisibility detection
993 if(newDrunkenState
>= DRUNKEN_DRUNK
)
994 m_detectInvisibilityMask
|= (1<<6);
996 m_detectInvisibilityMask
&= ~(1<<6);
998 if(newDrunkenState
== oldDrunkenState
)
1001 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1002 data
<< uint64(GetGUID());
1003 data
<< uint32(newDrunkenState
);
1004 data
<< uint32(itemId
);
1006 SendMessageToSet(&data
, true);
1009 void Player::Update( uint32 p_time
)
1015 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1020 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1021 m_nextMailDelivereTime
= 0;
1024 Unit::Update( p_time
);
1026 // update player only attacks
1027 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1029 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1032 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1034 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1037 time_t now
= time (NULL
);
1041 UpdateContestedPvP(p_time
);
1043 UpdateDuelFlag(now
);
1045 CheckDuelDistance(now
);
1047 UpdateAfkReport(now
);
1049 CheckExploreSystem();
1051 // Update items that have just a limited lifetime
1052 if (now
>m_Last_tick
)
1053 UpdateItemDuration(uint32(now
- m_Last_tick
));
1055 if (!m_timedquests
.empty())
1057 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1058 while (iter
!= m_timedquests
.end())
1060 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1061 if( q_status
.m_timer
<= p_time
)
1063 uint32 quest_id
= *iter
;
1064 ++iter
; // current iter will be removed in FailTimedQuest
1065 FailTimedQuest( quest_id
);
1069 q_status
.m_timer
-= p_time
;
1070 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1076 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1078 Unit
*pVictim
= getVictim();
1079 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1081 // default combat reach 10
1082 // TODO add weapon,skill check
1084 float pldistance
= ATTACK_DISTANCE
;
1086 if (isAttackReady(BASE_ATTACK
))
1088 if(!IsWithinDistInMap(pVictim
, pldistance
))
1090 setAttackTimer(BASE_ATTACK
,100);
1091 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1093 SendAttackSwingNotInRange();
1094 m_swingErrorMsg
= 1;
1097 //120 degrees of radiant range
1098 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1100 setAttackTimer(BASE_ATTACK
,100);
1101 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1103 SendAttackSwingBadFacingAttack();
1104 m_swingErrorMsg
= 2;
1109 m_swingErrorMsg
= 0; // reset swing error state
1111 // prevent base and off attack in same time, delay attack at 0.2 sec
1112 if(haveOffhandWeapon())
1114 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1115 if(off_att
< ATTACK_DISPLAY_DELAY
)
1116 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1118 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1119 resetAttackTimer(BASE_ATTACK
);
1123 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1125 if(!IsWithinDistInMap(pVictim
, pldistance
))
1127 setAttackTimer(OFF_ATTACK
,100);
1129 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1131 setAttackTimer(OFF_ATTACK
,100);
1135 // prevent base and off attack in same time, delay attack at 0.2 sec
1136 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1137 if(base_att
< ATTACK_DISPLAY_DELAY
)
1138 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1140 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1141 resetAttackTimer(OFF_ATTACK
);
1145 Unit
*owner
= pVictim
->GetOwner();
1146 Unit
*u
= owner
? owner
: pVictim
;
1147 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1150 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1155 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1157 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1159 int time_inn
= time(NULL
)-GetTimeInnEnter();
1160 if (time_inn
>= 10) //freeze update
1162 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1163 //speed collect rest bonus (section/in hour)
1164 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1165 UpdateInnerTime(time(NULL
));
1170 if(m_regenTimer
> 0)
1172 if(p_time
>= m_regenTimer
)
1175 m_regenTimer
-= p_time
;
1178 if (m_weaponChangeTimer
> 0)
1180 if(p_time
>= m_weaponChangeTimer
)
1181 m_weaponChangeTimer
= 0;
1183 m_weaponChangeTimer
-= p_time
;
1186 if (m_zoneUpdateTimer
> 0)
1188 if(p_time
>= m_zoneUpdateTimer
)
1190 uint32 newzone
= GetZoneId();
1191 if( m_zoneUpdateId
!= newzone
)
1192 UpdateZone(newzone
); // also update area
1195 // use area updates as well
1196 // needed for free far all arenas for example
1197 uint32 newarea
= GetAreaId();
1198 if( m_areaUpdateId
!= newarea
)
1199 UpdateArea(newarea
);
1201 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1205 m_zoneUpdateTimer
-= p_time
;
1213 if (m_deathState
== JUST_DIED
)
1220 if(p_time
>= m_nextSave
)
1222 // m_nextSave reseted in SaveToDB call
1224 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1228 m_nextSave
-= p_time
;
1233 if(m_breathTimer
> 0)
1235 if(p_time
>= m_breathTimer
)
1238 m_breathTimer
-= p_time
;
1242 //Handle Water/drowning
1248 //Handle detect stealth players
1249 if (m_DetectInvTimer
> 0)
1251 if (p_time
>= m_DetectInvTimer
)
1253 m_DetectInvTimer
= 3000;
1254 HandleStealthedUnitsDetection();
1257 m_DetectInvTimer
-= p_time
;
1261 if (now
> m_Last_tick
)
1263 uint32 elapsed
= uint32(now
- m_Last_tick
);
1264 m_Played_time
[0] += elapsed
; // Total played time
1265 m_Played_time
[1] += elapsed
; // Level played time
1271 m_drunkTimer
+= p_time
;
1273 if (m_drunkTimer
> 10000)
1277 // not auto-free ghost from body in instances
1278 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1280 if(p_time
>= m_deathTimer
)
1287 m_deathTimer
-= p_time
;
1290 UpdateEnchantTime(p_time
);
1291 UpdateHomebindTime(p_time
);
1294 SendUpdateToOutOfRangeGroupMembers();
1296 Pet
* pet
= GetPet();
1297 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1299 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1304 void Player::setDeathState(DeathState s
)
1306 uint32 ressSpellId
= 0;
1308 bool cur
= isAlive();
1310 if(s
== JUST_DIED
&& cur
)
1312 // drunken state is cleared on death
1314 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1317 clearResurrectRequestData();
1319 // remove form before other mods to prevent incorrect stats calculation
1320 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1322 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1323 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1325 // remove uncontrolled pets
1329 // save value before aura remove in Unit::setDeathState
1330 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1334 ressSpellId
= GetResurrectionSpellId();
1335 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1337 Unit::setDeathState(s
);
1339 // restore resurrection spell id for player after aura remove
1340 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1341 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1343 if(isAlive() && !cur
)
1345 //clear aura case after resurrection by another way (spells will be applied before next death)
1346 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1348 // restore default warrior stance
1349 if(getClass()== CLASS_WARRIOR
)
1350 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1354 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1356 *p_data
<< GetGUID();
1359 *p_data
<< getRace();
1360 uint8 pClass
= getClass();
1362 *p_data
<< getGender();
1364 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1365 *p_data
<< uint8(bytes
);
1366 *p_data
<< uint8(bytes
>> 8);
1367 *p_data
<< uint8(bytes
>> 16);
1368 *p_data
<< uint8(bytes
>> 24);
1370 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1371 *p_data
<< uint8(bytes
);
1373 *p_data
<< uint8(getLevel()); // player level
1374 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1375 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1376 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1378 *p_data
<< GetMapId();
1380 *p_data
<< GetPositionX();
1381 *p_data
<< GetPositionY();
1382 *p_data
<< GetPositionZ();
1384 *p_data
<< (result
? result
->Fetch()[13].GetUInt32() : 0);
1386 uint32 char_flags
= 0;
1387 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1388 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1389 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1390 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1391 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1392 char_flags
|= CHARACTER_FLAG_GHOST
;
1393 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1394 char_flags
|= CHARACTER_FLAG_RENAME
;
1395 // always send the flag if declined names aren't used
1396 // to let the client select a default method of declining the name
1397 if(!sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) || (result
&& result
->Fetch()[14].GetCppString() != ""))
1398 char_flags
|= CHARACTER_FLAG_DECLINED
;
1400 *p_data
<< (uint32
)char_flags
; // character flags
1401 *p_data
<< (uint32
)0; // new wotlk
1402 *p_data
<< (uint8
)1; // unknown
1406 uint32 petDisplayId
= 0;
1407 uint32 petLevel
= 0;
1408 uint32 petFamily
= 0;
1410 // show pet at selection character in character list only for non-ghost character
1411 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1413 Field
* fields
= result
->Fetch();
1415 uint32 entry
= fields
[10].GetUInt32();
1416 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1419 petDisplayId
= fields
[11].GetUInt32();
1420 petLevel
= fields
[12].GetUInt32();
1421 petFamily
= cInfo
->family
;
1425 *p_data
<< (uint32
)petDisplayId
;
1426 *p_data
<< (uint32
)petLevel
;
1427 *p_data
<< (uint32
)petFamily
;
1430 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1431 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1434 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1439 Field *fields = result->Fetch();
1440 uint8 slot = fields[0].GetUInt8() & 255;
1441 uint32 item_id = fields[1].GetUInt32();
1442 if( slot >= EQUIPMENT_SLOT_END )
1445 items[slot] = objmgr.GetItemPrototype(item_id);
1448 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1451 } while (result->NextRow());
1455 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1457 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1458 uint32 item_id
= GetUInt32Value(visualbase
);
1459 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1460 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1462 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1464 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1465 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1471 *p_data
<< (uint32
)proto
->DisplayInfoID
;
1472 *p_data
<< (uint8
)proto
->InventoryType
;
1473 *p_data
<< (uint32
)(enchant
?enchant
->aura_id
:0);
1477 *p_data
<< (uint32
)0;
1478 *p_data
<< (uint8
)0;
1479 *p_data
<< (uint32
)0; // enchant?
1482 *p_data
<< (uint32
)0; // first bag display id
1483 *p_data
<< (uint8
)0; // first bag inventory type
1484 *p_data
<< (uint32
)0; // enchant?
1487 bool Player::ToggleAFK()
1489 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1491 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1493 // afk player not allowed in battleground
1494 if(state
&& InBattleGround())
1495 LeaveBattleground();
1500 bool Player::ToggleDND()
1502 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1504 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1507 uint8
Player::chatTag() const
1524 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1526 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1528 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1532 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1533 Pet
* pet
= GetPet();
1535 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1537 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1538 if(!InBattleGround() && mEntry
->IsBattleGround() && !GetSession()->GetSecurity())
1541 // client without expansion support
1542 if(GetSession()->Expansion() < mEntry
->Expansion())
1544 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1547 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1549 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1551 return false; // normal client can't teleport to this map...
1555 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1558 // if we were on a transport, leave
1559 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1561 m_transport
->RemovePassenger(this);
1563 m_movementInfo
.t_x
= 0.0f
;
1564 m_movementInfo
.t_y
= 0.0f
;
1565 m_movementInfo
.t_z
= 0.0f
;
1566 m_movementInfo
.t_o
= 0.0f
;
1567 m_movementInfo
.t_time
= 0;
1570 SetSemaphoreTeleport(true);
1572 // The player was ported to another map and looses the duel immediately.
1573 // We have to perform this check before the teleport, otherwise the
1574 // ObjectAccessor won't find the flag.
1575 if (duel
&& GetMapId()!=mapid
)
1577 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1579 DuelComplete(DUEL_FLED
);
1582 // reset movement flags at teleport, because player will continue move with these flags after teleport
1583 SetUnitMovementFlags(0);
1585 if ((GetMapId() == mapid
) && (!m_transport
))
1587 // prepare zone change detect
1588 uint32 old_zone
= GetZoneId();
1591 if(!GetSession()->PlayerLogout())
1594 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1595 GetSession()->SendPacket(&data
);
1596 SetPosition( x
, y
, z
, orientation
, true);
1599 // this will be used instead of the current location in SaveToDB
1600 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1602 //BuildHeartBeatMsg(&data);
1603 //SendMessageToSet(&data, true);
1604 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1606 //same map, only remove pet if out of range
1607 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1609 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1610 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1612 m_temporaryUnsummonedPetNumber
= 0;
1614 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1618 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1621 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1624 if(pet
&& m_temporaryUnsummonedPetNumber
)
1626 Pet
* NewPet
= new Pet
;
1627 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1630 m_temporaryUnsummonedPetNumber
= 0;
1634 if(!GetSession()->PlayerLogout())
1636 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1637 SetSemaphoreTeleport(false);
1639 UpdateZone(GetZoneId());
1643 if(old_zone
!= GetZoneId())
1646 if(pvpInfo
.inHostileArea
)
1647 CastSpell(this, 2479, true);
1652 // far teleport to another map
1653 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1654 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1656 // Check enter rights before map getting to avoid creating instance copy for player
1657 // this check not dependent from map instance copy and same for all instance copies of selected map
1658 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1660 SetSemaphoreTeleport(false);
1664 // If the map is not created, assume it is possible to enter it.
1665 // It will be created in the WorldPortAck.
1666 Map
*map
= MapManager::Instance().FindMap(mapid
);
1667 if (!map
|| map
->CanEnter(this))
1673 ResetContestedPvP();
1675 // remove player from battleground on far teleport (when changing maps)
1676 if(BattleGround
const* bg
= GetBattleGround())
1678 // Note: at battleground join battleground id set before teleport
1679 // and we already will found "current" battleground
1680 // just need check that this is targeted map or leave
1681 if(bg
->GetMapId() != mapid
)
1682 LeaveBattleground(false); // don't teleport to entry point
1685 // remove pet on map change
1688 //leaving map -> delete pet right away (doing this later will cause problems)
1689 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1690 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1692 m_temporaryUnsummonedPetNumber
= 0;
1694 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1697 // remove all dyn objects
1698 RemoveAllDynObjects();
1700 // stop spellcasting
1701 // not attempt interrupt teleportation spell at caster teleport
1702 if(!(options
& TELE_TO_SPELL
))
1703 if(IsNonMeleeSpellCasted(true))
1704 InterruptNonMeleeSpells(true);
1706 if(!GetSession()->PlayerLogout())
1708 // send transfer packets
1709 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1710 data
<< uint32(mapid
);
1713 data
<< m_transport
->GetEntry() << GetMapId();
1715 GetSession()->SendPacket(&data
);
1717 data
.Initialize(SMSG_NEW_WORLD
, (20));
1720 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1724 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1726 GetSession()->SendPacket( &data
);
1727 SendSavedInstances();
1729 // remove from old map now
1730 if(oldmap
) oldmap
->Remove(this, false);
1733 // new final coordinates
1737 float final_o
= orientation
;
1741 final_x
+= m_movementInfo
.t_x
;
1742 final_y
+= m_movementInfo
.t_y
;
1743 final_z
+= m_movementInfo
.t_z
;
1744 final_o
+= m_movementInfo
.t_o
;
1747 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1748 // if the player is saved before worldportack (at logout for example)
1749 // this will be used instead of the current location in SaveToDB
1751 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1753 // move packet sent by client always after far teleport
1754 // SetPosition(final_x, final_y, final_z, final_o, true);
1757 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1765 void Player::AddToWorld()
1767 ///- Do not add/remove the player from the object storage
1768 ///- It will crash when updating the ObjectAccessor
1769 ///- The player should only be added when logging in
1772 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1775 m_items
[i
]->AddToWorld();
1779 void Player::RemoveFromWorld()
1784 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1786 UnsummonAllTotems();
1791 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1794 m_items
[i
]->RemoveFromWorld();
1797 ///- Do not add/remove the player from the object storage
1798 ///- It will crash when updating the ObjectAccessor
1799 ///- The player should only be removed when logging out
1800 Unit::RemoveFromWorld();
1803 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1807 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1811 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1813 // talent who gave more rage on attack
1814 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1818 addRage
= damage
/rageconversion
*2.5;
1820 // Berserker Rage effect
1821 if(HasAura(18499,0))
1825 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1827 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1830 void Player::RegenerateAll()
1832 if (m_regenTimer
!= 0)
1834 uint32 regenDelay
= 2000;
1836 // Not in combat or they have regeneration
1837 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1838 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1841 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1843 Regenerate(POWER_RAGE
);
1844 if(getClass() == CLASS_DEATH_KNIGHT
)
1845 Regenerate(POWER_RUNIC_POWER
);
1849 Regenerate( POWER_ENERGY
);
1851 Regenerate( POWER_MANA
);
1853 if(getClass() == CLASS_DEATH_KNIGHT
)
1854 Regenerate( POWER_RUNE
);
1856 m_regenTimer
= regenDelay
;
1859 void Player::Regenerate(Powers power
)
1861 uint32 curValue
= GetPower(power
);
1862 uint32 maxValue
= GetMaxPower(power
);
1864 float addvalue
= 0.0f
;
1870 bool recentCast
= IsUnderLastManaUseEffect();
1871 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1874 // Mangos Updates Mana in intervals of 2s, which is correct
1875 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1879 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1882 case POWER_RAGE
: // Regenerate rage
1884 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1885 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1887 case POWER_ENERGY
: // Regenerate energy (rogue)
1890 case POWER_RUNIC_POWER
:
1892 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1893 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1897 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1898 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1899 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1902 case POWER_HAPPINESS
:
1906 // Mana regen calculated in Player::UpdateManaRegen()
1907 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1908 if(power
!= POWER_MANA
)
1910 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1911 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1912 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1913 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1916 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1918 curValue
+= uint32(addvalue
);
1919 if (curValue
> maxValue
)
1920 curValue
= maxValue
;
1924 if(curValue
<= uint32(addvalue
))
1927 curValue
-= uint32(addvalue
);
1929 SetPower(power
, curValue
);
1932 void Player::RegenerateHealth()
1934 uint32 curValue
= GetHealth();
1935 uint32 maxValue
= GetMaxHealth();
1937 if (curValue
>= maxValue
) return;
1939 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1941 float addvalue
= 0.0f
;
1944 if ( IsPolymorphed() )
1945 addvalue
= GetMaxHealth()/3;
1946 // normal regen case (maybe partly in combat case)
1947 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1949 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1952 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1953 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1954 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1956 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1957 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1963 // always regeneration bonus (including combat)
1964 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1969 ModifyHealth(int32(addvalue
));
1972 bool Player::CanInteractWithNPCs(bool alive
) const
1974 if(alive
&& !isAlive())
1982 bool Player::IsUnderWater() const
1984 return IsInWater() &&
1985 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1988 void Player::SetInWater(bool apply
)
1990 if(m_isInWater
==apply
)
1993 //define player in water by opcodes
1994 //move player's guid into HateOfflineList of those mobs
1995 //which can't swim and move guid back into ThreatList when
1997 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1998 m_isInWater
= apply
;
2000 // remove auras that need water/land
2001 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2003 getHostilRefManager().updateThreatTables();
2006 void Player::SetGameMaster(bool on
)
2010 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2012 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2014 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
2015 ResetContestedPvP();
2017 getHostilRefManager().setOnlineOfflineState(false);
2022 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2023 setFactionForRace(getRace());
2024 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2026 // restore FFA PvP Server state
2027 if(sWorld
.IsFFAPvPRealm())
2028 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
2030 // restore FFA PvP area state, remove not allowed for GM mounts
2031 UpdateArea(m_areaUpdateId
);
2033 getHostilRefManager().setOnlineOfflineState(true);
2036 ObjectAccessor::UpdateVisibilityForPlayer(this);
2039 void Player::SetGMVisible(bool on
)
2043 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2045 // Reapply stealth/invisibility if active or show if not any
2046 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2047 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2048 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2049 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2051 SetVisibility(VISIBILITY_ON
);
2055 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2057 SetAcceptWhispers(false);
2058 SetGameMaster(true);
2060 SetVisibility(VISIBILITY_OFF
);
2064 bool Player::IsGroupVisibleFor(Player
* p
) const
2066 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2068 default: return IsInSameGroupWith(p
);
2069 case 1: return IsInSameRaidWith(p
);
2070 case 2: return GetTeam()==p
->GetTeam();
2074 bool Player::IsInSameGroupWith(Player
const* p
) const
2076 return p
==this || GetGroup() != NULL
&&
2077 GetGroup() == p
->GetGroup() &&
2078 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2081 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2082 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2083 void Player::UninviteFromGroup()
2085 if(GetGroupInvite()) // uninvited invitee
2087 Group
* group
= GetGroupInvite();
2088 group
->RemoveInvite(this);
2090 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2092 if(group
->IsCreated())
2094 group
->Disband(true);
2095 objmgr
.RemoveGroup(group
);
2098 group
->RemoveAllInvites();
2105 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2109 if (group
->RemoveMember(guid
, 0) <= 1)
2111 // group->Disband(); already disbanded in RemoveMember
2112 objmgr
.RemoveGroup(group
);
2114 // removemember sets the player's group pointer to NULL
2119 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2121 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2122 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2123 data
<< uint32(GivenXP
+RestXP
); // given experience
2124 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2127 data
<< uint32(GivenXP
); // experience without rested bonus
2128 data
<< float(1); // 1 - none 0 - 100% group bonus output
2130 data
<< uint8(0); // new 2.4.0
2131 GetSession()->SendPacket(&data
);
2134 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2142 uint32 level
= getLevel();
2144 // XP to money conversion processed in Player::RewardQuest
2145 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2148 // handle SPELL_AURA_MOD_XP_PCT auras
2149 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2150 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2151 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2153 // XP resting bonus for kill
2154 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2156 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2158 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2159 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2160 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2162 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2166 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2167 GiveLevel(level
+ 1);
2170 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2173 SetUInt32Value(PLAYER_XP
, newXP
);
2176 // Update player to next level
2177 // Current player experience not update (must be update by caller)
2178 void Player::GiveLevel(uint32 level
)
2180 if ( level
== getLevel() )
2183 PlayerLevelInfo info
;
2184 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2186 PlayerClassLevelInfo classInfo
;
2187 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2189 // send levelup info to client
2190 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2191 data
<< uint32(level
);
2192 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2193 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2194 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2202 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2203 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2205 GetSession()->SendPacket(&data
);
2207 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(level
));
2209 //update level, max level of skills
2210 if(getLevel()!= level
)
2211 m_Played_time
[1] = 0; // Level Played Time reset
2213 UpdateSkillsForLevel ();
2215 // save base values (bonuses already included in stored stats
2216 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2217 SetCreateStat(Stats(i
), info
.stats
[i
]);
2219 SetCreateHealth(classInfo
.basehealth
);
2220 SetCreateMana(classInfo
.basemana
);
2222 InitTalentForLevel();
2223 InitTaxiNodesForLevel();
2224 InitGlyphsForLevel();
2228 // set current level health and mana/energy to maximum after applying all mods.
2229 SetHealth(GetMaxHealth());
2230 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2231 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2232 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2233 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2234 SetPower(POWER_FOCUS
, 0);
2235 SetPower(POWER_HAPPINESS
, 0);
2237 // give level to summoned pet
2238 Pet
* pet
= GetPet();
2239 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2240 pet
->GivePetLevel(level
);
2241 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2244 void Player::InitTalentForLevel()
2246 uint32 level
= getLevel();
2247 // talents base at level diff ( talents = level - 9 but some can be used already)
2250 // Remove all talent points
2251 if(m_usedTalentCount
> 0) // Free any used talents
2254 SetFreeTalentPoints(0);
2259 uint32 talentPointsForLevel
= uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
2260 // if used more that have then reset
2261 if(m_usedTalentCount
> talentPointsForLevel
)
2263 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2266 SetFreeTalentPoints(0);
2268 // else update amount of free points
2270 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2274 void Player::InitStatsForLevel(bool reapplyMods
)
2276 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2277 _RemoveAllStatBonuses();
2279 PlayerClassLevelInfo classInfo
;
2280 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2282 PlayerLevelInfo info
;
2283 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2285 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2286 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(getLevel()));
2288 UpdateSkillsForLevel ();
2290 // set default cast time multiplier
2291 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2293 // reset size before reapply auras
2294 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2296 // save base values (bonuses already included in stored stats
2297 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2298 SetCreateStat(Stats(i
), info
.stats
[i
]);
2300 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2301 SetStat(Stats(i
), info
.stats
[i
]);
2303 SetCreateHealth(classInfo
.basehealth
);
2306 SetCreateMana(classInfo
.basemana
);
2308 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2312 //reset rating fields values
2313 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2314 SetUInt32Value(index
, 0);
2316 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2317 for (int i
= 0; i
< 7; i
++)
2319 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2320 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2321 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2324 //reset attack power, damage and attack speed fields
2325 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2326 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2327 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2329 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2330 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2331 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2332 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2333 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2334 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2336 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2337 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2338 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2339 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2340 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2341 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2343 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2344 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2345 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2346 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2348 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2349 for (uint8 i
= 0; i
< 7; ++i
)
2350 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2352 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2353 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2354 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2357 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2359 // set armor (resistance 0) to original value (create_agility*2)
2360 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2361 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2362 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2363 // set other resistance to original value (0)
2364 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2366 SetResistance(SpellSchools(i
), 0);
2367 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2368 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2371 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2372 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2373 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2375 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2376 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2378 // Init data for form but skip reapply item mods for form
2379 InitDataForForm(reapplyMods
);
2382 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2383 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2385 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2387 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2388 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2390 // cleanup unit flags (will be re-applied if need at aura load).
2391 RemoveFlag( UNIT_FIELD_FLAGS
,
2392 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2393 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2394 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2395 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2396 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2397 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2399 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2400 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
| PLAYER_FLAGS_FFA_PVP
);
2402 SetByteValue(UNIT_FIELD_BYTES_1
, 2, 0x00); // one form stealth modified bytes
2404 // restore if need some important flags
2405 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2407 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2408 _ApplyAllStatBonuses();
2410 // set current level health and mana/energy to maximum after applying all mods.
2411 SetHealth(GetMaxHealth());
2412 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2413 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2414 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2415 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2416 SetPower(POWER_FOCUS
, 0);
2417 SetPower(POWER_HAPPINESS
, 0);
2418 SetPower(POWER_RUNIC_POWER
, 0);
2421 void Player::SendInitialSpells()
2423 uint16 spellCount
= 0;
2425 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2428 size_t countPos
= data
.wpos();
2429 data
<< uint16(spellCount
); // spell count placeholder
2431 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2433 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2436 if(!itr
->second
->active
|| itr
->second
->disabled
)
2439 data
<< uint16(itr
->first
);
2440 data
<< uint16(0); // it's not slot id
2445 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2447 uint16 spellCooldowns
= m_spellCooldowns
.size();
2448 data
<< uint16(spellCooldowns
);
2449 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); itr
++)
2451 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2455 data
<< uint16(itr
->first
);
2457 time_t cooldown
= 0;
2458 time_t curTime
= time(NULL
);
2459 if(itr
->second
.end
> curTime
)
2460 cooldown
= (itr
->second
.end
-curTime
)*1000;
2462 data
<< uint16(itr
->second
.itemid
); // cast item id
2463 data
<< uint16(sEntry
->Category
); // spell category
2464 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2466 data
<< uint32(0); // cooldown
2467 data
<< uint32(cooldown
); // category cooldown
2471 data
<< uint32(cooldown
); // cooldown
2472 data
<< uint32(0); // category cooldown
2476 GetSession()->SendPacket(&data
);
2478 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2481 void Player::RemoveMail(uint32 id
)
2483 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2485 if ((*itr
)->messageID
== id
)
2487 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2494 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2496 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2497 data
<< (uint32
) mailId
;
2498 data
<< (uint32
) mailAction
;
2499 data
<< (uint32
) mailError
;
2500 if ( mailError
== MAIL_ERR_BAG_FULL
)
2501 data
<< (uint32
) equipError
;
2502 else if( mailAction
== MAIL_ITEM_TAKEN
)
2504 data
<< (uint32
) item_guid
; // item guid low?
2505 data
<< (uint32
) item_count
; // item count?
2507 GetSession()->SendPacket(&data
);
2510 void Player::SendNewMail()
2512 // deliver undelivered mail
2513 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2515 GetSession()->SendPacket(&data
);
2518 void Player::UpdateNextMailTimeAndUnreads()
2520 // calculate next delivery time (min. from non-delivered mails
2521 // and recalculate unReadMail
2522 time_t cTime
= time(NULL
);
2523 m_nextMailDelivereTime
= 0;
2525 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2527 if((*itr
)->deliver_time
> cTime
)
2529 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2530 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2532 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2537 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2539 if(deliver_time
<= time(NULL
)) // ready now
2544 else // not ready and no have ready mails
2546 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2547 m_nextMailDelivereTime
= deliver_time
;
2551 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool loading
, uint16 slot_id
, bool disabled
)
2553 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2556 // do character spell book cleanup (all characters)
2557 if(loading
&& !learning
) // spell load case
2559 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2560 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2563 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2568 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2570 // do character spell book cleanup (all characters)
2571 if(loading
&& !learning
) // spell load case
2573 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2574 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2577 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2582 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2584 bool disabled_case
= false;
2585 bool superceded_old
= false;
2587 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2588 if (itr
!= m_spells
.end())
2590 // update active state for known spell
2591 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2593 itr
->second
->active
= active
;
2595 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2596 if(loading
&& !learning
)
2597 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2598 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2599 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2603 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2604 data
<< uint16(spell_id
);
2605 GetSession()->SendPacket(&data
);
2607 return active
; // learn (show in spell book if active now)
2610 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2612 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2613 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2614 itr
->second
->disabled
= disabled
;
2619 disabled_case
= true;
2621 else switch(itr
->second
->state
)
2623 case PLAYERSPELL_UNCHANGED
: // known saved spell
2625 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2628 m_spells
.erase(itr
);
2629 state
= PLAYERSPELL_CHANGED
;
2630 break; // need re-add
2632 default: // known not saved yet spell (new or modified)
2634 // can be in case spell loading but learned at some previous spell loading
2635 if(loading
&& !learning
)
2636 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2643 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2645 // talent: unlearn all other talent ranks (high and low)
2646 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2648 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2650 for(int i
=0; i
<5; ++i
)
2652 // skip learning spell and no rank spell case
2653 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2654 if(!rankSpellId
|| rankSpellId
==spell_id
)
2657 // skip unknown ranks
2658 if(!HasSpell(rankSpellId
))
2661 removeSpell(rankSpellId
);
2665 // non talent spell: learn low ranks (recursive call)
2666 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2668 if(loading
) // at spells loading, no output, but allow save
2669 addSpell(prev_spell
,active
,true,loading
,SPELL_WITHOUT_SLOT_ID
,disabled
);
2670 else // at normal learning
2671 learnSpell(prev_spell
);
2674 PlayerSpell
*newspell
= new PlayerSpell
;
2675 newspell
->active
= active
;
2676 newspell
->state
= state
;
2677 newspell
->disabled
= disabled
;
2679 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2680 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2682 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2684 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2685 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2686 if(!i_spellInfo
) continue;
2688 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2690 if(itr
->second
->active
)
2692 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2694 if(!loading
) // not send spell (re-/over-)learn packets at loading
2696 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2697 data
<< uint16(itr
->first
);
2698 data
<< uint16(spell_id
);
2699 GetSession()->SendPacket( &data
);
2702 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2703 itr
->second
->active
= false;
2704 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2705 superceded_old
= true; // new spell replace old in action bars and spell book.
2707 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2709 if(!loading
) // not send spell (re-/over-)learn packets at loading
2711 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2712 data
<< uint16(spell_id
);
2713 data
<< uint16(itr
->first
);
2714 GetSession()->SendPacket( &data
);
2717 // mark new spell as disable (not learned yet for client and will not learned)
2718 newspell
->active
= false;
2719 if(newspell
->state
!= PLAYERSPELL_NEW
)
2720 newspell
->state
= PLAYERSPELL_CHANGED
;
2727 uint16 tmpslot
=slot_id
;
2729 if (tmpslot
== SPELL_WITHOUT_SLOT_ID
)
2732 PlayerSpellMap::iterator itr
;
2733 for (itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2735 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2737 if (itr
->second
->slotId
> maxid
)
2738 maxid
= itr
->second
->slotId
;
2740 tmpslot
= maxid
+ 1;
2743 newspell
->slotId
= tmpslot
;
2744 m_spells
[spell_id
] = newspell
;
2746 // return false if spell disabled
2747 if (newspell
->disabled
)
2751 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2753 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2754 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2755 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2757 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2758 CastSpell(this, spell_id
, true);
2760 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2761 else if (IsPassiveSpell(spell_id
))
2763 // if spell doesn't require a stance or the player is in the required stance
2764 if( ( !spellInfo
->Stances
&&
2765 spell_id
!= 5420 && spell_id
!= 5419 && spell_id
!= 7376 &&
2766 spell_id
!= 7381 && spell_id
!= 21156 && spell_id
!= 21009 &&
2767 spell_id
!= 21178 && spell_id
!= 33948 && spell_id
!= 40121 ) ||
2768 m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))) ||
2769 (spell_id
== 5420 && m_form
== FORM_TREE
) ||
2770 (spell_id
== 5419 && m_form
== FORM_TRAVEL
) ||
2771 (spell_id
== 7376 && m_form
== FORM_DEFENSIVESTANCE
) ||
2772 (spell_id
== 7381 && m_form
== FORM_BERSERKERSTANCE
) ||
2773 (spell_id
== 21156 && m_form
== FORM_BATTLESTANCE
)||
2774 (spell_id
== 21178 && (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
) ) ||
2775 (spell_id
== 33948 && m_form
== FORM_FLIGHT
) ||
2776 (spell_id
== 40121 && m_form
== FORM_FLIGHT_EPIC
) )
2777 //Check CasterAuraStates
2778 if (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)))
2779 CastSpell(this, spell_id
, true);
2781 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2783 CastSpell(this, spell_id
, true);
2787 // update used talent points count
2788 m_usedTalentCount
+= talentCost
;
2790 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2791 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2793 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2794 SetFreePrimaryProffesions(freeProfs
-1);
2797 // add dependent skills
2798 uint16 maxskill
= GetMaxSkillValueForLevel();
2800 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2804 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2805 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2807 if(skill_value
< spellLearnSkill
->value
)
2808 skill_value
= spellLearnSkill
->value
;
2810 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2812 if(skill_max_value
< new_skill_max_value
)
2813 skill_max_value
= new_skill_max_value
;
2815 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2819 // not ranked skills
2820 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2821 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2823 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2825 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2829 if(HasSkill(pSkill
->id
))
2832 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2833 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2834 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2836 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2838 case SKILL_RANGE_LANGUAGE
:
2839 SetSkill(pSkill
->id
, 300, 300 );
2841 case SKILL_RANGE_LEVEL
:
2842 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2844 case SKILL_RANGE_MONO
:
2845 SetSkill(pSkill
->id
, 1, 1 );
2854 // learn dependent spells
2855 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2856 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2858 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2860 if(!itr
->second
.autoLearned
)
2862 if(loading
) // at spells loading, no output, but allow save
2863 addSpell(itr
->second
.spell
,true,true,loading
);
2864 else // at normal learning
2865 learnSpell(itr
->second
.spell
);
2871 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
);
2872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
);
2875 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2876 return active
&& !disabled
&& !superceded_old
;
2879 void Player::learnSpell(uint32 spell_id
)
2881 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2883 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2884 bool active
= disabled
? itr
->second
->active
: true;
2886 bool learning
= addSpell(spell_id
,active
);
2888 // learn all disabled higher ranks (recursive)
2889 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2890 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2892 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2893 if (disabled
&& iter
!= m_spells
.end() && iter
->second
->disabled
)
2894 learnSpell(i
->second
);
2897 // prevent duplicated entires in spell book
2901 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2902 data
<< uint32(spell_id
);
2903 GetSession()->SendPacket(&data
);
2906 void Player::removeSpell(uint32 spell_id
, bool disabled
)
2908 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2909 if (itr
== m_spells
.end())
2912 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2915 // unlearn non talent higher ranks (recursive)
2916 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2917 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2918 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2919 removeSpell(itr2
->second
,disabled
);
2922 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2923 data
<< uint16(spell_id
);
2924 GetSession()->SendPacket(&data
);
2928 itr
->second
->disabled
= disabled
;
2929 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2930 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2934 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2937 m_spells
.erase(itr
);
2940 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2943 RemoveAurasDueToSpell(spell_id
);
2946 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2947 RemovePetAura(petSpell
);
2949 // free talent points
2950 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2953 if(talentCosts
< m_usedTalentCount
)
2954 m_usedTalentCount
-= talentCosts
;
2956 m_usedTalentCount
= 0;
2959 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2960 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2962 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2963 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2964 SetFreePrimaryProffesions(freeProfs
);
2967 // remove dependent skill
2968 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2971 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2972 if(!prev_spell
) // first rank, remove skill
2973 SetSkill(spellLearnSkill
->skill
,0,0);
2976 // search prev. skill setting by spell ranks chain
2977 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
2978 while(!prevSkill
&& prev_spell
)
2980 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
2981 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
2984 if(!prevSkill
) // not found prev skill setting, remove skill
2985 SetSkill(spellLearnSkill
->skill
,0,0);
2986 else // set to prev. skill setting values
2988 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
2989 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
2991 if(skill_value
> prevSkill
->value
)
2992 skill_value
= prevSkill
->value
;
2994 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
2996 if(skill_max_value
> new_skill_max_value
)
2997 skill_max_value
= new_skill_max_value
;
2999 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3006 // not ranked skills
3007 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3008 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3010 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3012 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3016 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3017 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3018 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
3020 // not reset skills for professions and racial abilities
3021 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3022 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3025 SetSkill(pSkill
->id
, 0, 0 );
3030 // remove dependent spells
3031 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3032 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3034 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3035 removeSpell(itr2
->second
.spell
, disabled
);
3038 void Player::RemoveArenaSpellCooldowns()
3040 // remove cooldowns on spells that has < 15 min CD
3041 SpellCooldowns::iterator itr
, next
;
3042 // iterate spell cooldowns
3043 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3047 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3048 // check if spellentry is present and if the cooldown is less than 15 mins
3050 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
3051 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
3054 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3055 data
<< uint32(itr
->first
);
3057 GetSession()->SendPacket(&data
);
3059 m_spellCooldowns
.erase(itr
);
3064 void Player::RemoveAllSpellCooldown()
3066 if(!m_spellCooldowns
.empty())
3068 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3070 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3071 data
<< uint32(itr
->first
);
3072 data
<< uint64(GetGUID());
3073 GetSession()->SendPacket(&data
);
3075 m_spellCooldowns
.clear();
3079 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3081 m_spellCooldowns
.clear();
3083 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3087 time_t curTime
= time(NULL
);
3091 Field
*fields
= result
->Fetch();
3093 uint32 spell_id
= fields
[0].GetUInt32();
3094 uint32 item_id
= fields
[1].GetUInt32();
3095 time_t db_time
= (time_t)fields
[2].GetUInt64();
3097 if(!sSpellStore
.LookupEntry(spell_id
))
3099 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3103 // skip outdated cooldown
3104 if(db_time
<= curTime
)
3107 AddSpellCooldown(spell_id
, item_id
, db_time
);
3109 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3111 while( result
->NextRow() );
3117 void Player::_SaveSpellCooldowns()
3119 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3121 time_t curTime
= time(NULL
);
3123 // remove outdated and save active
3124 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3126 if(itr
->second
.end
<= curTime
)
3127 m_spellCooldowns
.erase(itr
++);
3130 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
));
3136 uint32
Player::resetTalentsCost() const
3138 // The first time reset costs 1 gold
3139 if(m_resetTalentsCost
< 1*GOLD
)
3142 else if(m_resetTalentsCost
< 5*GOLD
)
3144 // After that it increases in increments of 5 gold
3145 else if(m_resetTalentsCost
< 10*GOLD
)
3149 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3152 // This cost will be reduced by a rate of 5 gold per month
3153 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3154 // to a minimum of 10 gold.
3155 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3159 // After that it increases in increments of 5 gold
3160 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3161 // until it hits a cap of 50 gold.
3162 if(new_cost
> 50*GOLD
)
3169 bool Player::resetTalents(bool no_cost
)
3171 // not need after this call
3172 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3174 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3175 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3178 uint32 level
= getLevel();
3179 uint32 talentPointsForLevel
= level
< 10 ? 0 : uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
3181 if (m_usedTalentCount
== 0)
3183 SetFreeTalentPoints(talentPointsForLevel
);
3191 cost
= resetTalentsCost();
3193 if (GetMoney() < cost
)
3195 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3200 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3202 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3204 if (!talentInfo
) continue;
3206 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3211 // unlearn only talents for character class
3212 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3213 // to prevent unexpected lost normal learned spell skip another class talents
3214 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3217 for (int j
= 0; j
< 5; j
++)
3219 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3221 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3227 // remove learned spells (all ranks)
3228 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3230 // unlearn if first rank is talent or learned by talent
3231 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3233 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3234 itr
= GetSpellMap().begin();
3243 SetFreeTalentPoints(talentPointsForLevel
);
3247 ModifyMoney(-(int32
)cost
);
3249 m_resetTalentsCost
= cost
;
3250 m_resetTalentsTime
= time(NULL
);
3253 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3254 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3259 bool Player::_removeSpell(uint16 spell_id
)
3261 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3262 if (itr
!= m_spells
.end())
3265 m_spells
.erase(itr
);
3271 Mail
* Player::GetMail(uint32 id
)
3273 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
3275 if ((*itr
)->messageID
== id
)
3283 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3287 Object::_SetCreateBits(updateMask
, target
);
3291 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3293 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3294 updateMask
->SetBit(index
);
3299 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3303 Object::_SetUpdateBits(updateMask
, target
);
3307 Object::_SetUpdateBits(updateMask
, target
);
3308 *updateMask
&= updateVisualBits
;
3312 void Player::InitVisibleBits()
3314 updateVisualBits
.SetCount(PLAYER_END
);
3316 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3317 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3318 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3319 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3320 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3321 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3322 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3323 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3324 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3325 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3326 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3327 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3328 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3329 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3330 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3331 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3332 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3333 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3334 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3335 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3336 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3337 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3338 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3339 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3340 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3341 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3342 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3343 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3344 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3345 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3346 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3347 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3348 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3349 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3350 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3351 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3352 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3353 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3354 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3355 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3356 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3357 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3358 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3359 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3360 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3361 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3362 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3363 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3364 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3365 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3366 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3367 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3368 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3369 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3370 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3372 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3373 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3374 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3375 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3376 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3377 updateVisualBits
.SetBit(PLAYER_BYTES
);
3378 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3379 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3380 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3381 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3383 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3384 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3385 updateVisualBits
.SetBit(i
);
3387 // Players visible items are not inventory stuff
3388 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3390 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3393 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3394 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3397 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3399 // item enchantments
3400 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3401 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3403 // random properties
3404 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3405 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3406 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3409 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3412 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3414 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3416 if(m_items
[i
] == NULL
)
3419 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3424 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3426 if(m_items
[i
] == NULL
)
3429 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3431 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3433 if(m_items
[i
] == NULL
)
3436 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3440 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3443 void Player::DestroyForPlayer( Player
*target
) const
3445 Unit::DestroyForPlayer( target
);
3447 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3449 if(m_items
[i
] == NULL
)
3452 m_items
[i
]->DestroyForPlayer( target
);
3457 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3459 if(m_items
[i
] == NULL
)
3462 m_items
[i
]->DestroyForPlayer( target
);
3464 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3466 if(m_items
[i
] == NULL
)
3469 m_items
[i
]->DestroyForPlayer( target
);
3474 bool Player::HasSpell(uint32 spell
) const
3476 PlayerSpellMap::const_iterator itr
= m_spells
.find((uint16
)spell
);
3477 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
);
3480 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3483 return TRAINER_SPELL_RED
;
3485 if (!trainer_spell
->spell
)
3486 return TRAINER_SPELL_RED
;
3489 if(HasSpell(trainer_spell
->spell
))
3490 return TRAINER_SPELL_GRAY
;
3492 // check race/class requirement
3493 if(!IsSpellFitByClassAndRace(trainer_spell
->spell
))
3494 return TRAINER_SPELL_RED
;
3496 // check level requirement
3497 if(getLevel() < trainer_spell
->reqlevel
)
3498 return TRAINER_SPELL_RED
;
3500 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->spell
))
3502 // check prev.rank requirement
3503 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3504 return TRAINER_SPELL_RED
;
3506 // check additional spell requirement
3507 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3508 return TRAINER_SPELL_RED
;
3511 // check skill requirement
3512 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3513 return TRAINER_SPELL_RED
;
3515 // exist, already checked at loading
3516 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->spell
);
3518 // secondary prof. or not prof. spell
3519 uint32 skill
= spell
->EffectMiscValue
[1];
3521 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3522 return TRAINER_SPELL_GREEN
;
3524 // check primary prof. limit
3525 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3526 return TRAINER_SPELL_RED
;
3528 return TRAINER_SPELL_GREEN
;
3531 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3533 uint32 guid
= GUID_LOPART(playerguid
);
3535 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3536 // bones will be deleted by corpse/bones deleting thread shortly
3537 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3539 // remove from guild
3540 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3543 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3545 guild
->DelMember(guid
);
3548 // the player was uninvited already on logout so just remove from group
3549 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3552 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3554 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3557 RemoveFromGroup(group
, playerguid
);
3561 // remove signs from petitions (also remove petitions if owner);
3562 RemovePetitionsAndSigns(playerguid
, 10);
3564 // return back all mails with COD and Item 0 1 2 3 4 5 6
3565 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
);
3570 Field
*fields
= resultMail
->Fetch();
3572 uint32 mail_id
= fields
[0].GetUInt32();
3573 uint16 mailTemplateId
= fields
[1].GetUInt16();
3574 uint32 sender
= fields
[2].GetUInt32();
3575 std::string subject
= fields
[3].GetCppString();
3576 uint32 itemTextId
= fields
[4].GetUInt32();
3577 uint32 money
= fields
[5].GetUInt32();
3578 bool has_items
= fields
[6].GetBool();
3580 //we can return mail now
3581 //so firstly delete the old one
3582 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3587 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id
);
3592 Field
*fields2
= resultItems
->Fetch();
3594 uint32 item_guidlow
= fields2
[0].GetUInt32();
3595 uint32 item_template
= fields2
[1].GetUInt32();
3597 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3600 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3604 Item
*pItem
= NewItemOrBag(itemProto
);
3605 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
)))
3607 pItem
->FSetState(ITEM_REMOVED
);
3608 pItem
->SaveToDB(); // it also deletes item object !
3612 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3614 while (resultItems
->NextRow());
3620 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3622 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3624 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3626 while (resultMail
->NextRow());
3631 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3632 // Get guids of character's pets, will deleted in transaction
3633 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3635 // NOW we can finally clear other DB data related to character
3636 CharacterDatabase
.BeginTransaction();
3641 Field
*fields3
= resultPets
->Fetch();
3642 uint32 petguidlow
= fields3
[0].GetUInt32();
3643 Pet::DeleteFromDB(petguidlow
);
3644 } while (resultPets
->NextRow());
3648 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3649 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3650 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3651 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3652 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3653 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3654 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3655 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3656 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3657 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3658 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3659 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3660 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3661 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3662 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3663 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3664 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3665 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3666 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3667 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3668 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3669 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3670 CharacterDatabase
.CommitTransaction();
3672 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3673 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3676 void Player::SetMovement(PlayerMovementType pType
)
3681 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3682 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3683 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3684 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3686 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3689 data
.append(GetPackGUID());
3691 GetSession()->SendPacket( &data
);
3695 - a resurrectable corpse must not be loaded for the player (only bones)
3696 - the player must be in world
3698 void Player::BuildPlayerRepop()
3700 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3701 data
.append(GetPackGUID());
3702 GetSession()->SendPacket(&data
);
3704 if(getRace() == RACE_NIGHTELF
)
3705 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)
3706 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3708 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3709 // there must be SMSG.STOP_MIRROR_TIMER
3710 // there we must send 888 opcode
3712 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3715 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3719 // create a corpse and place it at the player's location
3721 Corpse
*corpse
= GetCorpse();
3724 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3727 GetMap()->Add(corpse
);
3729 // convert player body to ghost
3732 SetMovement(MOVE_WATER_WALK
);
3733 if(!GetSession()->isLogingOut())
3734 SetMovement(MOVE_UNROOT
);
3736 // BG - remove insignia related
3737 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3739 SendCorpseReclaimDelay();
3741 // to prevent cheating
3742 corpse
->ResetGhostTime();
3744 StopMirrorTimers(); //disable timers(bars)
3746 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3748 SetByteValue(UNIT_FIELD_BYTES_1
, 3, PLAYER_STATE_FLAG_ALWAYS_STAND
);
3751 void Player::SendDelayResponse(const uint32 ml_seconds
)
3753 //FIXME: is this delay time arg really need? 50msec by default in code
3754 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3755 data
<< (uint32
)time(NULL
);
3757 GetSession()->SendPacket( &data
);
3760 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3762 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3767 GetSession()->SendPacket(&data
);
3769 // speed change, land walk
3771 // remove death flag + set aura
3772 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3773 if(getRace() == RACE_NIGHTELF
)
3774 RemoveAurasDueToSpell(20584); // speed bonuses
3775 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3777 setDeathState(ALIVE
);
3779 SetMovement(MOVE_LAND_WALK
);
3780 SetMovement(MOVE_UNROOT
);
3784 // set health/powers (0- will be set in caller)
3785 if(restore_percent
>0.0f
)
3787 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3788 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3789 SetPower(POWER_RAGE
, 0);
3790 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3793 // update visibility
3794 ObjectAccessor::UpdateVisibilityForPlayer(this);
3796 // some items limited to specific map
3797 DestroyZoneLimitedItem( true, GetZoneId());
3802 //Characters from level 1-10 are not affected by resurrection sickness.
3803 //Characters from level 11-19 will suffer from one minute of sickness
3804 //for each level they are above 10.
3805 //Characters level 20 and up suffer from ten minutes of sickness.
3806 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3808 if(int32(getLevel()) >= startLevel
)
3810 // set resurrection sickness
3811 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3813 // not full duration
3814 if(int32(getLevel()) < startLevel
+9)
3816 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3818 for(int i
=0; i
< 3; ++i
)
3820 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3822 Aur
->SetAuraDuration(delta
*1000);
3823 Aur
->SendAuraUpdate(false);
3830 void Player::KillPlayer()
3832 SetMovement(MOVE_ROOT
);
3834 StopMirrorTimers(); //disable timers(bars)
3836 setDeathState(CORPSE
);
3837 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3839 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3840 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3842 // 6 minutes until repop at graveyard
3843 m_deathTimer
= 6*MINUTE
*1000;
3845 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3847 // don't create corpse at this moment, player might be falling
3849 // update visibility
3850 ObjectAccessor::UpdateObjectVisibility(this);
3853 void Player::CreateCorpse()
3855 // prevent existence 2 corpse for player
3858 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3860 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3863 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3864 GetPositionY(), GetPositionZ(), GetOrientation()))
3870 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3871 _pb
= GetUInt32Value(PLAYER_BYTES
);
3872 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3874 uint8 race
= (uint8
)(_uf
);
3875 uint8 skin
= (uint8
)(_pb
);
3876 uint8 face
= (uint8
)(_pb
>> 8);
3877 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3878 uint8 haircolor
= (uint8
)(_pb
>> 24);
3879 uint8 facialhair
= (uint8
)(_pb2
);
3881 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3882 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3884 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3885 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3887 uint32 flags
= CORPSE_FLAG_UNK2
;
3888 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3889 flags
|= CORPSE_FLAG_HIDE_HELM
;
3890 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3891 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3892 if(InBattleGround())
3893 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3894 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3896 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3898 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3901 uint16 iIventoryType
;
3903 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3907 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3908 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3910 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3911 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3915 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3916 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3918 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3921 // register for player, but not show
3922 ObjectAccessor::Instance().AddCorpse(corpse
);
3925 void Player::SpawnCorpseBones()
3927 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3928 SaveToDB(); // prevent loading as ghost without corpse
3931 Corpse
* Player::GetCorpse() const
3933 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3936 void Player::DurabilityLossAll(double percent
, bool inventory
)
3938 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3939 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3940 DurabilityLoss(pItem
,percent
);
3944 // bags not have durability
3945 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3947 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3948 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3949 DurabilityLoss(pItem
,percent
);
3951 // keys not have durability
3952 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3954 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3955 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3956 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
3957 if(Item
* pItem
= GetItemByPos( i
, j
))
3958 DurabilityLoss(pItem
,percent
);
3962 void Player::DurabilityLoss(Item
* item
, double percent
)
3967 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3972 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
3974 if(pDurabilityLoss
< 1 )
3975 pDurabilityLoss
= 1;
3977 DurabilityPointsLoss(item
,pDurabilityLoss
);
3980 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
3982 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3983 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3984 DurabilityPointsLoss(pItem
,points
);
3988 // bags not have durability
3989 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3991 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3992 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3993 DurabilityPointsLoss(pItem
,points
);
3995 // keys not have durability
3996 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3998 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3999 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4000 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4001 if(Item
* pItem
= GetItemByPos( i
, j
))
4002 DurabilityPointsLoss(pItem
,points
);
4006 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4008 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4009 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4010 int32 pNewDurability
= pOldDurability
- points
;
4012 if (pNewDurability
< 0)
4014 else if (pNewDurability
> pMaxDurability
)
4015 pNewDurability
= pMaxDurability
;
4017 if (pOldDurability
!= pNewDurability
)
4019 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4020 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4021 _ApplyItemMods(item
,item
->GetSlot(), false);
4023 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4025 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4026 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4027 _ApplyItemMods(item
,item
->GetSlot(), true);
4029 item
->SetState(ITEM_CHANGED
, this);
4033 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4035 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4036 DurabilityPointsLoss(pItem
,1);
4039 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4041 uint32 TotalCost
= 0;
4042 // equipped, backpack, bags itself
4043 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4044 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4046 // bank, buyback and keys not repaired
4048 // items in inventory bags
4049 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4050 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4051 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4055 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4057 Item
* item
= GetItemByPos(pos
);
4059 uint32 TotalCost
= 0;
4063 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4067 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4071 uint32 LostDurability
= maxDurability
- curDurability
;
4072 if(LostDurability
>0)
4074 ItemPrototype
const *ditemProto
= item
->GetProto();
4076 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4079 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4083 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4084 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4085 if(!dQualitymodEntry
)
4087 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4091 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4092 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4094 costs
= uint32(costs
* discountMod
);
4096 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4101 if (GetGuildId()==0)
4103 DEBUG_LOG("You are not member of a guild");
4107 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4111 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4113 DEBUG_LOG("You do not have rights to withdraw for repairs");
4117 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4119 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4123 if (pGuild
->GetGuildBankMoney() < costs
)
4125 DEBUG_LOG("There is not enough money in bank");
4129 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4132 else if (GetMoney() < costs
)
4134 DEBUG_LOG("You do not have enough money");
4138 ModifyMoney( -int32(costs
) );
4142 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4143 item
->SetState(ITEM_CHANGED
, this);
4145 // reapply mods for total broken and repaired item if equipped
4146 if(IsEquipmentPos(pos
) && !curDurability
)
4147 _ApplyItemMods(item
,pos
& 255, true);
4151 void Player::RepopAtGraveyard()
4153 // note: this can be called also when the player is alive
4154 // for example from WorldSession::HandleMovementOpcodes
4156 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4158 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4159 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4161 ResurrectPlayer(0.5f
);
4165 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4167 // Special handle for battleground maps
4168 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4170 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4171 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4173 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4175 // stop countdown until repop
4178 // if no grave found, stay at the current location
4179 // and don't show spirit healer location
4182 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4183 if(isDead()) // not send if alive, because it used in TeleportTo()
4185 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4186 data
<< ClosestGrave
->map_id
;
4187 data
<< ClosestGrave
->x
;
4188 data
<< ClosestGrave
->y
;
4189 data
<< ClosestGrave
->z
;
4190 GetSession()->SendPacket(&data
);
4195 void Player::JoinedChannel(Channel
*c
)
4197 m_channels
.push_back(c
);
4200 void Player::LeftChannel(Channel
*c
)
4202 m_channels
.remove(c
);
4205 void Player::CleanupChannels()
4207 while(!m_channels
.empty())
4209 Channel
* ch
= *m_channels
.begin();
4210 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4211 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4212 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4213 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4216 sLog
.outDebug("Player: channels cleaned up!");
4219 void Player::UpdateLocalChannels(uint32 newZone
)
4221 if(m_channels
.empty())
4224 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4228 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4232 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4234 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4238 // skip non built-in channels
4239 if(!(*i
)->IsConstant())
4242 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4246 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4250 char new_channel_name_buf
[100];
4251 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4252 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4254 if((*i
)!=new_channel
)
4256 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4258 // leave old channel
4259 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4260 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4261 LeftChannel(*i
); // remove from player's channel list
4262 cMgr
->LeftChannel(name
); // delete if empty
4265 sLog
.outDebug("Player: channels cleaned up!");
4268 void Player::LeaveLFGChannel()
4270 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4274 (*i
)->Leave(GetGUID());
4280 void Player::UpdateDefense()
4282 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4284 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4286 // update dependent from defense skill part
4287 UpdateDefenseBonusesMod();
4291 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4293 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4295 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4304 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4307 if(amount
<= -100.0f
)
4310 val
= (100.0f
+ amount
) / 100.0f
;
4311 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4315 if(!CanModifyStats())
4320 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4321 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4322 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4323 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4328 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4330 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4332 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4336 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4339 return m_auraBaseMod
[modGroup
][modType
];
4342 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4344 if(modGroup
>= BASEMOD_END
)
4346 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4350 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4353 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4356 uint32
Player::GetShieldBlockValue() const
4358 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4360 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
)/20 - 1;
4362 value
= (value
< 0) ? 0 : value
;
4364 return uint32(value
);
4367 float Player::GetMeleeCritFromAgility()
4369 uint32 level
= getLevel();
4370 uint32 pclass
= getClass();
4372 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4374 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4375 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4376 if (critBase
==NULL
|| critRatio
==NULL
)
4379 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4383 float Player::GetDodgeFromAgility()
4385 // Table for base dodge values
4386 float dodge_base
[MAX_CLASSES
] = {
4388 0.00652f
, // Paladin
4395 0.02011f
, // Warlock
4399 // Crit/agility to dodge/agility coefficient multipliers
4400 float crit_to_dodge
[MAX_CLASSES
] = {
4414 uint32 level
= getLevel();
4415 uint32 pclass
= getClass();
4417 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4419 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4420 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4421 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4424 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4425 return dodge
*100.0f
;
4428 float Player::GetSpellCritFromIntellect()
4430 uint32 level
= getLevel();
4431 uint32 pclass
= getClass();
4433 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4435 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4436 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4437 if (critBase
==NULL
|| critRatio
==NULL
)
4440 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4444 float Player::GetRatingCoefficient(CombatRating cr
) const
4446 uint32 level
= getLevel();
4448 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4450 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4452 return 1.0f
; // By default use minimum coefficient (not must be called)
4454 return Rating
->ratio
;
4457 float Player::GetRatingBonusValue(CombatRating cr
) const
4459 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4462 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4464 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4465 if (melee
>25.0f
) melee
= 25.0f
;
4466 return uint32 (melee
* damage
/100.0f
);
4469 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4471 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4472 if (ranged
>25.0f
) ranged
=25.0f
;
4473 return uint32 (ranged
* damage
/100.0f
);
4476 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4478 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4479 // In wow script resilience limited to 25%
4482 return uint32 (spell
* damage
/ 100.0f
);
4485 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4487 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4488 // Dot resilience not limited (limit it by 100%)
4489 if (spellDot
> 100.0f
)
4491 return uint32 (spellDot
* damage
/ 100.0f
);
4494 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4499 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4501 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4508 float Player::OCTRegenHPPerSpirit()
4510 uint32 level
= getLevel();
4511 uint32 pclass
= getClass();
4513 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4515 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4516 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4517 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4520 // Formula from PaperDollFrame script
4521 float spirit
= GetStat(STAT_SPIRIT
);
4522 float baseSpirit
= spirit
;
4523 if (baseSpirit
>50) baseSpirit
= 50;
4524 float moreSpirit
= spirit
- baseSpirit
;
4525 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4529 float Player::OCTRegenMPPerSpirit()
4531 uint32 level
= getLevel();
4532 uint32 pclass
= getClass();
4534 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4536 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4537 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4538 if (moreRatio
==NULL
)
4541 // Formula get from PaperDollFrame script
4542 float spirit
= GetStat(STAT_SPIRIT
);
4543 float regen
= spirit
* moreRatio
->ratio
;
4547 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4549 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, value
, apply
);
4551 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4552 float RatingChange
= 0.0f
;
4554 bool affectStats
= CanModifyStats();
4558 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4559 case CR_DEFENSE_SKILL
:
4560 UpdateDefenseBonusesMod();
4563 UpdateDodgePercentage();
4566 UpdateParryPercentage();
4569 UpdateBlockPercentage();
4572 RatingChange
= value
/ RatingCoeffecient
;
4573 m_modMeleeHitChance
+= apply
? RatingChange
: -RatingChange
;
4576 RatingChange
= value
/ RatingCoeffecient
;
4577 m_modRangedHitChance
+= apply
? RatingChange
: -RatingChange
;
4580 RatingChange
= value
/ RatingCoeffecient
;
4581 m_modSpellHitChance
+= apply
? RatingChange
: -RatingChange
;
4586 UpdateCritPercentage(BASE_ATTACK
);
4587 UpdateCritPercentage(OFF_ATTACK
);
4590 case CR_CRIT_RANGED
:
4592 UpdateCritPercentage(RANGED_ATTACK
);
4596 UpdateAllSpellCritChances();
4598 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4599 case CR_HIT_TAKEN_RANGED
:
4601 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4603 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4604 case CR_CRIT_TAKEN_RANGED
:
4606 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4608 case CR_HASTE_MELEE
:
4609 RatingChange
= value
/ RatingCoeffecient
;
4610 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4611 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4613 case CR_HASTE_RANGED
:
4614 RatingChange
= value
/ RatingCoeffecient
;
4615 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4617 case CR_HASTE_SPELL
:
4618 RatingChange
= value
/ RatingCoeffecient
;
4619 ApplyCastTimePercentMod(RatingChange
,apply
);
4621 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4622 case CR_WEAPON_SKILL_OFFHAND
:
4623 case CR_WEAPON_SKILL_RANGED
:
4628 UpdateExpertise(BASE_ATTACK
);
4629 UpdateExpertise(OFF_ATTACK
);
4635 void Player::SetRegularAttackTime()
4637 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4639 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4640 if(tmpitem
&& !tmpitem
->IsBroken())
4642 ItemPrototype
const *proto
= tmpitem
->GetProto();
4644 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4646 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4651 //skill+step, checking for max value
4652 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4658 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4659 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4662 if(i
>=PLAYER_MAX_SKILLS
)
4665 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4666 uint32 value
= SKILL_VALUE(data
);
4667 uint32 max
= SKILL_MAX(data
);
4669 if ((!max
) || (!value
) || (value
>= max
))
4672 if (value
*512 < max
*urand(0,512))
4674 uint32 new_value
= value
+step
;
4678 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4679 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4686 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4688 if ( SkillValue
>= GrayLevel
)
4689 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4690 if ( SkillValue
>= GreenLevel
)
4691 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4692 if ( SkillValue
>= YellowLevel
)
4693 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4694 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4697 bool Player::UpdateCraftSkill(uint32 spellid
)
4699 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4701 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4702 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4704 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4706 if(_spell_idx
->second
->skillId
)
4708 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4710 // Alchemy Discoveries here
4711 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4712 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4714 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4715 learnSpell(discoveredSpell
);
4718 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4720 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4721 _spell_idx
->second
->max_value
,
4722 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4723 _spell_idx
->second
->min_value
),
4730 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4732 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4734 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4736 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4739 case SKILL_HERBALISM
:
4740 case SKILL_LOCKPICKING
:
4741 case SKILL_JEWELCRAFTING
:
4742 case SKILL_INSCRIPTION
:
4743 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4744 case SKILL_SKINNING
:
4745 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4746 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4748 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4750 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4751 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4753 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4758 bool Player::UpdateFishingSkill()
4760 sLog
.outDebug("UpdateFishingSkill");
4762 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4764 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4766 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4768 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4771 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4773 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4777 if(Chance
<= 0) // speedup in 0 chance case
4779 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4784 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4785 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4786 if ( i
>= PLAYER_MAX_SKILLS
)
4789 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4790 uint16 SkillValue
= SKILL_VALUE(data
);
4791 uint16 MaxValue
= SKILL_MAX(data
);
4793 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4796 int32 Roll
= irand(1,1000);
4798 if ( Roll
<= Chance
)
4800 uint32 new_value
= SkillValue
+step
;
4801 if(new_value
> MaxValue
)
4802 new_value
= MaxValue
;
4804 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4805 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4806 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4810 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4814 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4816 // no skill gain in pvp
4817 Unit
*pVictim
= getVictim();
4818 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4822 return; // always maximized SKILL_FERAL_COMBAT in fact
4824 if(m_form
== FORM_TREE
)
4825 return; // use weapon but not skill up
4827 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4833 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4836 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4837 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4838 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4844 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4846 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4850 UpdateAllCritPercentages();
4853 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, MeleeHitOutcome outcome
, bool defence
)
4857 case MELEE_HIT_CRIT
:
4858 case MELEE_HIT_DODGE
:
4859 case MELEE_HIT_PARRY
:
4860 case MELEE_HIT_BLOCK
:
4861 case MELEE_HIT_BLOCK_CRIT
:
4868 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4869 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4870 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4871 if(moblevel
< greylevel
)
4874 if (moblevel
> plevel
+ 5)
4875 moblevel
= plevel
+ 5;
4877 uint32 lvldif
= moblevel
- greylevel
;
4881 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4885 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4888 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4889 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4892 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4894 if(roll_chance_f(chance
))
4899 UpdateWeaponSkill(attType
);
4905 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4907 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4908 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4910 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4911 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4912 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4914 if(talent
) // permanent bonus stored in high part
4915 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4916 else // temporary/item bonus stored in low part
4917 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
4922 void Player::UpdateSkillsForLevel()
4924 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
4925 uint32 maxSkill
= GetMaxSkillValueForLevel();
4927 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
4929 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4930 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4932 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4934 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
4938 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
4941 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4942 uint32 max
= SKILL_MAX(data
);
4943 uint32 val
= SKILL_VALUE(data
);
4945 /// update only level dependent max skill values
4948 /// miximize skill always
4950 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
4951 /// update max skill value if current max skill not maximized
4952 else if(max
!= maxconfskill
)
4953 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
4958 void Player::UpdateSkillsToMaxSkillsForLevel()
4960 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4961 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4963 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4964 if( IsProfessionSkill(pskill
) || pskill
== SKILL_RIDING
)
4966 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4968 uint32 max
= SKILL_MAX(data
);
4971 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
4973 if(pskill
== SKILL_DEFENSE
)
4974 UpdateDefenseBonusesMod();
4978 // This functions sets a skill line value (and adds if doesn't exist yet)
4979 // To "remove" a skill line, set it's values to zero
4980 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
4986 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4987 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
4989 if(i
<PLAYER_MAX_SKILLS
) //has skill
4993 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4994 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4998 // clear skill fields
4999 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5000 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5001 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5003 // remove spells that depend on this skill when removing the skill
5004 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
5007 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
5010 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(itr
->first
);
5011 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(itr
->first
);
5013 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
5015 if (_spell_idx
->second
->skillId
== id
)
5017 // this may remove more than one spell (dependents)
5018 removeSpell(itr
->first
);
5019 next
= m_spells
.begin();
5026 else if(currVal
) //add
5028 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5029 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5031 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5034 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5037 // enable unlearn button for primary professions only
5038 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5039 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5041 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5042 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5043 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5045 // apply skill bonuses
5046 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5048 // temporary bonuses
5049 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5050 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5051 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5052 (*i
)->ApplyModifier(true);
5054 // permanent bonuses
5055 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5056 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5057 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5058 (*i
)->ApplyModifier(true);
5060 // Learn all spells for skill
5061 learnSkillRewardedSpells(id
);
5067 bool Player::HasSkill(uint32 skill
) const
5069 if(!skill
)return false;
5070 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5072 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5080 uint16
Player::GetSkillValue(uint32 skill
) const
5085 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5087 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5089 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5091 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5092 result
+= SKILL_TEMP_BONUS(bonus
);
5093 result
+= SKILL_PERM_BONUS(bonus
);
5094 return result
< 0 ? 0 : result
;
5100 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5103 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5105 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5107 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5109 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5110 result
+= SKILL_TEMP_BONUS(bonus
);
5111 result
+= SKILL_PERM_BONUS(bonus
);
5112 return result
< 0 ? 0 : result
;
5118 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5121 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5123 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5125 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5131 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5134 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5136 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5138 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5139 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5140 return result
< 0 ? 0 : result
;
5146 uint16
Player::GetPureSkillValue(uint32 skill
) const
5149 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5151 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5153 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5159 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5164 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5166 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5168 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5175 void Player::SendInitialActionButtons()
5177 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5179 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5180 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5182 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5183 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5185 data
<< uint16(itr
->second
.action
);
5186 data
<< uint8(itr
->second
.misc
);
5187 data
<< uint8(itr
->second
.type
);
5195 GetSession()->SendPacket( &data
);
5196 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5199 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5201 if(button
>= MAX_ACTION_BUTTONS
)
5203 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5207 // check cheating with adding non-known spells to action bar
5208 if(type
==ACTION_BUTTON_SPELL
)
5210 if(!sSpellStore
.LookupEntry(action
))
5212 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5216 if(!HasSpell(action
))
5218 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5223 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5225 if (buttonItr
==m_actionButtons
.end())
5226 { // just add new button
5227 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5230 { // change state of current button
5231 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5232 buttonItr
->second
= ActionButton(action
,type
,misc
);
5233 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5236 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5239 void Player::removeActionButton(uint8 button
)
5241 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5242 if (buttonItr
==m_actionButtons
.end())
5245 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5246 m_actionButtons
.erase(buttonItr
); // new and not saved
5248 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5250 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5253 void Player::SetDontMove(bool dontMove
)
5255 m_dontMove
= dontMove
;
5258 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5260 // prevent crash when a bad coord is sent by the client
5261 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5263 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5269 const float old_x
= GetPositionX();
5270 const float old_y
= GetPositionY();
5271 const float old_z
= GetPositionZ();
5272 const float old_r
= GetOrientation();
5274 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5276 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5277 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5279 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5281 // move and update visible state if need
5282 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5284 // reread after Map::Relocation
5291 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5292 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5295 // code block for underwater state update
5296 UpdateUnderwaterState(m
, x
, y
, z
);
5298 CheckExploreSystem();
5303 void Player::SaveRecallPosition()
5305 m_recallMap
= GetMapId();
5306 m_recallX
= GetPositionX();
5307 m_recallY
= GetPositionY();
5308 m_recallZ
= GetPositionZ();
5309 m_recallO
= GetOrientation();
5312 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5314 GetMap()->MessageBroadcast(this, data
, self
);
5317 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5319 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5322 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5324 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5327 void Player::SendDirectMessage(WorldPacket
*data
)
5329 GetSession()->SendPacket(data
);
5332 void Player::CheckExploreSystem()
5340 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5341 if(areaFlag
==0xffff)
5343 int offset
= areaFlag
/ 32;
5347 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
);
5351 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5352 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5354 if( !(currFields
& val
) )
5356 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5358 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5360 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5363 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5365 else if(p
->area_level
> 0)
5367 uint32 area
= p
->ID
;
5368 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5370 SendExplorationExperience(area
,0);
5374 int32 diff
= int32(getLevel()) - p
->area_level
;
5378 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5382 int32 exploration_percent
= (100-((diff
-5)*5));
5383 if (exploration_percent
> 100)
5384 exploration_percent
= 100;
5385 else if (exploration_percent
< 0)
5386 exploration_percent
= 0;
5388 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5392 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5396 SendExplorationExperience(area
,XP
);
5398 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5403 uint32
Player::TeamForRace(uint8 race
)
5405 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5408 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5412 switch(rEntry
->TeamID
)
5414 case 7: return ALLIANCE
;
5415 case 1: return HORDE
;
5418 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5422 uint32
Player::getFactionForRace(uint8 race
)
5424 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5427 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5431 return rEntry
->FactionID
;
5434 void Player::setFactionForRace(uint8 race
)
5436 m_team
= TeamForRace(race
);
5437 setFaction( getFactionForRace(race
) );
5440 void Player::UpdateReputation() const
5442 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5444 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5446 SendFactionState(&(itr
->second
));
5450 void Player::SendFactionState(FactionState
const* faction
) const
5452 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5454 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5455 data
<< (float) 0; // unk 2.4.0
5456 data
<< (uint8
) 0; // wotlk 8634
5457 data
<< (uint32
) 1; // count
5459 data
<< (uint32
) faction
->ReputationListID
;
5460 data
<< (uint32
) faction
->Standing
;
5462 GetSession()->SendPacket(&data
);
5466 void Player::SendInitialReputations()
5468 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5469 data
<< uint32 (0x00000080);
5473 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); itr
++)
5475 // fill in absent fields
5476 for (; a
!= itr
->first
; a
++)
5478 data
<< uint8 (0x00);
5479 data
<< uint32 (0x00000000);
5482 // fill in encountered data
5483 data
<< uint8 (itr
->second
.Flags
);
5484 data
<< uint32 (itr
->second
.Standing
);
5489 // fill in absent fields
5490 for (; a
!= 128; a
++)
5492 data
<< uint8 (0x00);
5493 data
<< uint32 (0x00000000);
5496 GetSession()->SendPacket(&data
);
5499 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5501 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5502 if (itr
!= m_factions
.end())
5503 return &itr
->second
;
5508 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5510 // not allow declare war to own faction
5511 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5515 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5519 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5521 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5523 faction
->Changed
= true;
5526 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5528 // always invisible or hidden faction can't be inactive
5529 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5533 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5537 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5539 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5541 faction
->Changed
= true;
5544 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5546 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5548 if(!factionTemplateEntry
)
5551 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5554 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5556 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5560 if(factionEntry
->reputationListID
< 0)
5563 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5564 if (itr
== m_factions
.end())
5567 SetFactionVisible(&itr
->second
);
5570 void Player::SetFactionVisible(FactionState
* faction
)
5572 // always invisible or hidden faction can't be make visible
5573 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5577 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5580 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5581 faction
->Changed
= true;
5583 if(!m_session
->PlayerLoading())
5585 // make faction visible in reputation list at client
5586 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5587 data
<< faction
->ReputationListID
;
5588 GetSession()->SendPacket(&data
);
5592 void Player::SetInitialFactions()
5594 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5596 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5598 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5600 FactionState newFaction
;
5601 newFaction
.ID
= factionEntry
->ID
;
5602 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5603 newFaction
.Standing
= 0;
5604 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5605 newFaction
.Changed
= true;
5607 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5612 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5617 uint32 raceMask
= getRaceMask();
5618 uint32 classMask
= getClassMask();
5619 for (int i
=0; i
< 4; i
++)
5621 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5622 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5623 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5624 return factionEntry
->ReputationFlags
[i
];
5629 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5634 uint32 raceMask
= getRaceMask();
5635 uint32 classMask
= getClassMask();
5636 for (int i
=0; i
< 4; i
++)
5638 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5639 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5640 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5641 return factionEntry
->BaseRepValue
[i
];
5644 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5648 int32
Player::GetReputation(uint32 faction_id
) const
5650 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5654 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5658 return GetReputation(factionEntry
);
5661 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5663 // Faction without recorded reputation. Just ignore.
5667 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5668 if (itr
!= m_factions
.end())
5669 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5674 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5676 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5678 return MIN_REPUTATION_RANK
;
5680 return GetReputationRank(factionEntry
);
5683 ReputationRank
Player::ReputationToRank(int32 standing
) const
5685 int32 Limit
= Reputation_Cap
+ 1;
5686 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5688 Limit
-= ReputationRank_Length
[i
];
5689 if (standing
>= Limit
)
5690 return ReputationRank(i
);
5692 return MIN_REPUTATION_RANK
;
5695 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5697 int32 Reputation
= GetReputation(factionEntry
);
5698 return ReputationToRank(Reputation
);
5701 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5703 int32 Reputation
= GetBaseReputation(factionEntry
);
5704 return ReputationToRank(Reputation
);
5707 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5709 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5711 if(!factionTemplateEntry
)
5713 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5717 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5719 // Faction without recorded reputation. Just ignore.
5723 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5726 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5728 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5732 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5734 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5735 if(factionEntryCalc
)
5736 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5741 return ModifyOneFactionReputation(factionEntry
, standing
);
5744 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5746 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5747 if (itr
!= m_factions
.end())
5749 int32 BaseRep
= GetBaseReputation(factionEntry
);
5750 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5752 if (new_rep
> Reputation_Cap
)
5753 new_rep
= Reputation_Cap
;
5755 if (new_rep
< Reputation_Bottom
)
5756 new_rep
= Reputation_Bottom
;
5758 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5759 SetFactionAtWar(&itr
->second
,true);
5761 itr
->second
.Standing
= new_rep
- BaseRep
;
5762 itr
->second
.Changed
= true;
5764 SetFactionVisible(&itr
->second
);
5766 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5768 if(uint32 questid
= GetQuestSlotQuestId(i
))
5770 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5771 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5773 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5774 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5776 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5777 if ( CanCompleteQuest( questid
) )
5778 CompleteQuest( questid
);
5780 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5782 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5783 IncompleteQuest( questid
);
5788 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5789 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5790 SendFactionState(&(itr
->second
));
5797 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5799 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5801 if(!factionTemplateEntry
)
5803 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5807 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5809 // Faction without recorded reputation. Just ignore.
5813 return SetFactionReputation(factionEntry
, standing
);
5816 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5818 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5822 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5824 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5825 if(factionEntryCalc
)
5826 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5831 return SetOneFactionReputation(factionEntry
, standing
);
5834 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5836 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5837 if (itr
!= m_factions
.end())
5839 if (standing
> Reputation_Cap
)
5840 standing
= Reputation_Cap
;
5842 if (standing
< Reputation_Bottom
)
5843 standing
= Reputation_Bottom
;
5845 int32 BaseRep
= GetBaseReputation(factionEntry
);
5846 itr
->second
.Standing
= standing
- BaseRep
;
5847 itr
->second
.Changed
= true;
5849 SetFactionVisible(&itr
->second
);
5851 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5852 SetFactionAtWar(&itr
->second
,true);
5854 SendFactionState(&(itr
->second
));
5855 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5856 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5862 //Calculate total reputation percent player gain with quest/creature level
5863 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5865 // for grey creature kill received 20%, in other case 100.
5866 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5868 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5870 percent
+= rep
> 0 ? repMod
: -repMod
;
5875 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5878 //Calculates how many reputation points player gains in victim's enemy factions
5879 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5881 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5884 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5889 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5891 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5892 donerep1
= int32(donerep1
*rate
);
5893 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5894 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5895 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5896 ModifyFactionReputation(factionEntry1
, donerep1
);
5898 // Wiki: Team factions value divided by 2
5899 if(Rep
->is_teamaward1
)
5901 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5902 if(team1_factionEntry
)
5903 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5907 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5909 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5910 donerep2
= int32(donerep2
*rate
);
5911 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5912 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5913 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5914 ModifyFactionReputation(factionEntry2
, donerep2
);
5916 // Wiki: Team factions value divided by 2
5917 if(Rep
->is_teamaward2
)
5919 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5920 if(team2_factionEntry
)
5921 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
5926 //Calculate how many reputation points player gain with the quest
5927 void Player::RewardReputation(Quest
const *pQuest
)
5929 // quest reputation reward/loss
5930 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5932 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5934 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
5935 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5937 ModifyFactionReputation(factionEntry
, rep
);
5941 // TODO: implement reputation spillover
5944 void Player::UpdateArenaFields(void)
5946 /* arena calcs go here */
5949 void Player::UpdateHonorFields()
5951 /// called when rewarding honor and at each save
5952 uint64 now
= time(NULL
);
5953 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5955 if(m_lastHonorUpdateTime
< today
)
5957 uint64 yesterday
= today
- DAY
;
5959 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5961 // update yesterday's contribution
5962 if(m_lastHonorUpdateTime
>= yesterday
)
5964 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5966 // this is the first update today, reset today's contribution
5967 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5968 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5972 // no honor/kills yesterday or today, reset
5973 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5974 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5978 m_lastHonorUpdateTime
= now
;
5981 ///Calculate the amount of honor gained based on the victim
5982 ///and the size of the group for which the honor is divided
5983 ///An exact honor value can also be given (overriding the calcs)
5984 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5986 // do not reward honor in arenas, but enable onkill spellproc
5989 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5992 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5998 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5999 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6002 uint64 victim_guid
= 0;
6003 uint32 victim_rank
= 0;
6005 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6006 UpdateHonorFields();
6010 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6013 victim_guid
= uVictim
->GetGUID();
6015 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6017 Player
*pVictim
= (Player
*)uVictim
;
6019 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6022 float f
= 1; //need for total kills (?? need more info)
6024 uint32 k_level
= getLevel();
6025 uint32 v_level
= pVictim
->getLevel();
6028 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6030 // [1..14] Alliance honor titles and player name
6031 // [15..28] Horde honor titles and player name
6032 // [29..38] Other title and player name
6034 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6035 // Get Killer titles, CharTitlesEntry::bit_index
6037 // title[1..14] -> rank[5..18]
6038 // title[15..28] -> rank[5..18]
6039 // title[other] -> 0
6040 if (victim_title
== 0)
6041 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6042 else if (victim_title
< 15)
6043 victim_rank
= victim_title
+ 4;
6044 else if (victim_title
< 29)
6045 victim_rank
= victim_title
- 14 + 4;
6047 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6052 else if( k_level
<= 39 )
6053 k_grey
= k_level
- 5 - k_level
/10;
6055 k_grey
= k_level
- 1 - k_level
/5;
6060 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6062 int32 v_rank
=1; //need more info
6064 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6065 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6067 // count the number of playerkills in one day
6068 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6069 // and those in a lifetime
6070 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6074 Creature
*cVictim
= (Creature
*)uVictim
;
6076 if (!cVictim
->isRacialLeader())
6079 honor
= 100; // ??? need more info
6080 victim_rank
= 19; // HK: Leader
6084 if (uVictim
!= NULL
)
6086 honor
*= sWorld
.getRate(RATE_HONOR
);
6091 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6094 // honor - for show honor points in log
6095 // victim_guid - for show victim name in log
6096 // victim_rank [1..4] HK: <dishonored rank>
6097 // victim_rank [5..19] HK: <alliance\horde rank>
6098 // victim_rank [0,20+] HK: <>
6099 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6100 data
<< (uint32
) honor
;
6101 data
<< (uint64
) victim_guid
;
6102 data
<< (uint32
) victim_rank
;
6104 GetSession()->SendPacket(&data
);
6107 ModifyHonorPoints(int32(honor
));
6109 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6113 void Player::ModifyHonorPoints( int32 value
)
6117 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6118 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6120 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6123 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6126 void Player::ModifyArenaPoints( int32 value
)
6130 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6131 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6133 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6136 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6139 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6141 std::ostringstream ss
;
6142 ss
<<"SELECT guildid FROM guild_member WHERE guid='"<<guid
<<"'";
6143 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6146 uint32 v
= result
->Fetch()[0].GetUInt32();
6154 uint32
Player::GetRankFromDB(uint64 guid
)
6156 std::ostringstream ss
;
6157 ss
<<"SELECT rank FROM guild_member WHERE guid='"<<guid
<<"'";
6158 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6161 uint32 v
= result
->Fetch()[0].GetUInt32();
6169 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6171 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid
), type
);
6175 uint32 id
= (*result
)[0].GetUInt32();
6180 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6182 std::ostringstream ss
;
6184 ss
<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6185 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6188 Field
* fields
= result
->Fetch();
6189 uint32 zone
= fields
[0].GetUInt32();
6194 // stored zone is zero, use generic and slow zone detection
6196 ss
<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6197 result
= CharacterDatabase
.Query(ss
.str().c_str());
6200 fields
= result
->Fetch();
6201 uint32 map
= fields
[0].GetUInt32();
6202 float posx
= fields
[1].GetFloat();
6203 float posy
= fields
[2].GetFloat();
6206 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
);
6209 ss
<< "UPDATE characters SET zone='"<<zone
<<"' WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6210 CharacterDatabase
.Execute(ss
.str().c_str());
6216 void Player::UpdateArea(uint32 newArea
)
6218 // FFA_PVP flags are area and not zone id dependent
6219 // so apply them accordingly
6220 m_areaUpdateId
= newArea
;
6222 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6224 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6227 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6231 // remove ffa flag only if not ffapvp realm
6232 // removal in sanctuaries and capitals is handled in zone update
6233 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6234 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6237 UpdateAreaDependentAuras(newArea
);
6240 void Player::UpdateZone(uint32 newZone
)
6242 m_zoneUpdateId
= newZone
;
6243 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6245 // zone changed, so area changed as well, update it
6246 UpdateArea(GetAreaId());
6248 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6252 if (sWorld
.getConfig(CONFIG_WEATHER
))
6254 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6257 wth
->SendWeatherUpdateToPlayer(this);
6261 if(!sWorld
.AddWeather(zone
->ID
))
6263 // send fine weather packet to remove old zone's weather
6264 Weather::SendFineWeatherUpdateToPlayer(this);
6269 pvpInfo
.inHostileArea
=
6270 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6271 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6272 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6273 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6275 if(pvpInfo
.inHostileArea
) // in hostile area
6277 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6278 UpdatePvP(true, true);
6280 else // in friendly area
6282 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6283 pvpInfo
.endTimer
= time(0); // start toggle-off
6286 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6288 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6289 if(sWorld
.IsFFAPvPRealm())
6290 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6294 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6297 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6299 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6300 SetRestType(REST_TYPE_IN_CITY
);
6301 InnEnter(time(0),GetMapId(),0,0,0);
6303 if(sWorld
.IsFFAPvPRealm())
6304 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6306 else // anywhere else
6308 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6310 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6312 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6314 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6315 SetRestType(REST_TYPE_NO
);
6317 if(sWorld
.IsFFAPvPRealm())
6318 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6321 else // not in tavern (leave city then)
6323 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6324 SetRestType(REST_TYPE_NO
);
6326 // Set player to FFA PVP when not in rested environment.
6327 if(sWorld
.IsFFAPvPRealm())
6328 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6333 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6334 // if player resurrected at teleport this will be applied in resurrect code
6336 DestroyZoneLimitedItem( true, newZone
);
6338 // recent client version not send leave/join channel packets for built-in local channels
6339 UpdateLocalChannels( newZone
);
6343 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6345 UpdateZoneDependentAuras(newZone
);
6348 //If players are too far way of duel flag... then player loose the duel
6349 void Player::CheckDuelDistance(time_t currTime
)
6354 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6355 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6359 if(duel
->outOfBound
== 0)
6361 if(!IsWithinDistInMap(obj
, 50))
6363 duel
->outOfBound
= currTime
;
6365 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6366 GetSession()->SendPacket(&data
);
6371 if(IsWithinDistInMap(obj
, 40))
6373 duel
->outOfBound
= 0;
6375 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6376 GetSession()->SendPacket(&data
);
6378 else if(currTime
>= (duel
->outOfBound
+10))
6380 DuelComplete(DUEL_FLED
);
6385 void Player::DuelComplete(DuelCompleteType type
)
6387 // duel not requested
6391 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6392 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6393 GetSession()->SendPacket(&data
);
6394 duel
->opponent
->GetSession()->SendPacket(&data
);
6396 if(type
!= DUEL_INTERUPTED
)
6398 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6399 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6400 data
<< duel
->opponent
->GetName();
6402 SendMessageToSet(&data
,true);
6405 // cool-down duel spell
6406 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6413 GetSession()->SendPacket(&data);
6414 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6415 data<<duel->opponent->GetGUID();
6419 duel->opponent->GetSession()->SendPacket(&data);*/
6421 //Remove Duel Flag object
6422 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6424 duel
->initiator
->RemoveGameObject(obj
,true);
6427 std::vector
<uint32
> auras2remove
;
6428 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6429 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); i
++)
6431 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6432 auras2remove
.push_back(i
->second
->GetId());
6435 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6436 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6438 auras2remove
.clear();
6439 AuraMap
const& auras
= GetAuras();
6440 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); i
++)
6442 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6443 auras2remove
.push_back(i
->second
->GetId());
6445 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6446 RemoveAurasDueToSpell(auras2remove
[i
]);
6448 // cleanup combo points
6449 if(GetComboTarget()==duel
->opponent
->GetGUID())
6451 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6454 if(duel
->opponent
->GetComboTarget()==GetGUID())
6455 duel
->opponent
->ClearComboPoints();
6456 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6457 duel
->opponent
->ClearComboPoints();
6460 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6461 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6462 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6463 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6465 delete duel
->opponent
->duel
;
6466 duel
->opponent
->duel
= NULL
;
6471 //---------------------------------------------------------//
6473 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6475 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6478 // not apply/remove mods for broken item
6479 if(item
->IsBroken())
6482 ItemPrototype
const *proto
= item
->GetProto();
6487 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6489 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6490 if(attacktype
< MAX_ATTACK
)
6491 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6493 _ApplyItemBonuses(proto
,slot
,apply
);
6495 if( slot
==EQUIPMENT_SLOT_RANGED
)
6496 _ApplyAmmoBonuses();
6498 ApplyItemEquipSpell(item
,apply
);
6499 ApplyEnchantment(item
, apply
);
6501 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6502 CorrectMetaGemEnchants(slot
, apply
);
6504 sLog
.outDebug("_ApplyItemMods complete.");
6507 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6509 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6512 for (int i
= 0; i
< 10; i
++)
6514 uint32 statType
= 0;
6517 if(proto
->ScalingStatDistribution
)
6519 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6521 statType
= ssd
->StatMod
[i
];
6523 if(uint32 modifier
= ssd
->Modifier
[i
])
6525 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6526 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6528 int multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6529 val
= (multiplier
* modifier
) / 10000;
6536 statType
= proto
->ItemStat
[i
].ItemStatType
;
6537 val
= float(proto
->ItemStat
[i
].ItemStatValue
);
6546 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6548 case ITEM_MOD_HEALTH
: // modify HP
6549 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6551 case ITEM_MOD_AGILITY
: // modify agility
6552 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6553 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6555 case ITEM_MOD_STRENGTH
: //modify strength
6556 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6557 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6559 case ITEM_MOD_INTELLECT
: //modify intellect
6560 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6561 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6563 case ITEM_MOD_SPIRIT
: //modify spirit
6564 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6565 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6567 case ITEM_MOD_STAMINA
: //modify stamina
6568 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6569 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6571 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6572 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6574 case ITEM_MOD_DODGE_RATING
:
6575 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6577 case ITEM_MOD_PARRY_RATING
:
6578 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6580 case ITEM_MOD_BLOCK_RATING
:
6581 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6583 case ITEM_MOD_HIT_MELEE_RATING
:
6584 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6586 case ITEM_MOD_HIT_RANGED_RATING
:
6587 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6589 case ITEM_MOD_HIT_SPELL_RATING
:
6590 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6592 case ITEM_MOD_CRIT_MELEE_RATING
:
6593 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6595 case ITEM_MOD_CRIT_RANGED_RATING
:
6596 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6598 case ITEM_MOD_CRIT_SPELL_RATING
:
6599 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6601 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6602 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6604 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6605 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6607 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6608 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6610 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6611 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6613 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6614 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6616 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6617 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6619 case ITEM_MOD_HASTE_MELEE_RATING
:
6620 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6622 case ITEM_MOD_HASTE_RANGED_RATING
:
6623 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6625 case ITEM_MOD_HASTE_SPELL_RATING
:
6626 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6628 case ITEM_MOD_HIT_RATING
:
6629 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6630 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6631 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6633 case ITEM_MOD_CRIT_RATING
:
6634 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6635 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6636 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6638 case ITEM_MOD_HIT_TAKEN_RATING
:
6639 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6640 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6641 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6643 case ITEM_MOD_CRIT_TAKEN_RATING
:
6644 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6645 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6646 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6648 case ITEM_MOD_RESILIENCE_RATING
:
6649 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6650 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6651 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6653 case ITEM_MOD_HASTE_RATING
:
6654 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6655 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6656 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6658 case ITEM_MOD_EXPERTISE_RATING
:
6659 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6661 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6662 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6668 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6671 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6674 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6677 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6679 if (proto
->NatureRes
)
6680 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6682 if (proto
->FrostRes
)
6683 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6685 if (proto
->ShadowRes
)
6686 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6688 if (proto
->ArcaneRes
)
6689 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6691 WeaponAttackType attType
= BASE_ATTACK
;
6692 float damage
= 0.0f
;
6694 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6695 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6696 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6698 attType
= RANGED_ATTACK
;
6700 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6702 attType
= OFF_ATTACK
;
6705 if (proto
->Damage
[0].DamageMin
> 0 )
6707 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6708 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6709 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6712 if (proto
->Damage
[0].DamageMax
> 0 )
6714 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6715 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6718 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6723 if(slot
== EQUIPMENT_SLOT_RANGED
)
6724 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6725 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6726 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6727 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6728 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6731 if(CanModifyStats() && (damage
|| proto
->Delay
))
6732 UpdateDamagePhysical(attType
);
6735 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6737 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6738 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6739 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6741 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6742 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6743 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6745 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6746 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6747 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6750 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6752 // generic not weapon specific case processes in aura code
6753 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6756 BaseModGroup mod
= BASEMOD_END
;
6759 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6760 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6761 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6765 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6767 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6771 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6773 // ignore spell mods for not wands
6774 Modifier
const* modifier
= aura
->GetModifier();
6775 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6778 // generic not weapon specific case processes in aura code
6779 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6782 UnitMods unitMod
= UNIT_MOD_END
;
6785 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6786 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6787 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6791 UnitModifierType unitModType
= TOTAL_VALUE
;
6792 switch(modifier
->m_auraname
)
6794 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6795 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6799 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6801 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6805 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6810 ItemPrototype
const *proto
= item
->GetProto();
6814 for (int i
= 0; i
< 5; i
++)
6816 _Spell
const& spellData
= proto
->Spells
[i
];
6819 if(!spellData
.SpellId
)
6822 // wrong triggering type
6823 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6826 // check if it is valid spell
6827 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6831 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6835 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6839 // Cannot be used in this stance/form
6840 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6843 if(form_change
) // check aura active state from other form
6846 for (int k
=0; k
< 3; ++k
)
6848 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6849 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6851 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6861 if(found
) // and skip re-cast already active aura at form change
6865 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6867 CastSpell(this,spellInfo
,true,item
);
6871 if(form_change
) // check aura compatibility
6873 // Cannot be used in this stance/form
6874 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6875 return; // and remove only not compatible at form change
6879 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6881 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6885 void Player::UpdateEquipSpellsAtFormChange()
6887 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6889 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6891 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6892 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6896 // item set bonuses not dependent from item broken state
6897 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6899 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6903 for(uint32 y
=0;y
<8; ++y
)
6905 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6909 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6910 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6915 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6917 if(!item
|| item
->IsBroken())
6920 ItemPrototype
const *proto
= item
->GetProto();
6924 if (!Target
|| Target
== this )
6927 for (int i
= 0; i
< 5; i
++)
6929 _Spell
const& spellData
= proto
->Spells
[i
];
6932 if(!spellData
.SpellId
)
6935 // wrong triggering type
6936 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6939 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6942 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6946 // not allow proc extra attack spell at extra attack
6947 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6950 float chance
= spellInfo
->procChance
;
6952 if(spellData
.SpellPPMRate
)
6954 uint32 WeaponSpeed
= GetAttackTime(attType
);
6955 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6957 else if(chance
> 100.0f
)
6959 chance
= GetWeaponProcChance();
6962 if (roll_chance_f(chance
))
6963 CastSpell(Target
, spellInfo
->Id
, true, item
);
6966 // item combat enchantments
6967 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6969 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6970 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6971 if(!pEnchant
) continue;
6972 for (int s
=0;s
<3;s
++)
6974 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6977 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6980 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6984 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6985 if (roll_chance_f(chance
))
6987 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6988 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6990 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6996 void Player::_RemoveAllItemMods()
6998 sLog
.outDebug("_RemoveAllItemMods start.");
7000 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7004 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7008 // item set bonuses not dependent from item broken state
7010 RemoveItemsSetItem(this,proto
);
7012 if(m_items
[i
]->IsBroken())
7015 ApplyItemEquipSpell(m_items
[i
],false);
7016 ApplyEnchantment(m_items
[i
], false);
7020 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7024 if(m_items
[i
]->IsBroken())
7026 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7030 uint32 attacktype
= Player::GetAttackBySlot(i
);
7031 if(attacktype
< MAX_ATTACK
)
7032 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7034 _ApplyItemBonuses(proto
,i
, false);
7036 if( i
== EQUIPMENT_SLOT_RANGED
)
7037 _ApplyAmmoBonuses();
7041 sLog
.outDebug("_RemoveAllItemMods complete.");
7044 void Player::_ApplyAllItemMods()
7046 sLog
.outDebug("_ApplyAllItemMods start.");
7048 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7052 if(m_items
[i
]->IsBroken())
7055 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7059 uint32 attacktype
= Player::GetAttackBySlot(i
);
7060 if(attacktype
< MAX_ATTACK
)
7061 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7063 _ApplyItemBonuses(proto
,i
, true);
7065 if( i
== EQUIPMENT_SLOT_RANGED
)
7066 _ApplyAmmoBonuses();
7070 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7074 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7078 // item set bonuses not dependent from item broken state
7080 AddItemsSetItem(this,m_items
[i
]);
7082 if(m_items
[i
]->IsBroken())
7085 ApplyItemEquipSpell(m_items
[i
],true);
7086 ApplyEnchantment(m_items
[i
], true);
7090 sLog
.outDebug("_ApplyAllItemMods complete.");
7093 void Player::_ApplyAmmoBonuses()
7096 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7100 float currentAmmoDPS
;
7102 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7103 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7104 currentAmmoDPS
= 0.0f
;
7106 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7108 if(currentAmmoDPS
== GetAmmoDPS())
7111 m_ammoDPS
= currentAmmoDPS
;
7113 if(CanModifyStats())
7114 UpdateDamagePhysical(RANGED_ATTACK
);
7117 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7122 // check ranged weapon
7123 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7124 if(!weapon
|| weapon
->IsBroken() )
7127 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7128 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7131 // check ammo ws. weapon compatibility
7132 switch(weapon_proto
->SubClass
)
7134 case ITEM_SUBCLASS_WEAPON_BOW
:
7135 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7136 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7139 case ITEM_SUBCLASS_WEAPON_GUN
:
7140 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7150 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7151 Called by remove insignia spell effect */
7152 void Player::RemovedInsignia(Player
* looterPlr
)
7154 if (!GetBattleGroundId())
7157 // If not released spirit, do it !
7158 if(m_deathTimer
> 0)
7165 Corpse
*corpse
= GetCorpse();
7169 // We have to convert player corpse to bones, not to be able to resurrect there
7170 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7171 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7175 // Now we must make bones lootable, and send player loot
7176 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7178 // We store the level of our player in the gold field
7179 // We retrieve this information at Player::SendLoot()
7180 bones
->loot
.gold
= getLevel();
7181 bones
->lootRecipient
= looterPlr
;
7182 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7191 void Player::SendLootRelease( uint64 guid
)
7193 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7194 data
<< uint64(guid
) << uint8(1);
7195 SendDirectMessage( &data
);
7198 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7201 PermissionTypes permission
= ALL_PERMISSION
;
7203 sLog
.outDebug("Player::SendLoot");
7204 if (IS_GAMEOBJECT_GUID(guid
))
7206 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7208 ObjectAccessor::GetGameObject(*this, guid
);
7210 // not check distance for GO in case owned GO (fishing bobber case, for example)
7211 // And permit out of range GO with no owner in case fishing hole
7212 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7214 SendLootRelease(guid
);
7220 if(go
->getLootState() == GO_READY
)
7222 uint32 lootid
= go
->GetLootId();
7226 sLog
.outDebug(" if(lootid)");
7228 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7231 if(loot_type
== LOOT_FISHING
)
7232 go
->getFishLoot(loot
);
7234 go
->SetLootState(GO_ACTIVATED
);
7237 else if (IS_ITEM_GUID(guid
))
7239 Item
*item
= GetItemByGuid( guid
);
7243 SendLootRelease(guid
);
7247 if(loot_type
== LOOT_DISENCHANTING
)
7251 if(!item
->m_lootGenerated
)
7253 item
->m_lootGenerated
= true;
7255 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7258 else if(loot_type
== LOOT_PROSPECTING
)
7262 if(!item
->m_lootGenerated
)
7264 item
->m_lootGenerated
= true;
7266 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7269 else if(loot_type
== LOOT_MILLING
)
7273 if(!item
->m_lootGenerated
)
7275 item
->m_lootGenerated
= true;
7277 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this);
7284 if(!item
->m_lootGenerated
)
7286 item
->m_lootGenerated
= true;
7288 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7290 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7294 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7296 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7298 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7300 SendLootRelease(guid
);
7304 loot
= &bones
->loot
;
7306 if (!bones
->lootForBody
)
7308 bones
->lootForBody
= true;
7309 uint32 pLevel
= bones
->loot
.gold
;
7310 bones
->loot
.clear();
7311 // It may need a better formula
7312 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7313 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7316 if (bones
->lootRecipient
!= this)
7317 permission
= NONE_PERMISSION
;
7321 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7323 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7324 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7326 SendLootRelease(guid
);
7330 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7332 SendLootRelease(guid
);
7336 loot
= &creature
->loot
;
7338 if(loot_type
== LOOT_PICKPOCKETING
)
7340 if ( !creature
->lootForPickPocketed
)
7342 creature
->lootForPickPocketed
= true;
7345 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7346 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7348 // Generate extra money for pick pocket loot
7349 const uint32 a
= urand(0, creature
->getLevel()/2);
7350 const uint32 b
= urand(0, getLevel()/2);
7351 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7356 // the player whose group may loot the corpse
7357 Player
*recipient
= creature
->GetLootRecipient();
7360 creature
->SetLootRecipient(this);
7364 if (creature
->lootForPickPocketed
)
7366 creature
->lootForPickPocketed
= false;
7370 if(!creature
->lootForBody
)
7372 creature
->lootForBody
= true;
7375 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7376 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7378 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7380 if(Group
* group
= recipient
->GetGroup())
7382 group
->UpdateLooterGuid(creature
,true);
7384 switch (group
->GetLootMethod())
7387 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7388 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7390 case NEED_BEFORE_GREED
:
7391 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7394 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7402 // possible only if creature->lootForBody && loot->empty() at spell cast check
7403 if (loot_type
== LOOT_SKINNING
)
7406 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7408 // set group rights only for loot_type != LOOT_SKINNING
7411 if(Group
* group
= GetGroup())
7413 if( group
== recipient
->GetGroup() )
7415 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7416 permission
= ALL_PERMISSION
;
7417 else if(group
->GetLooterGuid() == GetGUID())
7419 if(group
->GetLootMethod() == MASTER_LOOT
)
7420 permission
= MASTER_PERMISSION
;
7422 permission
= ALL_PERMISSION
;
7425 permission
= GROUP_PERMISSION
;
7428 permission
= NONE_PERMISSION
;
7430 else if(recipient
== this)
7431 permission
= ALL_PERMISSION
;
7433 permission
= NONE_PERMISSION
;
7440 QuestItemList
*q_list
= 0;
7441 if (permission
!= NONE_PERMISSION
)
7443 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7444 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7445 if (itr
== lootPlayerQuestItems
.end())
7446 q_list
= loot
->FillQuestLoot(this);
7448 q_list
= itr
->second
;
7451 QuestItemList
*ffa_list
= 0;
7452 if (permission
!= NONE_PERMISSION
)
7454 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7455 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7456 if (itr
== lootPlayerFFAItems
.end())
7457 ffa_list
= loot
->FillFFALoot(this);
7459 ffa_list
= itr
->second
;
7462 QuestItemList
*conditional_list
= 0;
7463 if (permission
!= NONE_PERMISSION
)
7465 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7466 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7467 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7468 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7470 conditional_list
= itr
->second
;
7473 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7474 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7475 loot_type
= LOOT_SKINNING
;
7477 if(loot_type
== LOOT_FISHINGHOLE
)
7478 loot_type
= LOOT_FISHING
;
7480 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7482 data
<< uint64(guid
);
7483 data
<< uint8(loot_type
);
7484 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7486 SendDirectMessage(&data
);
7488 // add 'this' player as one of the players that are looting 'loot'
7489 if (permission
!= NONE_PERMISSION
)
7490 loot
->AddLooter(GetGUID());
7492 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7493 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7496 void Player::SendNotifyLootMoneyRemoved()
7498 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7499 GetSession()->SendPacket( &data
);
7502 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7504 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7505 data
<< uint8(lootSlot
);
7506 GetSession()->SendPacket( &data
);
7509 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7511 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7514 GetSession()->SendPacket(&data
);
7517 void Player::SendInitWorldStates()
7519 // data depends on zoneid/mapid...
7520 BattleGround
* bg
= GetBattleGround();
7521 uint16 NumberOfFields
= 0;
7522 uint32 mapid
= GetMapId();
7523 uint32 zoneid
= GetZoneId();
7524 uint32 areaid
= GetAreaId();
7525 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7526 // may be exist better way to do this...
7549 NumberOfFields
= 81;
7552 NumberOfFields
= 14;
7556 NumberOfFields
= 38;
7559 NumberOfFields
= 22;
7562 NumberOfFields
= 36;
7565 NumberOfFields
= 35;
7576 NumberOfFields
= 10;
7580 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7581 data
<< uint32(mapid
); // mapid
7582 data
<< uint32(zoneid
); // zone id
7583 data
<< uint32(areaid
); // area id, new 2.1.0
7584 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7585 data
<< uint32(0x8d8) << uint32(0x0); // 1
7586 data
<< uint32(0x8d7) << uint32(0x0); // 2
7587 data
<< uint32(0x8d6) << uint32(0x0); // 3
7588 data
<< uint32(0x8d5) << uint32(0x0); // 4
7589 data
<< uint32(0x8d4) << uint32(0x0); // 5
7590 data
<< uint32(0x8d3) << uint32(0x0); // 6
7591 if(mapid
== 530) // Outland
7593 data
<< uint32(0x9bf) << uint32(0x0); // 7
7594 data
<< uint32(0x9bd) << uint32(0xF); // 8
7595 data
<< uint32(0x9bb) << uint32(0xF); // 9
7610 data
<< uint32(0x7ae) << uint32(0x1); // 7
7611 data
<< uint32(0x532) << uint32(0x1); // 8
7612 data
<< uint32(0x531) << uint32(0x0); // 9
7613 data
<< uint32(0x52e) << uint32(0x0); // 10
7614 data
<< uint32(0x571) << uint32(0x0); // 11
7615 data
<< uint32(0x570) << uint32(0x0); // 12
7616 data
<< uint32(0x567) << uint32(0x1); // 13
7617 data
<< uint32(0x566) << uint32(0x1); // 14
7618 data
<< uint32(0x550) << uint32(0x1); // 15
7619 data
<< uint32(0x544) << uint32(0x0); // 16
7620 data
<< uint32(0x536) << uint32(0x0); // 17
7621 data
<< uint32(0x535) << uint32(0x1); // 18
7622 data
<< uint32(0x518) << uint32(0x0); // 19
7623 data
<< uint32(0x517) << uint32(0x0); // 20
7624 data
<< uint32(0x574) << uint32(0x0); // 21
7625 data
<< uint32(0x573) << uint32(0x0); // 22
7626 data
<< uint32(0x572) << uint32(0x0); // 23
7627 data
<< uint32(0x56f) << uint32(0x0); // 24
7628 data
<< uint32(0x56e) << uint32(0x0); // 25
7629 data
<< uint32(0x56d) << uint32(0x0); // 26
7630 data
<< uint32(0x56c) << uint32(0x0); // 27
7631 data
<< uint32(0x56b) << uint32(0x0); // 28
7632 data
<< uint32(0x56a) << uint32(0x1); // 29
7633 data
<< uint32(0x569) << uint32(0x1); // 30
7634 data
<< uint32(0x568) << uint32(0x1); // 13
7635 data
<< uint32(0x565) << uint32(0x0); // 32
7636 data
<< uint32(0x564) << uint32(0x0); // 33
7637 data
<< uint32(0x563) << uint32(0x0); // 34
7638 data
<< uint32(0x562) << uint32(0x0); // 35
7639 data
<< uint32(0x561) << uint32(0x0); // 36
7640 data
<< uint32(0x560) << uint32(0x0); // 37
7641 data
<< uint32(0x55f) << uint32(0x0); // 38
7642 data
<< uint32(0x55e) << uint32(0x0); // 39
7643 data
<< uint32(0x55d) << uint32(0x0); // 40
7644 data
<< uint32(0x3c6) << uint32(0x4); // 41
7645 data
<< uint32(0x3c4) << uint32(0x6); // 42
7646 data
<< uint32(0x3c2) << uint32(0x4); // 43
7647 data
<< uint32(0x516) << uint32(0x1); // 44
7648 data
<< uint32(0x515) << uint32(0x0); // 45
7649 data
<< uint32(0x3b6) << uint32(0x6); // 46
7650 data
<< uint32(0x55c) << uint32(0x0); // 47
7651 data
<< uint32(0x55b) << uint32(0x0); // 48
7652 data
<< uint32(0x55a) << uint32(0x0); // 49
7653 data
<< uint32(0x559) << uint32(0x0); // 50
7654 data
<< uint32(0x558) << uint32(0x0); // 51
7655 data
<< uint32(0x557) << uint32(0x0); // 52
7656 data
<< uint32(0x556) << uint32(0x0); // 53
7657 data
<< uint32(0x555) << uint32(0x0); // 54
7658 data
<< uint32(0x554) << uint32(0x1); // 55
7659 data
<< uint32(0x553) << uint32(0x1); // 56
7660 data
<< uint32(0x552) << uint32(0x1); // 57
7661 data
<< uint32(0x551) << uint32(0x1); // 58
7662 data
<< uint32(0x54f) << uint32(0x0); // 59
7663 data
<< uint32(0x54e) << uint32(0x0); // 60
7664 data
<< uint32(0x54d) << uint32(0x1); // 61
7665 data
<< uint32(0x54c) << uint32(0x0); // 62
7666 data
<< uint32(0x54b) << uint32(0x0); // 63
7667 data
<< uint32(0x545) << uint32(0x0); // 64
7668 data
<< uint32(0x543) << uint32(0x1); // 65
7669 data
<< uint32(0x542) << uint32(0x0); // 66
7670 data
<< uint32(0x540) << uint32(0x0); // 67
7671 data
<< uint32(0x53f) << uint32(0x0); // 68
7672 data
<< uint32(0x53e) << uint32(0x0); // 69
7673 data
<< uint32(0x53d) << uint32(0x0); // 70
7674 data
<< uint32(0x53c) << uint32(0x0); // 71
7675 data
<< uint32(0x53b) << uint32(0x0); // 72
7676 data
<< uint32(0x53a) << uint32(0x1); // 73
7677 data
<< uint32(0x539) << uint32(0x0); // 74
7678 data
<< uint32(0x538) << uint32(0x0); // 75
7679 data
<< uint32(0x537) << uint32(0x0); // 76
7680 data
<< uint32(0x534) << uint32(0x0); // 77
7681 data
<< uint32(0x533) << uint32(0x0); // 78
7682 data
<< uint32(0x530) << uint32(0x0); // 79
7683 data
<< uint32(0x52f) << uint32(0x0); // 80
7684 data
<< uint32(0x52d) << uint32(0x1); // 81
7687 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7688 bg
->FillInitialWorldStates(data
);
7691 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7692 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7693 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7694 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7695 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7696 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7697 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7698 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7702 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7703 bg
->FillInitialWorldStates(data
);
7706 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7707 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7708 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7709 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7710 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7711 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7712 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7713 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7714 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7715 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7716 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7717 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7718 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7719 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7720 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7721 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7722 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7723 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7724 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7725 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7726 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7727 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7728 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7729 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7730 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7731 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7732 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7733 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7734 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7735 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7736 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7737 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7741 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7742 bg
->FillInitialWorldStates(data
);
7745 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7746 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7747 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7748 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7749 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7750 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7751 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7752 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7753 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7754 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7755 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7756 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7757 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7758 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7759 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7760 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7761 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7762 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7763 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7764 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7765 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7766 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7767 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7768 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7769 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7770 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7771 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7772 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7773 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7774 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7775 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7776 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7777 // and some more ... unknown
7780 case 3483: // Hellfire Peninsula
7781 data
<< uint32(0x9ba) << uint32(0x1); // 10
7782 data
<< uint32(0x9b9) << uint32(0x1); // 11
7783 data
<< uint32(0x9b5) << uint32(0x0); // 12
7784 data
<< uint32(0x9b4) << uint32(0x1); // 13
7785 data
<< uint32(0x9b3) << uint32(0x0); // 14
7786 data
<< uint32(0x9b2) << uint32(0x0); // 15
7787 data
<< uint32(0x9b1) << uint32(0x1); // 16
7788 data
<< uint32(0x9b0) << uint32(0x0); // 17
7789 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7790 data
<< uint32(0x9ac) << uint32(0x0); // 19
7791 data
<< uint32(0x9a8) << uint32(0x0); // 20
7792 data
<< uint32(0x9a7) << uint32(0x0); // 21
7793 data
<< uint32(0x9a6) << uint32(0x1); // 22
7795 case 3519: // Terokkar Forest
7796 data
<< uint32(0xa41) << uint32(0x0); // 10
7797 data
<< uint32(0xa40) << uint32(0x14); // 11
7798 data
<< uint32(0xa3f) << uint32(0x0); // 12
7799 data
<< uint32(0xa3e) << uint32(0x0); // 13
7800 data
<< uint32(0xa3d) << uint32(0x5); // 14
7801 data
<< uint32(0xa3c) << uint32(0x0); // 15
7802 data
<< uint32(0xa87) << uint32(0x0); // 16
7803 data
<< uint32(0xa86) << uint32(0x0); // 17
7804 data
<< uint32(0xa85) << uint32(0x0); // 18
7805 data
<< uint32(0xa84) << uint32(0x0); // 19
7806 data
<< uint32(0xa83) << uint32(0x0); // 20
7807 data
<< uint32(0xa82) << uint32(0x0); // 21
7808 data
<< uint32(0xa81) << uint32(0x0); // 22
7809 data
<< uint32(0xa80) << uint32(0x0); // 23
7810 data
<< uint32(0xa7e) << uint32(0x0); // 24
7811 data
<< uint32(0xa7d) << uint32(0x0); // 25
7812 data
<< uint32(0xa7c) << uint32(0x0); // 26
7813 data
<< uint32(0xa7b) << uint32(0x0); // 27
7814 data
<< uint32(0xa7a) << uint32(0x0); // 28
7815 data
<< uint32(0xa79) << uint32(0x0); // 29
7816 data
<< uint32(0x9d0) << uint32(0x5); // 30
7817 data
<< uint32(0x9ce) << uint32(0x0); // 31
7818 data
<< uint32(0x9cd) << uint32(0x0); // 32
7819 data
<< uint32(0x9cc) << uint32(0x0); // 33
7820 data
<< uint32(0xa88) << uint32(0x0); // 34
7821 data
<< uint32(0xad0) << uint32(0x0); // 35
7822 data
<< uint32(0xacf) << uint32(0x1); // 36
7824 case 3521: // Zangarmarsh
7825 data
<< uint32(0x9e1) << uint32(0x0); // 10
7826 data
<< uint32(0x9e0) << uint32(0x0); // 11
7827 data
<< uint32(0x9df) << uint32(0x0); // 12
7828 data
<< uint32(0xa5d) << uint32(0x1); // 13
7829 data
<< uint32(0xa5c) << uint32(0x0); // 14
7830 data
<< uint32(0xa5b) << uint32(0x1); // 15
7831 data
<< uint32(0xa5a) << uint32(0x0); // 16
7832 data
<< uint32(0xa59) << uint32(0x1); // 17
7833 data
<< uint32(0xa58) << uint32(0x0); // 18
7834 data
<< uint32(0xa57) << uint32(0x0); // 19
7835 data
<< uint32(0xa56) << uint32(0x0); // 20
7836 data
<< uint32(0xa55) << uint32(0x1); // 21
7837 data
<< uint32(0xa54) << uint32(0x0); // 22
7838 data
<< uint32(0x9e7) << uint32(0x0); // 23
7839 data
<< uint32(0x9e6) << uint32(0x0); // 24
7840 data
<< uint32(0x9e5) << uint32(0x0); // 25
7841 data
<< uint32(0xa00) << uint32(0x0); // 26
7842 data
<< uint32(0x9ff) << uint32(0x1); // 27
7843 data
<< uint32(0x9fe) << uint32(0x0); // 28
7844 data
<< uint32(0x9fd) << uint32(0x0); // 29
7845 data
<< uint32(0x9fc) << uint32(0x1); // 30
7846 data
<< uint32(0x9fb) << uint32(0x0); // 31
7847 data
<< uint32(0xa62) << uint32(0x0); // 32
7848 data
<< uint32(0xa61) << uint32(0x1); // 33
7849 data
<< uint32(0xa60) << uint32(0x1); // 34
7850 data
<< uint32(0xa5f) << uint32(0x0); // 35
7852 case 3698: // Nagrand Arena
7853 data
<< uint32(0xa0f) << uint32(0x0); // 7
7854 data
<< uint32(0xa10) << uint32(0x0); // 8
7855 data
<< uint32(0xa11) << uint32(0x0); // 9
7857 case 3702: // Blade's Edge Arena
7858 data
<< uint32(0x9f0) << uint32(0x0); // 7
7859 data
<< uint32(0x9f1) << uint32(0x0); // 8
7860 data
<< uint32(0x9f3) << uint32(0x0); // 9
7862 case 3968: // Ruins of Lordaeron
7863 data
<< uint32(0xbb8) << uint32(0x0); // 7
7864 data
<< uint32(0xbb9) << uint32(0x0); // 8
7865 data
<< uint32(0xbba) << uint32(0x0); // 9
7867 case 3703: // Shattrath City
7870 data
<< uint32(0x914) << uint32(0x0); // 7
7871 data
<< uint32(0x913) << uint32(0x0); // 8
7872 data
<< uint32(0x912) << uint32(0x0); // 9
7873 data
<< uint32(0x915) << uint32(0x0); // 10
7876 GetSession()->SendPacket(&data
);
7879 uint32
Player::GetXPRestBonus(uint32 xp
)
7881 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7883 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7886 SetRestBonus( GetRestBonus() - rested_bonus
);
7888 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7889 return rested_bonus
;
7892 void Player::SetBindPoint(uint64 guid
)
7894 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7895 data
<< uint64(guid
);
7896 GetSession()->SendPacket( &data
);
7899 void Player::SendTalentWipeConfirm(uint64 guid
)
7901 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7902 data
<< uint64(guid
);
7903 data
<< uint32(resetTalentsCost());
7904 GetSession()->SendPacket( &data
);
7907 void Player::SendPetSkillWipeConfirm()
7909 Pet
* pet
= GetPet();
7912 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7913 data
<< pet
->GetGUID();
7914 data
<< uint32(pet
->resetTalentsCost());
7915 GetSession()->SendPacket( &data
);
7918 /*********************************************************/
7919 /*** STORAGE SYSTEM ***/
7920 /*********************************************************/
7922 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7927 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7929 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7933 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7934 else if(charges
<= 1)
7936 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7937 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7942 void Player::SetSheath( uint32 sheathed
)
7946 case SHEATH_STATE_UNARMED
: // no prepared weapon
7947 SetVirtualItemSlot(0,NULL
);
7948 SetVirtualItemSlot(1,NULL
);
7949 SetVirtualItemSlot(2,NULL
);
7951 case SHEATH_STATE_MELEE
: // prepared melee weapon
7953 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7954 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7955 SetVirtualItemSlot(2,NULL
);
7957 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7958 SetVirtualItemSlot(0,NULL
);
7959 SetVirtualItemSlot(1,NULL
);
7960 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7963 SetVirtualItemSlot(0,NULL
);
7964 SetVirtualItemSlot(1,NULL
);
7965 SetVirtualItemSlot(2,NULL
);
7968 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7971 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7973 uint8 pClass
= getClass();
7976 slots
[0] = NULL_SLOT
;
7977 slots
[1] = NULL_SLOT
;
7978 slots
[2] = NULL_SLOT
;
7979 slots
[3] = NULL_SLOT
;
7980 switch( proto
->InventoryType
)
7983 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7986 slots
[0] = EQUIPMENT_SLOT_NECK
;
7988 case INVTYPE_SHOULDERS
:
7989 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7992 slots
[0] = EQUIPMENT_SLOT_BODY
;
7995 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7998 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8001 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8004 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8007 slots
[0] = EQUIPMENT_SLOT_FEET
;
8009 case INVTYPE_WRISTS
:
8010 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8013 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8015 case INVTYPE_FINGER
:
8016 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8017 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8019 case INVTYPE_TRINKET
:
8020 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8021 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8024 slots
[0] = EQUIPMENT_SLOT_BACK
;
8026 case INVTYPE_WEAPON
:
8028 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8030 // suggest offhand slot only if know dual wielding
8031 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8033 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8035 case INVTYPE_SHIELD
:
8036 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8038 case INVTYPE_RANGED
:
8039 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8041 case INVTYPE_2HWEAPON
:
8042 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8044 case INVTYPE_TABARD
:
8045 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8047 case INVTYPE_WEAPONMAINHAND
:
8048 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8050 case INVTYPE_WEAPONOFFHAND
:
8051 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8053 case INVTYPE_HOLDABLE
:
8054 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8056 case INVTYPE_THROWN
:
8057 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8059 case INVTYPE_RANGEDRIGHT
:
8060 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8063 slots
[0] = INVENTORY_SLOT_BAG_1
;
8064 slots
[1] = INVENTORY_SLOT_BAG_2
;
8065 slots
[2] = INVENTORY_SLOT_BAG_3
;
8066 slots
[3] = INVENTORY_SLOT_BAG_4
;
8070 switch(proto
->SubClass
)
8072 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8073 if (pClass
== CLASS_PALADIN
)
8074 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8076 case ITEM_SUBCLASS_ARMOR_IDOL
:
8077 if (pClass
== CLASS_DRUID
)
8078 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8080 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8081 if (pClass
== CLASS_SHAMAN
)
8082 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8084 case ITEM_SUBCLASS_ARMOR_MISC
:
8085 if (pClass
== CLASS_WARLOCK
)
8086 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8088 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8089 if (pClass
== CLASS_DEATH_KNIGHT
)
8090 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8099 if( slot
!= NULL_SLOT
)
8101 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8103 for (int i
= 0; i
< 4; i
++)
8105 if ( slots
[i
] == slot
)
8112 // search free slot at first
8113 for (int i
= 0; i
< 4; i
++)
8115 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8117 // in case 2hand equipped weapon offhand slot empty but not free
8118 if(slots
[i
]==EQUIPMENT_SLOT_OFFHAND
)
8120 Item
* mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
8121 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
8129 // if not found free and can swap return first appropriate from used
8130 for (int i
= 0; i
< 4; i
++)
8132 if ( slots
[i
] != NULL_SLOT
&& swap
)
8141 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8144 uint32 tempcount
= 0;
8146 uint8 res
= EQUIP_ERR_OK
;
8148 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8150 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8151 if( pItem
&& pItem
->GetEntry() == item
)
8153 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8154 if(ires
==EQUIP_ERR_OK
)
8156 tempcount
+= pItem
->GetCount();
8157 if( tempcount
>= count
)
8158 return EQUIP_ERR_OK
;
8164 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8166 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8167 if( pItem
&& pItem
->GetEntry() == item
)
8169 tempcount
+= pItem
->GetCount();
8170 if( tempcount
>= count
)
8171 return EQUIP_ERR_OK
;
8174 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8176 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8177 if( pItem
&& pItem
->GetEntry() == item
)
8179 tempcount
+= pItem
->GetCount();
8180 if( tempcount
>= count
)
8181 return EQUIP_ERR_OK
;
8185 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8187 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8190 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8192 pItem
= GetItemByPos( i
, j
);
8193 if( pItem
&& pItem
->GetEntry() == item
)
8195 tempcount
+= pItem
->GetCount();
8196 if( tempcount
>= count
)
8197 return EQUIP_ERR_OK
;
8203 // not found req. item count and have unequippable items
8207 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8210 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8212 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8213 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8214 count
+= pItem
->GetCount();
8216 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8218 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8219 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8220 count
+= pItem
->GetCount();
8222 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8224 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8226 count
+= pBag
->GetItemCount(item
,skipItem
);
8229 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8231 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8233 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8234 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8235 count
+= pItem
->GetGemCountWithID(item
);
8241 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8243 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8244 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8245 count
+= pItem
->GetCount();
8247 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8249 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8251 count
+= pBag
->GetItemCount(item
,skipItem
);
8254 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8256 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8258 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8259 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8260 count
+= pItem
->GetGemCountWithID(item
);
8268 Item
* Player::GetItemByGuid( uint64 guid
) const
8270 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8272 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8273 if( pItem
&& pItem
->GetGUID() == guid
)
8276 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8278 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8279 if( pItem
&& pItem
->GetGUID() == guid
)
8283 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8285 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8288 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8290 Item
* pItem
= pBag
->GetItemByPos( j
);
8291 if( pItem
&& pItem
->GetGUID() == guid
)
8296 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8298 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8301 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8303 Item
* pItem
= pBag
->GetItemByPos( j
);
8304 if( pItem
&& pItem
->GetGUID() == guid
)
8313 Item
* Player::GetItemByPos( uint16 pos
) const
8315 uint8 bag
= pos
>> 8;
8316 uint8 slot
= pos
& 255;
8317 return GetItemByPos( bag
, slot
);
8320 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8322 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8323 return m_items
[slot
];
8324 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8325 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8327 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8329 return pBag
->GetItemByPos(slot
);
8334 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8339 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8340 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8341 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8342 default: return NULL
;
8345 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8346 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8352 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8358 Item
* Player::GetShield(bool useable
) const
8360 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8361 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8367 if( item
->IsBroken())
8373 uint32
Player::GetAttackBySlot( uint8 slot
)
8377 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8378 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8379 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8380 default: return MAX_ATTACK
;
8384 bool Player::HasBankBagSlot( uint8 slot
) const
8386 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8387 if( slot
< maxslot
)
8392 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8394 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8396 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8398 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8400 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8405 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8407 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8409 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8414 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8416 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8418 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8420 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8425 bool Player::IsBagPos( uint16 pos
)
8427 uint8 bag
= pos
>> 8;
8428 uint8 slot
= pos
& 255;
8429 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8431 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8436 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8442 if (bag
== INVENTORY_SLOT_BAG_0
)
8444 // any post selected
8445 if (slot
== NULL_SLOT
)
8449 if (slot
< EQUIPMENT_SLOT_END
)
8453 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8457 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8461 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8465 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8469 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8475 // bag content slots
8476 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8478 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8482 // any post selected
8483 if (slot
== NULL_SLOT
)
8486 return slot
< pBag
->GetBagSize();
8489 // bank bag content slots
8490 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8492 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8496 // any post selected
8497 if (slot
== NULL_SLOT
)
8500 return slot
< pBag
->GetBagSize();
8508 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8510 uint32 tempcount
= 0;
8511 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8513 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8514 if( pItem
&& pItem
->GetEntry() == item
)
8516 tempcount
+= pItem
->GetCount();
8517 if( tempcount
>= count
)
8521 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8523 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8524 if( pItem
&& pItem
->GetEntry() == item
)
8526 tempcount
+= pItem
->GetCount();
8527 if( tempcount
>= count
)
8531 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8533 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8535 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8537 Item
* pItem
= GetItemByPos( i
, j
);
8538 if( pItem
&& pItem
->GetEntry() == item
)
8540 tempcount
+= pItem
->GetCount();
8541 if( tempcount
>= count
)
8550 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8552 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8553 if( pItem
&& pItem
->GetEntry() == item
)
8555 tempcount
+= pItem
->GetCount();
8556 if( tempcount
>= count
)
8560 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8562 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8564 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8566 Item
* pItem
= GetItemByPos( i
, j
);
8567 if( pItem
&& pItem
->GetEntry() == item
)
8569 tempcount
+= pItem
->GetCount();
8570 if( tempcount
>= count
)
8581 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8584 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8586 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8587 if( pItem
&& pItem
->GetEntry() == item
)
8591 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8592 if (pProto
&& pProto
->GemProperties
)
8594 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8596 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8597 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8599 if (pItem
->GetGemCountWithID(item
) > 0 )
8608 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8610 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8614 *no_space_count
= count
;
8615 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8619 if(pProto
->MaxCount
== 0)
8620 return EQUIP_ERR_OK
;
8622 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8624 if( curcount
+ count
> pProto
->MaxCount
)
8627 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8628 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8631 return EQUIP_ERR_OK
;
8634 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8637 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8639 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8640 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8643 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8645 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8646 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8649 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8651 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8653 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8655 pItem
= GetItemByPos( i
, j
);
8656 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8664 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8666 Item
* pItem2
= GetItemByPos( bag
, slot
);
8668 // ignore move item (this slot will be empty at move)
8669 if(pItem2
==pSrcItem
)
8674 // empty specific slot - check item fit to slot
8675 if( !pItem2
|| swap
)
8677 if( bag
== INVENTORY_SLOT_BAG_0
)
8680 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8681 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8684 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
))
8685 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8687 // currencytoken case
8688 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8689 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8692 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
))
8693 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8696 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8697 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8701 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8703 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8705 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8707 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8709 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8710 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8713 // non empty stack with space
8714 need_space
= pProto
->Stackable
;
8716 // non empty slot, check item type
8720 if(pItem2
->GetEntry() != pProto
->ItemId
)
8721 return EQUIP_ERR_ITEM_CANT_STACK
;
8724 if(pItem2
->GetCount() >= pProto
->Stackable
)
8725 return EQUIP_ERR_ITEM_CANT_STACK
;
8727 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8730 if(need_space
> count
)
8733 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8734 if(!newPosition
.isContainedIn(dest
))
8736 dest
.push_back(newPosition
);
8737 count
-= need_space
;
8739 return EQUIP_ERR_OK
;
8742 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
8744 // skip specific bag already processed in first called _CanStoreItem_InBag
8746 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8748 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8750 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8752 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8754 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8756 // specialized bag mode or non-specilized
8757 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8758 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8760 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8761 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8763 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8765 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8769 Item
* pItem2
= GetItemByPos( bag
, j
);
8771 // ignore move item (this slot will be empty at move)
8772 if(pItem2
==pSrcItem
)
8775 // if merge skip empty, if !merge skip non-empty
8776 if((pItem2
!=NULL
)!=merge
)
8781 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8783 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8784 if(need_space
> count
)
8787 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8788 if(!newPosition
.isContainedIn(dest
))
8790 dest
.push_back(newPosition
);
8791 count
-= need_space
;
8794 return EQUIP_ERR_OK
;
8800 uint32 need_space
= pProto
->Stackable
;
8801 if(need_space
> count
)
8804 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8805 if(!newPosition
.isContainedIn(dest
))
8807 dest
.push_back(newPosition
);
8808 count
-= need_space
;
8811 return EQUIP_ERR_OK
;
8815 return EQUIP_ERR_OK
;
8818 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
8820 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8822 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8823 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8826 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8828 // ignore move item (this slot will be empty at move)
8829 if(pItem2
==pSrcItem
)
8832 // if merge skip empty, if !merge skip non-empty
8833 if((pItem2
!=NULL
)!=merge
)
8838 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8840 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8841 if(need_space
> count
)
8843 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8844 if(!newPosition
.isContainedIn(dest
))
8846 dest
.push_back(newPosition
);
8847 count
-= need_space
;
8850 return EQUIP_ERR_OK
;
8856 uint32 need_space
= pProto
->Stackable
;
8857 if(need_space
> count
)
8860 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8861 if(!newPosition
.isContainedIn(dest
))
8863 dest
.push_back(newPosition
);
8864 count
-= need_space
;
8867 return EQUIP_ERR_OK
;
8871 return EQUIP_ERR_OK
;
8874 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8876 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8878 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8882 *no_space_count
= count
;
8883 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8886 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8889 *no_space_count
= count
;
8890 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8893 // check count of items (skip for auto move for same player from bank)
8894 uint32 no_similar_count
= 0; // can't store this amount similar items
8895 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8896 if(res
!=EQUIP_ERR_OK
)
8898 if(count
==no_similar_count
)
8901 *no_space_count
= no_similar_count
;
8904 count
-= no_similar_count
;
8908 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8910 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8911 if(res
!=EQUIP_ERR_OK
)
8914 *no_space_count
= count
+ no_similar_count
;
8920 if(no_similar_count
==0)
8921 return EQUIP_ERR_OK
;
8924 *no_space_count
= count
+ no_similar_count
;
8925 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8929 // not specific slot or have space for partly store only in specific slot
8932 if( bag
!= NULL_BAG
)
8934 // search stack in bag for merge to
8935 if( pProto
->Stackable
> 1 )
8937 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8939 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8940 if(res
!=EQUIP_ERR_OK
)
8943 *no_space_count
= count
+ no_similar_count
;
8949 if(no_similar_count
==0)
8950 return EQUIP_ERR_OK
;
8953 *no_space_count
= count
+ no_similar_count
;
8954 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8957 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8958 if(res
!=EQUIP_ERR_OK
)
8961 *no_space_count
= count
+ no_similar_count
;
8967 if(no_similar_count
==0)
8968 return EQUIP_ERR_OK
;
8971 *no_space_count
= count
+ no_similar_count
;
8972 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8975 else // equipped bag
8977 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8978 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8979 if(res
!=EQUIP_ERR_OK
)
8980 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8982 if(res
!=EQUIP_ERR_OK
)
8985 *no_space_count
= count
+ no_similar_count
;
8991 if(no_similar_count
==0)
8992 return EQUIP_ERR_OK
;
8995 *no_space_count
= count
+ no_similar_count
;
8996 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9001 // search free slot in bag for place to
9002 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9004 // search free slot - keyring case
9005 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9007 uint32 keyringSize
= GetMaxKeyringSize();
9008 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9009 if(res
!=EQUIP_ERR_OK
)
9012 *no_space_count
= count
+ no_similar_count
;
9018 if(no_similar_count
==0)
9019 return EQUIP_ERR_OK
;
9022 *no_space_count
= count
+ no_similar_count
;
9023 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9026 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
9028 res
= _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START
,VANITYPET_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9029 if(res
!=EQUIP_ERR_OK
)
9032 *no_space_count
= count
+ no_similar_count
;
9038 if(no_similar_count
==0)
9039 return EQUIP_ERR_OK
;
9042 *no_space_count
= count
+ no_similar_count
;
9043 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9046 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9048 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9049 if(res
!=EQUIP_ERR_OK
)
9052 *no_space_count
= count
+ no_similar_count
;
9058 if(no_similar_count
==0)
9059 return EQUIP_ERR_OK
;
9062 *no_space_count
= count
+ no_similar_count
;
9063 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9066 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
9068 res
= _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9069 if(res
!=EQUIP_ERR_OK
)
9072 *no_space_count
= count
+ no_similar_count
;
9078 if(no_similar_count
==0)
9079 return EQUIP_ERR_OK
;
9082 *no_space_count
= count
+ no_similar_count
;
9083 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9087 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9088 if(res
!=EQUIP_ERR_OK
)
9091 *no_space_count
= count
+ no_similar_count
;
9097 if(no_similar_count
==0)
9098 return EQUIP_ERR_OK
;
9101 *no_space_count
= count
+ no_similar_count
;
9102 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9105 else // equipped bag
9107 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9108 if(res
!=EQUIP_ERR_OK
)
9109 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9111 if(res
!=EQUIP_ERR_OK
)
9114 *no_space_count
= count
+ no_similar_count
;
9120 if(no_similar_count
==0)
9121 return EQUIP_ERR_OK
;
9124 *no_space_count
= count
+ no_similar_count
;
9125 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9130 // not specific bag or have space for partly store only in specific bag
9132 // search stack for merge to
9133 if( pProto
->Stackable
> 1 )
9135 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9136 if(res
!=EQUIP_ERR_OK
)
9139 *no_space_count
= count
+ no_similar_count
;
9145 if(no_similar_count
==0)
9146 return EQUIP_ERR_OK
;
9149 *no_space_count
= count
+ no_similar_count
;
9150 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9153 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9154 if(res
!=EQUIP_ERR_OK
)
9157 *no_space_count
= count
+ no_similar_count
;
9163 if(no_similar_count
==0)
9164 return EQUIP_ERR_OK
;
9167 *no_space_count
= count
+ no_similar_count
;
9168 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9171 if( pProto
->BagFamily
)
9173 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9175 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9176 if(res
!=EQUIP_ERR_OK
)
9181 if(no_similar_count
==0)
9182 return EQUIP_ERR_OK
;
9185 *no_space_count
= count
+ no_similar_count
;
9186 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9191 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9193 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9194 if(res
!=EQUIP_ERR_OK
)
9199 if(no_similar_count
==0)
9200 return EQUIP_ERR_OK
;
9203 *no_space_count
= count
+ no_similar_count
;
9204 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9209 // search free slot - special bag case
9210 if( pProto
->BagFamily
)
9212 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9214 uint32 keyringSize
= GetMaxKeyringSize();
9215 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9216 if(res
!=EQUIP_ERR_OK
)
9219 *no_space_count
= count
+ no_similar_count
;
9225 if(no_similar_count
==0)
9226 return EQUIP_ERR_OK
;
9229 *no_space_count
= count
+ no_similar_count
;
9230 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9233 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
9235 res
= _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START
,VANITYPET_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9236 if(res
!=EQUIP_ERR_OK
)
9239 *no_space_count
= count
+ no_similar_count
;
9245 if(no_similar_count
==0)
9246 return EQUIP_ERR_OK
;
9249 *no_space_count
= count
+ no_similar_count
;
9250 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9253 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9255 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9256 if(res
!=EQUIP_ERR_OK
)
9259 *no_space_count
= count
+ no_similar_count
;
9265 if(no_similar_count
==0)
9266 return EQUIP_ERR_OK
;
9269 *no_space_count
= count
+ no_similar_count
;
9270 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9273 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
9275 res
= _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9276 if(res
!=EQUIP_ERR_OK
)
9279 *no_space_count
= count
+ no_similar_count
;
9285 if(no_similar_count
==0)
9286 return EQUIP_ERR_OK
;
9289 *no_space_count
= count
+ no_similar_count
;
9290 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9294 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9296 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9297 if(res
!=EQUIP_ERR_OK
)
9302 if(no_similar_count
==0)
9303 return EQUIP_ERR_OK
;
9306 *no_space_count
= count
+ no_similar_count
;
9307 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9313 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9314 if(res
!=EQUIP_ERR_OK
)
9317 *no_space_count
= count
+ no_similar_count
;
9323 if(no_similar_count
==0)
9324 return EQUIP_ERR_OK
;
9327 *no_space_count
= count
+ no_similar_count
;
9328 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9331 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9333 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9334 if(res
!=EQUIP_ERR_OK
)
9339 if(no_similar_count
==0)
9340 return EQUIP_ERR_OK
;
9343 *no_space_count
= count
+ no_similar_count
;
9344 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9349 *no_space_count
= count
+ no_similar_count
;
9351 return EQUIP_ERR_INVENTORY_FULL
;
9354 //////////////////////////////////////////////////////////////////////////
9355 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9360 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9361 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9362 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9363 int inv_pets
[VANITYPET_SLOT_END
-VANITYPET_SLOT_START
];
9364 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9365 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9367 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9368 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9369 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9370 memset(inv_pets
,0,sizeof(int)*(VANITYPET_SLOT_END
-VANITYPET_SLOT_START
));
9371 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9372 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9374 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9376 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9378 if (pItem2
&& !pItem2
->IsInTrade())
9380 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9384 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9386 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9388 if (pItem2
&& !pItem2
->IsInTrade())
9390 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9394 for(int i
= VANITYPET_SLOT_START
; i
< VANITYPET_SLOT_END
; i
++)
9396 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9398 if (pItem2
&& !pItem2
->IsInTrade())
9400 inv_pets
[i
-VANITYPET_SLOT_START
] = pItem2
->GetCount();
9404 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9406 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9408 if (pItem2
&& !pItem2
->IsInTrade())
9410 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9414 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9416 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9418 if (pItem2
&& !pItem2
->IsInTrade())
9420 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9424 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9426 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9428 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9430 pItem2
= GetItemByPos( i
, j
);
9431 if (pItem2
&& !pItem2
->IsInTrade())
9433 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9439 // check free space for all items
9440 for (int k
=0;k
<count
;k
++)
9442 Item
*pItem
= pItems
[k
];
9445 if (!pItem
) continue;
9447 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9448 ItemPrototype
const *pProto
= pItem
->GetProto();
9452 return EQUIP_ERR_ITEM_NOT_FOUND
;
9455 if(pItem
->IsBindedNotWith(GetGUID()))
9456 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9459 ItemPrototype
const *pBagProto
;
9461 // item is 'one item only'
9462 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9463 if(res
!= EQUIP_ERR_OK
)
9466 // search stack for merge to
9467 if( pProto
->Stackable
> 1 )
9469 bool b_found
= false;
9471 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9473 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9474 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9476 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9481 if (b_found
) continue;
9483 for(int t
= VANITYPET_SLOT_START
; t
< VANITYPET_SLOT_END
; t
++)
9485 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9486 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_pets
[t
-VANITYPET_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9488 inv_pets
[t
-VANITYPET_SLOT_START
] += pItem
->GetCount();
9493 if (b_found
) continue;
9495 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9497 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9498 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9500 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9505 if (b_found
) continue;
9507 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9509 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9510 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9512 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9517 if (b_found
) continue;
9519 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9521 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9522 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9524 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9529 if (b_found
) continue;
9531 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9533 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9536 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9538 pItem2
= GetItemByPos( t
, j
);
9539 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->Stackable
)
9541 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9548 if (b_found
) continue;
9552 if( pProto
->BagFamily
)
9554 bool b_found
= false;
9555 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9557 uint32 keyringSize
= GetMaxKeyringSize();
9558 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9560 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9562 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9569 if (b_found
) continue;
9571 if(pProto
->BagFamily
& BAG_FAMILY_MASK_VANITY_PETS
)
9573 for(uint32 t
= VANITYPET_SLOT_START
; t
< VANITYPET_SLOT_END
; ++t
)
9575 if( inv_pets
[t
-VANITYPET_SLOT_START
] == 0 )
9577 inv_pets
[t
-VANITYPET_SLOT_START
] = 1;
9584 if (b_found
) continue;
9586 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9588 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9590 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9592 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9599 if (b_found
) continue;
9601 if(pProto
->BagFamily
& BAG_FAMILY_MASK_QUEST_ITEMS
)
9603 for(uint32 t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; ++t
)
9605 if( inv_quests
[t
-QUESTBAG_SLOT_START
] == 0 )
9607 inv_quests
[t
-QUESTBAG_SLOT_START
] = 1;
9614 if (b_found
) continue;
9616 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9618 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9621 pBagProto
= pBag
->GetProto();
9623 // not plain container check
9624 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9625 ItemCanGoIntoBag(pProto
,pBagProto
) )
9627 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9629 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9631 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9639 if (b_found
) continue;
9643 bool b_found
= false;
9644 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9646 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9648 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9653 if (b_found
) continue;
9655 // search free slot in bags
9656 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9658 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9661 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9663 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9665 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9673 // no free slot found?
9675 return EQUIP_ERR_INVENTORY_FULL
;
9678 return EQUIP_ERR_OK
;
9681 //////////////////////////////////////////////////////////////////////////
9682 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, uint32 count
, bool swap
) const
9685 Item
*pItem
= Item::CreateItem( item
, count
, this );
9688 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9693 return EQUIP_ERR_ITEM_NOT_FOUND
;
9696 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9701 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9702 ItemPrototype
const *pProto
= pItem
->GetProto();
9705 // May be here should be more stronger checks; STUNNED checked
9706 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9707 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9708 return EQUIP_ERR_YOU_ARE_STUNNED
;
9710 if(pItem
->IsBindedNotWith(GetGUID()))
9711 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9713 // check count of items (skip for auto move for same player from bank)
9714 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9715 if(res
!= EQUIP_ERR_OK
)
9718 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9720 // - in-progress arenas
9721 if( !pProto
->CanChangeEquipStateInCombat() )
9724 return EQUIP_ERR_NOT_IN_COMBAT
;
9726 if(BattleGround
* bg
= GetBattleGround())
9727 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9728 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9731 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9732 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9734 if(IsNonMeleeSpellCasted(false))
9735 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9737 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9738 if( eslot
== NULL_SLOT
)
9739 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9741 uint8 msg
= CanUseItem( pItem
, not_loading
);
9742 if( msg
!= EQUIP_ERR_OK
)
9744 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9745 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9747 // check unique-equipped on item
9748 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9750 // there is an equip limit on this item
9751 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9752 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9753 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9756 // check unique-equipped on gems
9757 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9759 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9762 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9766 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9767 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9769 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9770 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9771 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9775 // check unique-equipped special item classes
9776 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9778 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9780 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9782 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9784 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9785 (!swap
|| pBag
->GetSlot() != eslot
) )
9787 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9788 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9790 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9797 uint32 type
= pProto
->InventoryType
;
9799 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9801 if( type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9804 return EQUIP_ERR_CANT_DUAL_WIELD
;
9807 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
9810 if(mainItem
->GetProto()->InventoryType
== INVTYPE_2HWEAPON
)
9811 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9815 // equip two-hand weapon case (with possible unequip 2 items)
9816 if( type
== INVTYPE_2HWEAPON
)
9818 if(eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9819 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9821 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9822 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9823 ItemPosCountVec off_dest
;
9824 if( offItem
&& (!not_loading
||
9825 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9826 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9827 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9829 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9830 return EQUIP_ERR_OK
;
9834 return EQUIP_ERR_ITEM_NOT_FOUND
;
9836 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9839 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9841 // Applied only to equipped items and bank bags
9842 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9843 return EQUIP_ERR_OK
;
9845 Item
* pItem
= GetItemByPos(pos
);
9847 // Applied only to existed equipped item
9849 return EQUIP_ERR_OK
;
9851 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9853 ItemPrototype
const *pProto
= pItem
->GetProto();
9855 return EQUIP_ERR_ITEM_NOT_FOUND
;
9857 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9859 // - in-progress arenas
9860 if( !pProto
->CanChangeEquipStateInCombat() )
9863 return EQUIP_ERR_NOT_IN_COMBAT
;
9865 if(BattleGround
* bg
= GetBattleGround())
9866 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9867 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9870 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9871 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9873 return EQUIP_ERR_OK
;
9876 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9879 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9881 uint32 count
= pItem
->GetCount();
9883 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9884 ItemPrototype
const *pProto
= pItem
->GetProto();
9886 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9888 if( pItem
->IsBindedNotWith(GetGUID()) )
9889 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9891 // check count of items (skip for auto move for same player from bank)
9892 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9893 if(res
!= EQUIP_ERR_OK
)
9897 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9899 if( pProto
->InventoryType
== INVTYPE_BAG
)
9901 Bag
*pBag
= (Bag
*)pItem
;
9904 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9906 if( !HasBankBagSlot( slot
) )
9907 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9908 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9913 if( !pBag
->IsEmpty() )
9914 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9920 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9921 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9924 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9925 if(res
!=EQUIP_ERR_OK
)
9929 return EQUIP_ERR_OK
;
9932 // not specific slot or have space for partly store only in specific slot
9935 if( bag
!= NULL_BAG
)
9937 if( pProto
->InventoryType
== INVTYPE_BAG
)
9939 Bag
*pBag
= (Bag
*)pItem
;
9940 if( pBag
&& !pBag
->IsEmpty() )
9941 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9944 // search stack in bag for merge to
9945 if( pProto
->Stackable
> 1 )
9947 if( bag
== INVENTORY_SLOT_BAG_0
)
9949 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9950 if(res
!=EQUIP_ERR_OK
)
9954 return EQUIP_ERR_OK
;
9958 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9959 if(res
!=EQUIP_ERR_OK
)
9960 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9962 if(res
!=EQUIP_ERR_OK
)
9966 return EQUIP_ERR_OK
;
9970 // search free slot in bag
9971 if( bag
== INVENTORY_SLOT_BAG_0
)
9973 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9974 if(res
!=EQUIP_ERR_OK
)
9978 return EQUIP_ERR_OK
;
9982 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9983 if(res
!=EQUIP_ERR_OK
)
9984 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9986 if(res
!=EQUIP_ERR_OK
)
9990 return EQUIP_ERR_OK
;
9994 // not specific bag or have space for partly store only in specific bag
9996 // search stack for merge to
9997 if( pProto
->Stackable
> 1 )
10000 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10001 if(res
!=EQUIP_ERR_OK
)
10005 return EQUIP_ERR_OK
;
10008 if( pProto
->BagFamily
)
10010 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10012 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10013 if(res
!=EQUIP_ERR_OK
)
10017 return EQUIP_ERR_OK
;
10021 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10023 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10024 if(res
!=EQUIP_ERR_OK
)
10028 return EQUIP_ERR_OK
;
10032 // search free place in special bag
10033 if( pProto
->BagFamily
)
10035 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10037 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10038 if(res
!=EQUIP_ERR_OK
)
10042 return EQUIP_ERR_OK
;
10046 // search free space
10047 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10048 if(res
!=EQUIP_ERR_OK
)
10052 return EQUIP_ERR_OK
;
10054 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10056 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10057 if(res
!=EQUIP_ERR_OK
)
10061 return EQUIP_ERR_OK
;
10063 return EQUIP_ERR_BANK_FULL
;
10066 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10070 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10071 if( !isAlive() && not_loading
)
10072 return EQUIP_ERR_YOU_ARE_DEAD
;
10073 //if( isStunned() )
10074 // return EQUIP_ERR_YOU_ARE_STUNNED;
10075 ItemPrototype
const *pProto
= pItem
->GetProto();
10078 if( pItem
->IsBindedNotWith(GetGUID()) )
10079 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10080 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10081 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10082 if( pItem
->GetSkill() != 0 )
10084 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10085 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10087 if( pProto
->RequiredSkill
!= 0 )
10089 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10090 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10091 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10092 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10094 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10095 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10096 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10097 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10098 if( getLevel() < pProto
->RequiredLevel
)
10099 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10100 return EQUIP_ERR_OK
;
10103 return EQUIP_ERR_ITEM_NOT_FOUND
;
10106 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10108 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10112 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10114 if( pProto
->RequiredSkill
!= 0 )
10116 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10118 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10121 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10123 if( getLevel() < pProto
->RequiredLevel
)
10130 uint8
Player::CanUseAmmo( uint32 item
) const
10132 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10134 return EQUIP_ERR_YOU_ARE_DEAD
;
10135 //if( isStunned() )
10136 // return EQUIP_ERR_YOU_ARE_STUNNED;
10137 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10140 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10141 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10142 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10143 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10144 if( pProto
->RequiredSkill
!= 0 )
10146 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10147 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10148 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10149 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10151 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10152 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10153 /*if( GetReputation() < pProto->RequiredReputation )
10154 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10156 if( getLevel() < pProto
->RequiredLevel
)
10157 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10159 // Requires No Ammo
10160 if(GetDummyAura(46699))
10161 return EQUIP_ERR_BAG_FULL6
;
10163 return EQUIP_ERR_OK
;
10165 return EQUIP_ERR_ITEM_NOT_FOUND
;
10168 void Player::SetAmmo( uint32 item
)
10174 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10180 uint8 msg
= CanUseAmmo( item
);
10181 if( msg
!= EQUIP_ERR_OK
)
10183 SendEquipError( msg
, NULL
, NULL
);
10188 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10190 _ApplyAmmoBonuses();
10193 void Player::RemoveAmmo()
10195 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10199 if(CanModifyStats())
10200 UpdateDamagePhysical(RANGED_ATTACK
);
10203 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10204 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10207 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10208 count
+= itr
->count
;
10210 Item
*pItem
= Item::CreateItem( item
, count
, this );
10213 ItemAddedQuestCheck( item
, count
);
10214 if(randomPropertyId
)
10215 pItem
->SetItemRandomProperties(randomPropertyId
);
10216 pItem
= StoreItem( dest
, pItem
, update
);
10221 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10226 Item
* lastItem
= pItem
;
10228 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10230 uint16 pos
= itr
->pos
;
10231 uint32 count
= itr
->count
;
10235 if(itr
== dest
.end())
10237 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10241 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10247 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10248 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10253 uint8 bag
= pos
>> 8;
10254 uint8 slot
= pos
& 255;
10256 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10258 Item
*pItem2
= GetItemByPos( bag
, slot
);
10263 pItem
= pItem
->CloneItem(count
,this);
10265 pItem
->SetCount(count
);
10270 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10271 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10272 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10273 pItem
->SetBinding( true );
10275 if( bag
== INVENTORY_SLOT_BAG_0
)
10277 m_items
[slot
] = pItem
;
10278 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10279 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10280 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10282 pItem
->SetSlot( slot
);
10283 pItem
->SetContainer( NULL
);
10285 if( IsInWorld() && update
)
10287 pItem
->AddToWorld();
10288 pItem
->SendUpdateToPlayer( this );
10291 pItem
->SetState(ITEM_CHANGED
, this);
10295 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10298 pBag
->StoreItem( slot
, pItem
, update
);
10299 if( IsInWorld() && update
)
10301 pItem
->AddToWorld();
10302 pItem
->SendUpdateToPlayer( this );
10304 pItem
->SetState(ITEM_CHANGED
, this);
10305 pBag
->SetState(ITEM_CHANGED
, this);
10309 AddEnchantmentDurations(pItem
);
10310 AddItemDurations(pItem
);
10316 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10317 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10318 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10319 pItem2
->SetBinding( true );
10321 pItem2
->SetCount( pItem2
->GetCount() + count
);
10322 if( IsInWorld() && update
)
10323 pItem2
->SendUpdateToPlayer( this );
10327 // delete item (it not in any slot currently)
10328 if( IsInWorld() && update
)
10330 pItem
->RemoveFromWorld();
10331 pItem
->DestroyForPlayer( this );
10334 RemoveEnchantmentDurations(pItem
);
10335 RemoveItemDurations(pItem
);
10337 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10338 pItem
->SetState(ITEM_REMOVED
, this);
10340 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10341 AddEnchantmentDurations(pItem2
);
10343 pItem2
->SetState(ITEM_CHANGED
, this);
10349 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, uint32 count
, bool update
)
10351 Item
*pItem
= Item::CreateItem( item
, count
, this );
10354 ItemAddedQuestCheck( item
, count
);
10355 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10362 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10366 AddEnchantmentDurations(pItem
);
10367 AddItemDurations(pItem
);
10369 uint8 bag
= pos
>> 8;
10370 uint8 slot
= pos
& 255;
10372 Item
*pItem2
= GetItemByPos( bag
, slot
);
10376 VisualizeItem( slot
, pItem
);
10380 ItemPrototype
const *pProto
= pItem
->GetProto();
10382 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10383 if(pProto
&& pProto
->ItemSet
)
10384 AddItemsSetItem(this,pItem
);
10386 _ApplyItemMods(pItem
, slot
, true);
10388 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10390 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10392 if (getClass() == CLASS_ROGUE
)
10393 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10395 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10398 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10401 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10403 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10404 data
<< uint64(GetGUID());
10406 data
<< uint32(cooldownSpell
);
10408 GetSession()->SendPacket(&data
);
10413 if( IsInWorld() && update
)
10415 pItem
->AddToWorld();
10416 pItem
->SendUpdateToPlayer( this );
10419 ApplyEquipCooldown(pItem
);
10421 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10422 UpdateExpertise(BASE_ATTACK
);
10423 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10424 UpdateExpertise(OFF_ATTACK
);
10428 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10429 if( IsInWorld() && update
)
10430 pItem2
->SendUpdateToPlayer( this );
10432 // delete item (it not in any slot currently)
10433 //pItem->DeleteFromDB();
10434 if( IsInWorld() && update
)
10436 pItem
->RemoveFromWorld();
10437 pItem
->DestroyForPlayer( this );
10440 RemoveEnchantmentDurations(pItem
);
10441 RemoveItemDurations(pItem
);
10443 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10444 pItem
->SetState(ITEM_REMOVED
, this);
10445 pItem2
->SetState(ITEM_CHANGED
, this);
10447 ApplyEquipCooldown(pItem2
);
10456 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10460 AddEnchantmentDurations(pItem
);
10461 AddItemDurations(pItem
);
10463 uint8 slot
= pos
& 255;
10464 VisualizeItem( slot
, pItem
);
10468 pItem
->AddToWorld();
10469 pItem
->SendUpdateToPlayer( this );
10474 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10476 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10477 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10478 // entry // Size: 1
10479 // inspected enchantments // Size: 6
10481 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10482 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10487 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10489 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10490 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10492 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10493 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10495 // Use SetInt16Value to prevent set high part to FFFF for negative value
10496 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10497 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10501 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10503 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10504 SetUInt32Value(VisibleBase
+ 0, 0);
10506 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10507 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10509 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10510 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10514 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10519 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10520 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10521 pItem
->SetBinding( true );
10523 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10525 m_items
[slot
] = pItem
;
10526 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10527 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10528 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10529 pItem
->SetSlot( slot
);
10530 pItem
->SetContainer( NULL
);
10532 if( slot
< EQUIPMENT_SLOT_END
)
10533 SetVisibleItemSlot(slot
,pItem
);
10535 pItem
->SetState(ITEM_CHANGED
, this);
10538 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10540 // note: removeitem does not actually change the item
10541 // it only takes the item out of storage temporarily
10542 // note2: if removeitem is to be used for delinking
10543 // the item must be removed from the player's updatequeue
10545 Item
*pItem
= GetItemByPos( bag
, slot
);
10548 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10550 RemoveEnchantmentDurations(pItem
);
10551 RemoveItemDurations(pItem
);
10553 if( bag
== INVENTORY_SLOT_BAG_0
)
10555 if ( slot
< INVENTORY_SLOT_BAG_END
)
10557 ItemPrototype
const *pProto
= pItem
->GetProto();
10558 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10560 if(pProto
&& pProto
->ItemSet
)
10561 RemoveItemsSetItem(this,pProto
);
10563 _ApplyItemMods(pItem
, slot
, false);
10565 // remove item dependent auras and casts (only weapon and armor slots)
10566 if(slot
< EQUIPMENT_SLOT_END
)
10567 RemoveItemDependentAurasAndCasts(pItem
);
10569 // remove held enchantments
10570 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10572 if (pItem
->GetItemSuffixFactor())
10574 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10575 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10579 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10580 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10585 m_items
[slot
] = NULL
;
10586 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10588 if ( slot
< EQUIPMENT_SLOT_END
)
10589 SetVisibleItemSlot(slot
,NULL
);
10593 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10595 pBag
->RemoveItem(slot
, update
);
10597 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10598 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10599 pItem
->SetSlot( NULL_SLOT
);
10600 if( IsInWorld() && update
)
10601 pItem
->SendUpdateToPlayer( this );
10603 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10604 UpdateExpertise(BASE_ATTACK
);
10605 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10606 UpdateExpertise(OFF_ATTACK
);
10610 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10611 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10613 if(Item
* it
= GetItemByPos(bag
,slot
))
10615 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10616 RemoveItem( bag
,slot
,update
);
10617 it
->RemoveFromUpdateQueueOf(this);
10618 if(it
->IsInWorld())
10620 it
->RemoveFromWorld();
10621 it
->DestroyForPlayer( this );
10626 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10627 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10629 // update quest counters
10630 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10633 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10635 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10636 if(pLastItem
==pItem
)
10638 // update owner for last item (this can be original item with wrong owner
10639 if(pLastItem
->GetOwnerGUID() != GetGUID())
10640 pLastItem
->SetOwnerGUID(GetGUID());
10642 // if this original item then it need create record in inventory
10643 // in case trade we already have item in other player inventory
10644 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10648 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10650 Item
*pItem
= GetItemByPos( bag
, slot
);
10653 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10655 // start from destroy contained items (only equipped bag can have its)
10656 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10658 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10659 DestroyItem(slot
,i
,update
);
10662 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10663 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10665 RemoveEnchantmentDurations(pItem
);
10666 RemoveItemDurations(pItem
);
10668 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10670 if( bag
== INVENTORY_SLOT_BAG_0
)
10672 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10674 // equipment and equipped bags can have applied bonuses
10675 if ( slot
< INVENTORY_SLOT_BAG_END
)
10677 ItemPrototype
const *pProto
= pItem
->GetProto();
10679 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10680 if(pProto
&& pProto
->ItemSet
)
10681 RemoveItemsSetItem(this,pProto
);
10683 _ApplyItemMods(pItem
, slot
, false);
10686 if ( slot
< EQUIPMENT_SLOT_END
)
10688 // remove item dependent auras and casts (only weapon and armor slots)
10689 RemoveItemDependentAurasAndCasts(pItem
);
10691 // equipment visual show
10692 SetVisibleItemSlot(slot
,NULL
);
10695 m_items
[slot
] = NULL
;
10697 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10698 pBag
->RemoveItem(slot
, update
);
10700 if( IsInWorld() && update
)
10702 pItem
->RemoveFromWorld();
10703 pItem
->DestroyForPlayer(this);
10706 //pItem->SetOwnerGUID(0);
10707 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10708 pItem
->SetSlot( NULL_SLOT
);
10709 pItem
->SetState(ITEM_REMOVED
, this);
10713 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10715 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10717 ItemPrototype
const *pProto
;
10718 uint32 remcount
= 0;
10721 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10723 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10724 if( pItem
&& pItem
->GetEntry() == item
)
10726 if( pItem
->GetCount() + remcount
<= count
)
10728 // all items in inventory can unequipped
10729 remcount
+= pItem
->GetCount();
10730 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10732 if(remcount
>=count
)
10737 pProto
= pItem
->GetProto();
10738 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10739 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10740 if( IsInWorld() & update
)
10741 pItem
->SendUpdateToPlayer( this );
10742 pItem
->SetState(ITEM_CHANGED
, this);
10747 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10749 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10750 if( pItem
&& pItem
->GetEntry() == item
)
10752 if( pItem
->GetCount() + remcount
<= count
)
10754 // all keys can be unequipped
10755 remcount
+= pItem
->GetCount();
10756 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10758 if(remcount
>=count
)
10763 pProto
= pItem
->GetProto();
10764 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10765 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10766 if( IsInWorld() & update
)
10767 pItem
->SendUpdateToPlayer( this );
10768 pItem
->SetState(ITEM_CHANGED
, this);
10774 // in inventory bags
10775 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10777 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10779 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10781 pItem
= pBag
->GetItemByPos(j
);
10782 if( pItem
&& pItem
->GetEntry() == item
)
10784 // all items in bags can be unequipped
10785 if( pItem
->GetCount() + remcount
<= count
)
10787 remcount
+= pItem
->GetCount();
10788 DestroyItem( i
, j
, update
);
10790 if(remcount
>=count
)
10795 pProto
= pItem
->GetProto();
10796 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10797 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10798 if( IsInWorld() && update
)
10799 pItem
->SendUpdateToPlayer( this );
10800 pItem
->SetState(ITEM_CHANGED
, this);
10808 // in equipment and bag list
10809 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10811 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10812 if( pItem
&& pItem
->GetEntry() == item
)
10814 if( pItem
->GetCount() + remcount
<= count
)
10816 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10818 remcount
+= pItem
->GetCount();
10819 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10821 if(remcount
>=count
)
10827 pProto
= pItem
->GetProto();
10828 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10829 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10830 if( IsInWorld() & update
)
10831 pItem
->SendUpdateToPlayer( this );
10832 pItem
->SetState(ITEM_CHANGED
, this);
10839 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10841 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10844 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10846 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10847 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10848 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10850 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10852 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10853 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10854 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10857 // in inventory bags
10858 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10860 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10863 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10865 Item
* pItem
= pBag
->GetItemByPos(j
);
10866 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10867 DestroyItem( i
, j
, update
);
10872 // in equipment and bag list
10873 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10875 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10876 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10877 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10881 void Player::DestroyConjuredItems( bool update
)
10883 // used when entering arena
10884 // destroys all conjured items
10885 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10888 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10890 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10891 if( pItem
&& pItem
->GetProto() &&
10892 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10893 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10894 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10897 // in inventory bags
10898 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10900 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10903 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10905 Item
* pItem
= pBag
->GetItemByPos(j
);
10906 if( pItem
&& pItem
->GetProto() &&
10907 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10908 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10909 DestroyItem( i
, j
, update
);
10914 // in equipment and bag list
10915 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10917 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10918 if( pItem
&& pItem
->GetProto() &&
10919 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10920 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10921 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10925 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10930 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10932 if( pItem
->GetCount() <= count
)
10934 count
-= pItem
->GetCount();
10936 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10940 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10941 pItem
->SetCount( pItem
->GetCount() - count
);
10943 if( IsInWorld() & update
)
10944 pItem
->SendUpdateToPlayer( this );
10945 pItem
->SetState(ITEM_CHANGED
, this);
10949 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10951 uint8 srcbag
= src
>> 8;
10952 uint8 srcslot
= src
& 255;
10954 uint8 dstbag
= dst
>> 8;
10955 uint8 dstslot
= dst
& 255;
10957 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10960 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10964 // not let split all items (can be only at cheating)
10965 if(pSrcItem
->GetCount() == count
)
10967 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10971 // not let split more existed items (can be only at cheating)
10972 if(pSrcItem
->GetCount() < count
)
10974 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10978 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10980 //best error message found for attempting to split while looting
10981 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10985 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10986 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10989 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10993 if( IsInventoryPos( dst
) )
10995 // change item amount before check (for unique max count check)
10996 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10998 ItemPosCountVec dest
;
10999 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11000 if( msg
!= EQUIP_ERR_OK
)
11003 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11004 SendEquipError( msg
, pSrcItem
, NULL
);
11009 pSrcItem
->SendUpdateToPlayer( this );
11010 pSrcItem
->SetState(ITEM_CHANGED
, this);
11011 StoreItem( dest
, pNewItem
, true);
11013 else if( IsBankPos ( dst
) )
11015 // change item amount before check (for unique max count check)
11016 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11018 ItemPosCountVec dest
;
11019 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11020 if( msg
!= EQUIP_ERR_OK
)
11023 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11024 SendEquipError( msg
, pSrcItem
, NULL
);
11029 pSrcItem
->SendUpdateToPlayer( this );
11030 pSrcItem
->SetState(ITEM_CHANGED
, this);
11031 BankItem( dest
, pNewItem
, true);
11033 else if( IsEquipmentPos ( dst
) )
11035 // change item amount before check (for unique max count check), provide space for splitted items
11036 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11039 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11040 if( msg
!= EQUIP_ERR_OK
)
11043 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11044 SendEquipError( msg
, pSrcItem
, NULL
);
11049 pSrcItem
->SendUpdateToPlayer( this );
11050 pSrcItem
->SetState(ITEM_CHANGED
, this);
11051 EquipItem( dest
, pNewItem
, true);
11052 AutoUnequipOffhandIfNeed();
11056 void Player::SwapItem( uint16 src
, uint16 dst
)
11058 uint8 srcbag
= src
>> 8;
11059 uint8 srcslot
= src
& 255;
11061 uint8 dstbag
= dst
>> 8;
11062 uint8 dstslot
= dst
& 255;
11064 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11065 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11070 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11074 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11078 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11080 //best error message found for attempting to swap while looting
11081 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11085 // check unequip potability for equipped items and bank bags
11086 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11088 // bags can be swapped with empty bag slots
11089 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
11090 if(msg
!= EQUIP_ERR_OK
)
11092 SendEquipError( msg
, pSrcItem
, pDstItem
);
11097 // prevent put equipped/bank bag in self
11098 if( IsBagPos ( src
) && srcslot
== dstbag
)
11100 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11106 if( IsInventoryPos( dst
) )
11108 ItemPosCountVec dest
;
11109 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11110 if( msg
!= EQUIP_ERR_OK
)
11112 SendEquipError( msg
, pSrcItem
, NULL
);
11116 RemoveItem(srcbag
, srcslot
, true);
11117 StoreItem( dest
, pSrcItem
, true);
11119 else if( IsBankPos ( dst
) )
11121 ItemPosCountVec dest
;
11122 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11123 if( msg
!= EQUIP_ERR_OK
)
11125 SendEquipError( msg
, pSrcItem
, NULL
);
11129 RemoveItem(srcbag
, srcslot
, true);
11130 BankItem( dest
, pSrcItem
, true);
11132 else if( IsEquipmentPos ( dst
) )
11135 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11136 if( msg
!= EQUIP_ERR_OK
)
11138 SendEquipError( msg
, pSrcItem
, NULL
);
11142 RemoveItem(srcbag
, srcslot
, true);
11143 EquipItem( dest
, pSrcItem
, true);
11144 AutoUnequipOffhandIfNeed();
11147 else // if (!pDstItem)
11149 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11151 //best error message found for attempting to swap while looting
11152 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11156 // check unequip potability for equipped items and bank bags
11157 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11159 // bags can be swapped with empty bag slots
11160 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
11161 if(msg
!= EQUIP_ERR_OK
)
11163 SendEquipError( msg
, pSrcItem
, pDstItem
);
11168 // attempt merge to / fill target item
11171 ItemPosCountVec sDest
;
11173 if( IsInventoryPos( dst
) )
11174 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11175 else if( IsBankPos ( dst
) )
11176 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11177 else if( IsEquipmentPos ( dst
) )
11178 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11182 // can be merge/fill
11183 if(msg
== EQUIP_ERR_OK
)
11185 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->Stackable
)
11187 RemoveItem(srcbag
, srcslot
, true);
11189 if( IsInventoryPos( dst
) )
11190 StoreItem( sDest
, pSrcItem
, true);
11191 else if( IsBankPos ( dst
) )
11192 BankItem( sDest
, pSrcItem
, true);
11193 else if( IsEquipmentPos ( dst
) )
11195 EquipItem( eDest
, pSrcItem
, true);
11196 AutoUnequipOffhandIfNeed();
11201 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->Stackable
);
11202 pDstItem
->SetCount( pSrcItem
->GetProto()->Stackable
);
11203 pSrcItem
->SetState(ITEM_CHANGED
, this);
11204 pDstItem
->SetState(ITEM_CHANGED
, this);
11207 pSrcItem
->SendUpdateToPlayer( this );
11208 pDstItem
->SendUpdateToPlayer( this );
11215 // impossible merge/fill, do real swap
11218 // check src->dest move possibility
11219 ItemPosCountVec sDest
;
11221 if( IsInventoryPos( dst
) )
11222 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11223 else if( IsBankPos( dst
) )
11224 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11225 else if( IsEquipmentPos( dst
) )
11227 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11228 if( msg
== EQUIP_ERR_OK
)
11229 msg
= CanUnequipItem( eDest
, true );
11232 if( msg
!= EQUIP_ERR_OK
)
11234 SendEquipError( msg
, pSrcItem
, pDstItem
);
11238 // check dest->src move possibility
11239 ItemPosCountVec sDest2
;
11241 if( IsInventoryPos( src
) )
11242 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11243 else if( IsBankPos( src
) )
11244 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11245 else if( IsEquipmentPos( src
) )
11247 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11248 if( msg
== EQUIP_ERR_OK
)
11249 msg
= CanUnequipItem( eDest2
, true);
11252 if( msg
!= EQUIP_ERR_OK
)
11254 SendEquipError( msg
, pDstItem
, pSrcItem
);
11258 // now do moves, remove...
11259 RemoveItem(dstbag
, dstslot
, false);
11260 RemoveItem(srcbag
, srcslot
, false);
11263 if( IsInventoryPos( dst
) )
11264 StoreItem(sDest
, pSrcItem
, true);
11265 else if( IsBankPos( dst
) )
11266 BankItem(sDest
, pSrcItem
, true);
11267 else if( IsEquipmentPos( dst
) )
11268 EquipItem(eDest
, pSrcItem
, true);
11271 if( IsInventoryPos( src
) )
11272 StoreItem(sDest2
, pDstItem
, true);
11273 else if( IsBankPos( src
) )
11274 BankItem(sDest2
, pDstItem
, true);
11275 else if( IsEquipmentPos( src
) )
11276 EquipItem(eDest2
, pDstItem
, true);
11278 AutoUnequipOffhandIfNeed();
11282 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11286 uint32 slot
= m_currentBuybackSlot
;
11287 // if current back slot non-empty search oldest or free
11290 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11291 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11293 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11302 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11304 if(oldest_time
> i_time
)
11306 oldest_time
= i_time
;
11312 slot
= oldest_slot
;
11315 RemoveItemFromBuyBackSlot( slot
, true );
11316 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11318 m_items
[slot
] = pItem
;
11319 time_t base
= time(NULL
);
11320 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11321 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11323 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11324 ItemPrototype
const *pProto
= pItem
->GetProto();
11326 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11328 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11329 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11331 // move to next (for non filled list is move most optimized choice)
11332 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11333 ++m_currentBuybackSlot
;
11337 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11339 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11340 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11341 return m_items
[slot
];
11345 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11347 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11348 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11350 Item
*pItem
= m_items
[slot
];
11353 pItem
->RemoveFromWorld();
11354 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11357 m_items
[slot
] = NULL
;
11359 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11360 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11361 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11362 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11364 // if current backslot is filled set to now free slot
11365 if(m_items
[m_currentBuybackSlot
])
11366 m_currentBuybackSlot
= slot
;
11370 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11372 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11373 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11374 data
<< uint8(msg
);
11378 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11379 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11380 data
<< uint8(0); // not 0 there...
11382 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11387 if(ItemPrototype
const* proto
= pItem
->GetProto())
11388 level
= proto
->RequiredLevel
;
11390 data
<< uint32(level
); // new 2.4.0
11393 GetSession()->SendPacket(&data
);
11396 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11398 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11399 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11400 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11401 data
<< uint32(item
);
11403 data
<< uint32(param
);
11404 data
<< uint8(msg
);
11405 GetSession()->SendPacket(&data
);
11408 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11410 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11411 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11412 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11413 data
<< uint64(guid
);
11415 data
<< uint32(param
);
11416 data
<< uint8(msg
);
11417 GetSession()->SendPacket(&data
);
11420 void Player::ClearTrade()
11423 acceptTrade
= false;
11424 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11425 tradeItems
[i
] = NULL_SLOT
;
11428 void Player::TradeCancel(bool sendback
)
11432 // send yellow "Trade canceled" message to both traders
11436 ws
->SendCancelTrade();
11437 ws
= pTrader
->GetSession();
11438 if(!ws
->PlayerLogout())
11439 ws
->SendCancelTrade();
11443 pTrader
->ClearTrade();
11444 // prevent loss of reference
11445 pTrader
->pTrader
= NULL
;
11450 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11452 if(m_itemDuration
.empty())
11455 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11457 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11460 ++itr
; // current element can be erased in UpdateDuration
11462 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11463 item
->UpdateDuration(this,time
);
11467 void Player::UpdateEnchantTime(uint32 time
)
11469 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11473 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11475 next
= m_enchantDuration
.erase(itr
);
11477 else if(itr
->leftduration
<= time
)
11479 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11480 itr
->item
->ClearEnchantment(itr
->slot
);
11481 next
= m_enchantDuration
.erase(itr
);
11483 else if(itr
->leftduration
> time
)
11485 itr
->leftduration
-= time
;
11491 void Player::AddEnchantmentDurations(Item
*item
)
11493 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11495 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11498 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11500 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11504 void Player::RemoveEnchantmentDurations(Item
*item
)
11506 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11508 if(itr
->item
== item
)
11510 // save duration in item
11511 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11512 itr
= m_enchantDuration
.erase(itr
);
11519 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11521 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11522 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11525 if(itr
->slot
==slot
)
11527 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11529 // remove from stats
11530 ApplyEnchantment(itr
->item
,slot
,false,false);
11532 itr
->item
->ClearEnchantment(slot
);
11534 // remove from update list
11535 next
= m_enchantDuration
.erase(itr
);
11541 // remove enchants from inventory items
11542 // NOTE: no need to remove these from stats, since these aren't equipped
11544 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11546 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11547 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11548 pItem
->ClearEnchantment(slot
);
11551 // in inventory bags
11552 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11554 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11557 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11559 Item
* pItem
= pBag
->GetItemByPos(j
);
11560 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11561 pItem
->ClearEnchantment(slot
);
11567 // duration == 0 will remove item enchant
11568 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11573 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11576 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11578 if(itr
->item
== item
&& itr
->slot
== slot
)
11580 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11581 m_enchantDuration
.erase(itr
);
11585 if(item
&& duration
> 0 )
11587 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11588 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11592 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11594 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11595 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11598 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11603 if(!item
->IsEquipped())
11606 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11609 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11613 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11617 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11620 for (int s
=0; s
<3; s
++)
11622 uint32 enchant_display_type
= pEnchant
->type
[s
];
11623 uint32 enchant_amount
= pEnchant
->amount
[s
];
11624 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11626 switch(enchant_display_type
)
11628 case ITEM_ENCHANTMENT_TYPE_NONE
:
11630 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11631 // processed in Player::CastItemCombatSpell
11633 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11634 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11635 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11636 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11637 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11638 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11639 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11641 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11642 if(enchant_spell_id
)
11646 int32 basepoints
= int32(enchant_amount
);
11647 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11648 if (item
->GetItemRandomPropertyId() !=0 && !enchant_amount
)
11650 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11653 // Search enchant_amount
11654 for (int k
=0; k
<3; k
++)
11656 if(item_rand
->enchant_id
[k
] == enchant_id
)
11658 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11664 // Cast custom spell vs all equal basepoints getted from enchant_amount
11666 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11668 CastSpell(this,enchant_spell_id
,true,item
);
11671 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11674 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11675 if (!enchant_amount
)
11677 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11680 for (int k
=0; k
<3; k
++)
11682 if(item_rand
->enchant_id
[k
] == enchant_id
)
11684 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11691 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11693 case ITEM_ENCHANTMENT_TYPE_STAT
:
11695 if (!enchant_amount
)
11697 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11698 if(item_rand_suffix
)
11700 for (int k
=0; k
<3; k
++)
11702 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11704 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11711 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11712 switch (enchant_spell_id
)
11714 case ITEM_MOD_AGILITY
:
11715 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11716 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11717 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11719 case ITEM_MOD_STRENGTH
:
11720 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11721 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11722 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11724 case ITEM_MOD_INTELLECT
:
11725 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11726 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11727 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11729 case ITEM_MOD_SPIRIT
:
11730 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11731 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11732 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11734 case ITEM_MOD_STAMINA
:
11735 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11736 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11737 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11739 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11740 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11741 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11743 case ITEM_MOD_DODGE_RATING
:
11744 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11745 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11747 case ITEM_MOD_PARRY_RATING
:
11748 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11749 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11751 case ITEM_MOD_BLOCK_RATING
:
11752 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11753 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11755 case ITEM_MOD_HIT_MELEE_RATING
:
11756 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11757 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11759 case ITEM_MOD_HIT_RANGED_RATING
:
11760 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11761 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11763 case ITEM_MOD_HIT_SPELL_RATING
:
11764 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11765 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11767 case ITEM_MOD_CRIT_MELEE_RATING
:
11768 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11769 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11771 case ITEM_MOD_CRIT_RANGED_RATING
:
11772 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11773 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11775 case ITEM_MOD_CRIT_SPELL_RATING
:
11776 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11777 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11779 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11781 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11782 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11784 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11785 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11787 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11788 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11790 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11791 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11793 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11794 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11796 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11797 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11799 // case ITEM_MOD_HASTE_MELEE_RATING:
11800 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11802 // case ITEM_MOD_HASTE_RANGED_RATING:
11803 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11805 case ITEM_MOD_HASTE_SPELL_RATING
:
11806 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11808 case ITEM_MOD_HIT_RATING
:
11809 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11810 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11811 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11812 sLog
.outDebug("+ %u HIT", enchant_amount
);
11814 case ITEM_MOD_CRIT_RATING
:
11815 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11816 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11817 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11818 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11820 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11821 // case ITEM_MOD_HIT_TAKEN_RATING:
11822 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11823 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11824 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11826 // case ITEM_MOD_CRIT_TAKEN_RATING:
11827 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11828 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11829 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11831 case ITEM_MOD_RESILIENCE_RATING
:
11832 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11833 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11834 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11835 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11837 case ITEM_MOD_HASTE_RATING
:
11838 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11839 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11840 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11841 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11843 case ITEM_MOD_EXPERTISE_RATING
:
11844 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11845 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11847 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11848 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11849 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11856 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11858 if(getClass() == CLASS_SHAMAN
)
11860 float addValue
= 0.0f
;
11861 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11863 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11864 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11866 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11868 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11869 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11875 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
11877 } /*switch(enchant_display_type)*/
11880 // visualize enchantment at player and equipped items
11881 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11883 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11884 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11892 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11894 AddEnchantmentDuration(item
,slot
,duration
);
11898 // duration == 0 will remove EnchantDuration
11899 AddEnchantmentDuration(item
,slot
,0);
11904 void Player::SendEnchantmentDurations()
11906 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11908 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11912 void Player::SendItemDurations()
11914 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11916 (*itr
)->SendTimeUpdate(this);
11920 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11922 if(!item
) // prevent crash
11925 // last check 2.0.10
11926 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11927 data
<< GetGUID(); // player GUID
11928 data
<< uint32(received
); // 0=looted, 1=from npc
11929 data
<< uint32(created
); // 0=received, 1=created
11930 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11931 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11932 // item slot, but when added to stack: 0xFFFFFFFF
11933 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11934 data
<< uint32(item
->GetEntry()); // item id
11935 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11936 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11937 data
<< uint32(count
); // count of items
11938 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11940 if (broadcast
&& GetGroup())
11941 GetGroup()->BroadcastPacket(&data
);
11943 GetSession()->SendPacket(&data
);
11946 /*********************************************************/
11947 /*** QUEST SYSTEM ***/
11948 /*********************************************************/
11950 void Player::PrepareQuestMenu( uint64 guid
)
11953 QuestRelations
* pObjectQR
;
11954 QuestRelations
* pObjectQIR
;
11955 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11958 pObject
= (Object
*)pCreature
;
11959 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11960 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11964 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11967 pObject
= (Object
*)pGameObject
;
11968 pObjectQR
= &objmgr
.mGOQuestRelations
;
11969 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11975 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11978 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11980 uint32 quest_id
= i
->second
;
11981 QuestStatus status
= GetQuestStatus( quest_id
);
11982 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11983 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11984 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11985 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11986 else if (status
== QUEST_STATUS_AVAILABLE
)
11987 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11990 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11992 uint32 quest_id
= i
->second
;
11993 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11994 if(!pQuest
) continue;
11996 QuestStatus status
= GetQuestStatus( quest_id
);
11998 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11999 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12000 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12001 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12005 void Player::SendPreparedQuest( uint64 guid
)
12007 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12008 if( questMenu
.Empty() )
12011 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12013 uint32 status
= qmi0
.m_qIcon
;
12015 // single element case
12016 if ( questMenu
.MenuItemCount() == 1 )
12018 // Auto open -- maybe also should verify there is no greeting
12019 uint32 quest_id
= qmi0
.m_qId
;
12020 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12023 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12024 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12025 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12026 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12027 // Send completable on repeatable quest if player don't have quest
12028 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12029 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12031 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12034 // multiply entries
12040 std::string title
= "";
12041 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12044 uint32 textid
= pCreature
->GetNpcTextId();
12045 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
12048 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12049 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12054 qe
= gossiptext
->Options
[0].Emotes
[0];
12056 if(!gossiptext
->Options
[0].Text_0
.empty())
12058 title
= gossiptext
->Options
[0].Text_0
;
12060 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12063 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12066 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12067 title
= nl
->Text_0
[0][loc_idx
];
12073 title
= gossiptext
->Options
[0].Text_1
;
12075 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12078 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12081 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12082 title
= nl
->Text_1
[0][loc_idx
];
12088 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12092 bool Player::IsActiveQuest( uint32 quest_id
) const
12094 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12096 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12099 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12102 QuestRelations
* pObjectQR
;
12103 QuestRelations
* pObjectQIR
;
12105 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12108 pObject
= (Object
*)pCreature
;
12109 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12110 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12114 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12117 pObject
= (Object
*)pGameObject
;
12118 pObjectQR
= &objmgr
.mGOQuestRelations
;
12119 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12125 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12126 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12128 if (itr
->second
== nextQuestID
)
12129 return objmgr
.GetQuestTemplate(nextQuestID
);
12135 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12137 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12138 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12139 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12140 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12142 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12148 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12150 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12151 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12152 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12153 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12154 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12155 && SatisfyQuestDay( pQuest
, msg
);
12158 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12160 if( !SatisfyQuestLog( msg
) )
12163 uint32 srcitem
= pQuest
->GetSrcItemId();
12166 uint32 count
= pQuest
->GetSrcItemCount();
12167 ItemPosCountVec dest
;
12168 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12170 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12171 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12173 else if( msg
!= EQUIP_ERR_OK
)
12175 SendEquipError( msg
, NULL
, NULL
);
12182 bool Player::CanCompleteQuest( uint32 quest_id
)
12186 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12187 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12188 return false; // not allow re-complete quest
12190 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12195 // auto complete quest
12196 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12199 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12202 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12204 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12206 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12211 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12213 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12215 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12218 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12223 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12226 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12229 if ( qInfo
->GetRewOrReqMoney() < 0 )
12231 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12235 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12236 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12245 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12247 // Solve problem that player don't have the quest and try complete it.
12248 // if repeatable she must be able to complete event if player don't have it.
12249 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12250 if( !CanTakeQuest(pQuest
, false) )
12253 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12254 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12255 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12258 if( !CanRewardQuest(pQuest
, false) )
12264 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12266 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12267 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12270 // daily quest can't be rewarded (25 daily quest already completed)
12271 if(!SatisfyQuestDay(pQuest
,true))
12274 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12275 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12278 // prevent receive reward with quest items in bank
12279 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12281 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12283 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12284 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12287 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12293 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12294 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12300 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12302 // prevent receive reward with quest items in bank or for not completed quest
12303 if(!CanRewardQuest(pQuest
,msg
))
12306 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12308 if( pQuest
->RewChoiceItemId
[reward
] )
12310 ItemPosCountVec dest
;
12311 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12312 if( res
!= EQUIP_ERR_OK
)
12314 SendEquipError( res
, NULL
, NULL
);
12320 if ( pQuest
->GetRewItemsCount() > 0 )
12322 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12324 if( pQuest
->RewItemId
[i
] )
12326 ItemPosCountVec dest
;
12327 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12328 if( res
!= EQUIP_ERR_OK
)
12330 SendEquipError( res
, NULL
, NULL
);
12340 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12342 uint16 log_slot
= FindQuestSlot( 0 );
12343 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12345 uint32 quest_id
= pQuest
->GetQuestId();
12347 // if not exist then created with set uState==NEW and rewarded=false
12348 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12349 if (questStatusData
.uState
!= QUEST_NEW
)
12350 questStatusData
.uState
= QUEST_CHANGED
;
12352 // check for repeatable quests status reset
12353 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12354 questStatusData
.m_explored
= false;
12356 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12358 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12359 questStatusData
.m_itemcount
[i
] = 0;
12362 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12364 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12365 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12368 GiveQuestSourceItem( pQuest
);
12369 AdjustQuestReqItemCount( pQuest
);
12371 if( pQuest
->GetRepObjectiveFaction() )
12372 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12375 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12377 uint32 limittime
= pQuest
->GetLimitTime();
12379 // shared timed quest
12380 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12381 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12383 AddTimedQuest( quest_id
);
12384 questStatusData
.m_timer
= limittime
* 1000;
12385 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12388 questStatusData
.m_timer
= 0;
12390 SetQuestSlot(log_slot
, quest_id
, qtime
);
12392 //starting initial quest script
12393 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12394 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12396 UpdateForQuestsGO();
12399 void Player::CompleteQuest( uint32 quest_id
)
12403 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12405 uint16 log_slot
= FindQuestSlot( quest_id
);
12406 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12407 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12409 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12411 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12412 RewardQuest(qInfo
,0,this,false);
12414 SendQuestComplete( quest_id
);
12419 void Player::IncompleteQuest( uint32 quest_id
)
12423 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12425 uint16 log_slot
= FindQuestSlot( quest_id
);
12426 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12427 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12431 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12433 uint32 quest_id
= pQuest
->GetQuestId();
12435 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12437 if ( pQuest
->ReqItemId
[i
] )
12438 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12441 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12442 // SetTimedQuest( 0 );
12443 m_timedquests
.erase(pQuest
->GetQuestId());
12445 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12447 if( pQuest
->RewChoiceItemId
[reward
] )
12449 ItemPosCountVec dest
;
12450 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12452 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12453 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12458 if ( pQuest
->GetRewItemsCount() > 0 )
12460 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12462 if( pQuest
->RewItemId
[i
] )
12464 ItemPosCountVec dest
;
12465 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12467 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12468 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12474 RewardReputation( pQuest
);
12476 if( pQuest
->GetRewSpellCast() > 0 )
12477 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12478 else if( pQuest
->GetRewSpell() > 0)
12479 CastSpell( this, pQuest
->GetRewSpell(), true);
12481 uint16 log_slot
= FindQuestSlot( quest_id
);
12482 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12483 SetQuestSlot(log_slot
,0);
12485 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12487 // Not give XP in case already completed once repeatable quest
12488 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12490 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12491 GiveXP( XP
, NULL
);
12493 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12495 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12496 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12499 if(pQuest
->GetRewHonorableKills())
12500 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12503 if(pQuest
->GetCharTitleId())
12505 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12506 SetTitle(titleEntry
);
12509 // Send reward mail
12510 if(pQuest
->GetRewMailTemplateId())
12512 MailMessageType mailType
;
12513 uint32 senderGuidOrEntry
;
12514 switch(questGiver
->GetTypeId())
12517 mailType
= MAIL_CREATURE
;
12518 senderGuidOrEntry
= questGiver
->GetEntry();
12520 case TYPEID_GAMEOBJECT
:
12521 mailType
= MAIL_GAMEOBJECT
;
12522 senderGuidOrEntry
= questGiver
->GetEntry();
12525 mailType
= MAIL_ITEM
;
12526 senderGuidOrEntry
= questGiver
->GetEntry();
12528 case TYPEID_PLAYER
:
12529 mailType
= MAIL_NORMAL
;
12530 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12533 mailType
= MAIL_NORMAL
;
12534 senderGuidOrEntry
= GetGUIDLow();
12538 Loot questMailLoot
;
12540 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12543 MailItemsInfo mi
; // item list preparing
12545 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12547 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12549 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12551 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12552 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12557 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12559 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12561 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12563 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12564 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12569 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12572 if(pQuest
->IsDaily())
12574 SetDailyQuestStatus(quest_id
);
12575 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12578 if ( !pQuest
->IsRepeatable() )
12579 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12581 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12583 q_status
.m_rewarded
= true;
12586 SendQuestReward( pQuest
, XP
, questGiver
);
12588 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12589 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12593 void Player::FailQuest( uint32 quest_id
)
12597 IncompleteQuest( quest_id
);
12599 uint16 log_slot
= FindQuestSlot( quest_id
);
12600 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12602 SetQuestSlotTimer(log_slot
, 1 );
12603 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12605 SendQuestFailed( quest_id
);
12609 void Player::FailTimedQuest( uint32 quest_id
)
12613 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12615 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12616 q_status
.m_timer
= 0;
12618 IncompleteQuest( quest_id
);
12620 uint16 log_slot
= FindQuestSlot( quest_id
);
12621 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12623 SetQuestSlotTimer(log_slot
, 1 );
12624 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12626 SendQuestTimerFailed( quest_id
);
12630 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12632 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12633 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12635 // skip zone zoneOrSort and 0 case skillOrClass
12636 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12639 int32 questSort
= -zoneOrSort
;
12640 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12642 // check class sort cases in zoneOrSort
12643 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12646 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12651 if( skillOrClass
< 0 )
12653 uint8 reqClass
= -int32(skillOrClass
);
12654 if(getClass() != reqClass
)
12657 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12662 else if( skillOrClass
> 0 )
12664 uint32 reqSkill
= skillOrClass
;
12665 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12668 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12676 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12678 if( getLevel() < qInfo
->GetMinLevel() )
12681 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12687 bool Player::SatisfyQuestLog( bool msg
)
12690 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12695 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12696 GetSession()->SendPacket( &data
);
12697 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12702 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12704 // No previous quest (might be first quest in a series)
12705 if( qInfo
->prevQuests
.empty())
12708 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12710 uint32 prevId
= abs(*iter
);
12712 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12713 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12715 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12717 // If any of the positive previous quests completed, return true
12718 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12720 // skip one-from-all exclusive group
12721 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12724 // each-from-all exclusive group ( < 0)
12725 // can be start if only all quests in prev quest exclusive group completed and rewarded
12726 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12727 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12729 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12731 for(; iter
!= end
; ++iter
)
12733 uint32 exclude_Id
= iter
->second
;
12735 // skip checked quest id, only state of other quests in group is interesting
12736 if(exclude_Id
== prevId
)
12739 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12741 // alternative quest from group also must be completed and rewarded(reported)
12742 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12745 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12751 // If any of the negative previous quests active, return true
12752 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12753 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12755 // skip one-from-all exclusive group
12756 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12759 // each-from-all exclusive group ( < 0)
12760 // can be start if only all quests in prev quest exclusive group active
12761 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12762 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12764 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12766 for(; iter
!= end
; ++iter
)
12768 uint32 exclude_Id
= iter
->second
;
12770 // skip checked quest id, only state of other quests in group is interesting
12771 if(exclude_Id
== prevId
)
12774 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12776 // alternative quest from group also must be active
12777 if( i_exstatus
== mQuestStatus
.end() ||
12778 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12779 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12782 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12791 // Has only positive prev. quests in non-rewarded state
12792 // and negative prev. quests in non-active state
12794 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12799 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12801 uint32 reqraces
= qInfo
->GetRequiredRaces();
12802 if ( reqraces
== 0 )
12804 if( (reqraces
& getRaceMask()) == 0 )
12807 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12813 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12815 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12816 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12819 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12823 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12824 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12827 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12834 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12836 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12837 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12840 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12846 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12848 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12851 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12857 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12859 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12860 if(qInfo
->GetExclusiveGroup() <= 0)
12863 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12864 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12866 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12868 for(; iter
!= end
; ++iter
)
12870 uint32 exclude_Id
= iter
->second
;
12872 // skip checked quest id, only state of other quests in group is interesting
12873 if(exclude_Id
== qInfo
->GetQuestId())
12876 // not allow have daily quest if daily quest from exclusive group already recently completed
12877 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12878 if( !SatisfyQuestDay(Nquest
, false) )
12881 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12885 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12887 // alternative quest already started or completed
12888 if( i_exstatus
!= mQuestStatus
.end()
12889 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12892 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12899 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12901 if(!qInfo
->GetNextQuestInChain())
12904 // next quest in chain already started or completed
12905 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12906 if( itr
!= mQuestStatus
.end()
12907 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12910 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12914 // check for all quests further up the chain
12915 // only necessary if there are quest chains with more than one quest that can be skipped
12916 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12920 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12922 // No previous quest in chain
12923 if( qInfo
->prevChainQuests
.empty())
12926 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12928 uint32 prevId
= *iter
;
12930 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12932 if( i_prevstatus
!= mQuestStatus
.end() )
12934 // If any of the previous quests in chain active, return false
12935 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12936 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12939 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12944 // check for all quests further down the chain
12945 // only necessary if there are quest chains with more than one quest that can be skipped
12946 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12950 // No previous quest in chain active
12954 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12956 if(!qInfo
->IsDaily())
12959 bool have_slot
= false;
12960 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12962 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12963 if(qInfo
->GetQuestId()==id
)
12973 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12980 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12982 uint32 srcitem
= pQuest
->GetSrcItemId();
12985 uint32 count
= pQuest
->GetSrcItemCount();
12989 ItemPosCountVec dest
;
12990 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12991 if( msg
== EQUIP_ERR_OK
)
12993 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12994 SendNewItem(item
, count
, true, false);
12997 // player already have max amount required item, just report success
12998 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13001 SendEquipError( msg
, NULL
, NULL
);
13008 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13010 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13013 uint32 srcitem
= qInfo
->GetSrcItemId();
13016 uint32 count
= qInfo
->GetSrcItemCount();
13020 // exist one case when destroy source quest item not possible:
13021 // non un-equippable item (equipped non-empty bag, for example)
13022 uint8 res
= CanUnequipItems(srcitem
,count
);
13023 if(res
!= EQUIP_ERR_OK
)
13026 SendEquipError( res
, NULL
, NULL
);
13030 DestroyItemCount(srcitem
, count
, true, true);
13036 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13038 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13041 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13042 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13043 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13044 && !qInfo
->IsRepeatable() )
13045 return itr
->second
.m_rewarded
;
13052 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13056 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13057 if( itr
!= mQuestStatus
.end() )
13058 return itr
->second
.m_status
;
13060 return QUEST_STATUS_NONE
;
13063 bool Player::CanShareQuest(uint32 quest_id
) const
13065 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13066 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13068 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13069 if( itr
!= mQuestStatus
.end() )
13070 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13075 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13077 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13080 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13082 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13083 m_timedquests
.erase(qInfo
->GetQuestId());
13086 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13088 q_status
.m_status
= status
;
13089 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13092 UpdateForQuestsGO();
13095 // not used in MaNGOS, but used in scripting code
13096 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13098 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13102 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13103 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13104 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13109 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
13111 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13113 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
13115 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13116 if( reqitemcount
!= 0 )
13118 uint32 quest_id
= pQuest
->GetQuestId();
13119 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13121 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13122 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13123 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13129 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13131 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13132 if ( GetQuestSlotQuestId(i
) == quest_id
)
13135 return MAX_QUEST_LOG_SIZE
;
13138 void Player::AreaExploredOrEventHappens( uint32 questId
)
13142 uint16 log_slot
= FindQuestSlot( questId
);
13143 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13145 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13147 if(!q_status
.m_explored
)
13149 q_status
.m_explored
= true;
13150 if (q_status
.uState
!= QUEST_NEW
)
13151 q_status
.uState
= QUEST_CHANGED
;
13154 if( CanCompleteQuest( questId
) )
13155 CompleteQuest( questId
);
13159 //not used in mangosd, function for external script library
13160 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13162 if( Group
*pGroup
= GetGroup() )
13164 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13166 Player
*pGroupGuy
= itr
->getSource();
13168 // for any leave or dead (with not released body) group member at appropriate distance
13169 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13170 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13174 AreaExploredOrEventHappens(questId
);
13177 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13179 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13181 uint32 questid
= GetQuestSlotQuestId(i
);
13182 if ( questid
== 0 )
13185 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13187 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13190 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13191 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13194 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13196 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13197 if ( reqitem
== entry
)
13199 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13200 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13201 if ( curitemcount
< reqitemcount
)
13203 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13204 q_status
.m_itemcount
[j
] += additemcount
;
13205 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13207 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13209 if ( CanCompleteQuest( questid
) )
13210 CompleteQuest( questid
);
13215 UpdateForQuestsGO();
13216 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13219 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13221 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13223 uint32 questid
= GetQuestSlotQuestId(i
);
13226 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13229 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13232 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13234 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13235 if ( reqitem
== entry
)
13237 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13239 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13240 uint32 curitemcount
;
13241 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13242 curitemcount
= q_status
.m_itemcount
[j
];
13244 curitemcount
= GetItemCount(entry
,true);
13245 if ( curitemcount
< reqitemcount
+ count
)
13247 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13248 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13249 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13251 IncompleteQuest( questid
);
13257 UpdateForQuestsGO();
13260 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13262 uint32 addkillcount
= 1;
13263 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13264 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13266 uint32 questid
= GetQuestSlotQuestId(i
);
13270 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13273 // just if !ingroup || !noraidgroup || raidgroup
13274 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13275 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13277 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13279 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13281 // skip GO activate objective or none
13282 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13285 // skip Cast at creature objective
13286 if(qInfo
->ReqSpell
[j
] !=0 )
13289 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13291 if ( reqkill
== entry
)
13293 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13294 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13295 if ( curkillcount
< reqkillcount
)
13297 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13298 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13300 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13302 if ( CanCompleteQuest( questid
) )
13303 CompleteQuest( questid
);
13305 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13314 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13316 bool isCreature
= IS_CREATURE_GUID(guid
);
13318 uint32 addCastCount
= 1;
13319 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13321 uint32 questid
= GetQuestSlotQuestId(i
);
13325 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13329 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13331 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13333 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13335 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13337 // skip kill creature objective (0) or wrong spell casts
13338 if(qInfo
->ReqSpell
[j
] != spell_id
)
13341 uint32 reqTarget
= 0;
13345 // creature activate objectives
13346 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13347 // checked at quest_template loading
13348 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13352 // GO activate objective
13353 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13354 // checked at quest_template loading
13355 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13358 // other not this creature/GO related objectives
13359 if( reqTarget
!= entry
)
13362 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13363 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13364 if ( curCastCount
< reqCastCount
)
13366 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13367 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13369 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13372 if ( CanCompleteQuest( questid
) )
13373 CompleteQuest( questid
);
13375 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13383 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13385 uint32 addTalkCount
= 1;
13386 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13388 uint32 questid
= GetQuestSlotQuestId(i
);
13392 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13396 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13398 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13400 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13402 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13404 // skip spell casts and Gameobject objectives
13405 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13408 uint32 reqTarget
= 0;
13410 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13411 // checked at quest_template loading
13412 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13416 if ( reqTarget
== entry
)
13418 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13419 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13420 if ( curTalkCount
< reqTalkCount
)
13422 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13423 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13425 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13427 if ( CanCompleteQuest( questid
) )
13428 CompleteQuest( questid
);
13430 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13439 void Player::MoneyChanged( uint32 count
)
13441 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13443 uint32 questid
= GetQuestSlotQuestId(i
);
13447 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13448 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13450 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13452 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13454 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13456 if ( CanCompleteQuest( questid
) )
13457 CompleteQuest( questid
);
13460 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13462 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13463 IncompleteQuest( questid
);
13469 bool Player::HasQuestForItem( uint32 itemid
) const
13471 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13473 QuestStatusData
const& q_status
= i
->second
;
13475 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13477 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13481 // hide quest if player is in raid-group and quest is no raid quest
13482 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13485 // There should be no mixed ReqItem/ReqSource drop
13486 // This part for ReqItem drop
13487 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13489 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13492 // This part - for ReqSource
13493 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13495 // examined item is a source item
13496 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13498 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13500 // total count of created ReqItems and SourceItems is less than ReqItemCount
13501 if(qinfo
->ReqItemId
[idx
] != 0 &&
13502 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13505 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13506 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13508 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13511 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13512 else if(qinfo
->ReqSpell
[idx
] != 0)
13514 // not casted and need more reagents/item for use.
13515 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13525 void Player::SendQuestComplete( uint32 quest_id
)
13529 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13530 data
<< uint32(quest_id
);
13531 GetSession()->SendPacket( &data
);
13532 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13536 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13538 uint32 questid
= pQuest
->GetQuestId();
13539 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13540 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13541 data
<< uint32(questid
);
13543 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13545 data
<< uint32(XP
);
13546 data
<< uint32(pQuest
->GetRewOrReqMoney());
13551 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13554 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13555 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13556 GetSession()->SendPacket( &data
);
13558 if (pQuest
->GetQuestCompleteScript() != 0)
13559 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13562 void Player::SendQuestFailed( uint32 quest_id
)
13566 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13568 data
<< uint32(0); // failed reason (4 for inventory is full)
13569 GetSession()->SendPacket( &data
);
13570 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13574 void Player::SendQuestTimerFailed( uint32 quest_id
)
13578 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13580 GetSession()->SendPacket( &data
);
13581 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13585 void Player::SendCanTakeQuestResponse( uint32 msg
)
13587 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13588 data
<< uint32(msg
);
13589 GetSession()->SendPacket( &data
);
13590 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13593 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13597 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13598 data
<< uint64(pPlayer
->GetGUID());
13599 data
<< uint8(msg
); // valid values: 0-8
13600 GetSession()->SendPacket( &data
);
13601 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13605 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13607 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13608 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13609 //data << pQuest->ReqItemId[item_idx];
13611 GetSession()->SendPacket( &data
);
13614 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13616 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13618 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13620 // client expected gameobject template id in form (id|0x80000000)
13621 entry
= (-entry
) | 0x80000000;
13623 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13624 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13625 data
<< uint32(pQuest
->GetQuestId());
13626 data
<< uint32(entry
);
13627 data
<< uint32(old_count
+ add_count
);
13628 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13629 data
<< uint64(guid
);
13630 GetSession()->SendPacket(&data
);
13632 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13633 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13634 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13637 /*********************************************************/
13638 /*** LOAD SYSTEM ***/
13639 /*********************************************************/
13641 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13643 bool delete_result
= true;
13646 // 0 1 2 3 4 5 6 7 8 9
13647 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13648 if(!result
) return false;
13650 else delete_result
= false;
13652 Field
*fields
= result
->Fetch();
13654 if(!LoadValues( fields
[1].GetString()))
13656 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13657 if(delete_result
) delete result
;
13661 // overwrite possible wrong/corrupted guid
13662 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13664 m_name
= fields
[2].GetCppString();
13666 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13667 SetMapId(fields
[6].GetUInt32());
13668 // the instance id is not needed at character enum
13670 m_Played_time
[0] = fields
[7].GetUInt32();
13671 m_Played_time
[1] = fields
[8].GetUInt32();
13673 m_atLoginFlags
= fields
[9].GetUInt32();
13675 // I don't see these used anywhere ..
13678 _LoadBoundInstances();*/
13680 if (delete_result
) delete result
;
13682 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13685 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13686 m_deathState
= DEAD
;
13691 void Player::_LoadDeclinedNames(QueryResult
* result
)
13697 delete m_declinedname
;
13699 m_declinedname
= new DeclinedName
;
13700 Field
*fields
= result
->Fetch();
13701 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13702 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13707 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13709 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13713 Field
*fields
= result
->Fetch();
13715 x
= fields
[0].GetFloat();
13716 y
= fields
[1].GetFloat();
13717 z
= fields
[2].GetFloat();
13718 o
= fields
[3].GetFloat();
13719 mapid
= fields
[4].GetUInt32();
13720 in_flight
= !fields
[5].GetCppString().empty();
13726 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13728 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13732 Field
*fields
= result
->Fetch();
13734 data
= StrSplit(fields
[0].GetCppString(), " ");
13741 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13743 if(index
>= data
.size())
13746 return (uint32
)atoi(data
[index
].c_str());
13749 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13752 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13753 memcpy(&result
, &temp
, sizeof(result
));
13758 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13761 if(!LoadValuesArrayFromDB(data
,guid
))
13764 return GetUInt32ValueFromArray(data
,index
);
13767 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13770 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13771 memcpy(&result
, &temp
, sizeof(result
));
13776 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13778 //// 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
13779 //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);
13780 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13784 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13788 Field
*fields
= result
->Fetch();
13790 uint32 dbAccountId
= fields
[1].GetUInt32();
13792 // check if the character's account in the db and the logged in account match.
13793 // player should be able to load/delete character only with correct account!
13794 if( dbAccountId
!= GetSession()->GetAccountId() )
13796 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13801 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13803 m_name
= fields
[3].GetCppString();
13805 // check name limitations
13806 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13809 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13813 if(!LoadValues( fields
[2].GetString()))
13815 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13820 // overwrite possible wrong/corrupted guid
13821 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13823 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13824 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13826 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13827 SetVisibleItemSlot(slot
,NULL
);
13831 delete m_items
[slot
];
13832 m_items
[slot
] = NULL
;
13836 // update money limits
13837 if(GetMoney() > MAX_MONEY_AMOUNT
)
13838 SetMoney(MAX_MONEY_AMOUNT
);
13840 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13843 m_race
= fields
[4].GetUInt8();
13844 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13845 //Other way is to saves m_team into characters table.
13846 setFactionForRace(m_race
);
13849 m_class
= fields
[5].GetUInt8();
13851 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
13854 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
13859 InitPrimaryProffesions(); // to max set before any spell loaded
13861 uint32 transGUID
= fields
[24].GetUInt32();
13862 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13863 SetMapId(fields
[9].GetUInt32());
13864 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13866 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13868 // check arena teams integrity
13869 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13871 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13875 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13876 if(at
->HaveMember(GetGUID()))
13879 // arena team not exist or not member, cleanup fields
13880 for(int j
=0; j
< 6; ++j
)
13881 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13884 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13886 if(!IsPositionValid())
13888 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());
13890 SetMapId(info
->mapId
);
13891 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13895 m_movementInfo
.t_x
= 0.0f
;
13896 m_movementInfo
.t_y
= 0.0f
;
13897 m_movementInfo
.t_z
= 0.0f
;
13898 m_movementInfo
.t_o
= 0.0f
;
13901 // load the player's map here if it's not already loaded
13902 Map
*map
= GetMap();
13903 // since the player may not be bound to the map yet, make sure subsequent
13904 // getmap calls won't create new maps
13905 SetInstanceId(map
->GetInstanceId());
13907 SaveRecallPosition();
13909 if (transGUID
!= 0)
13911 m_movementInfo
.t_x
= fields
[20].GetFloat();
13912 m_movementInfo
.t_y
= fields
[21].GetFloat();
13913 m_movementInfo
.t_z
= fields
[22].GetFloat();
13914 m_movementInfo
.t_o
= fields
[23].GetFloat();
13916 if( !MaNGOS::IsValidMapCoord(
13917 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13918 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13919 // transport size limited
13920 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13922 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13923 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13924 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13926 SetMapId(info
->mapId
);
13927 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13929 m_movementInfo
.t_x
= 0.0f
;
13930 m_movementInfo
.t_y
= 0.0f
;
13931 m_movementInfo
.t_z
= 0.0f
;
13932 m_movementInfo
.t_o
= 0.0f
;
13938 if (transGUID
!= 0)
13940 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13942 if( (*iter
)->GetGUIDLow() == transGUID
)
13944 m_transport
= *iter
;
13945 m_transport
->AddPassenger(this);
13946 SetMapId(m_transport
->GetMapId());
13953 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13956 SetMapId(info
->mapId
);
13957 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13959 m_movementInfo
.t_x
= 0.0f
;
13960 m_movementInfo
.t_y
= 0.0f
;
13961 m_movementInfo
.t_z
= 0.0f
;
13962 m_movementInfo
.t_o
= 0.0f
;
13968 time_t now
= time(NULL
);
13969 time_t logoutTime
= time_t(fields
[16].GetUInt64());
13971 // since last logout (in seconds)
13972 uint64 time_diff
= uint64(now
- logoutTime
);
13974 // set value, including drunk invisibility detection
13975 // calculate sobering. after 15 minutes logged out, the player will be sober again
13977 if(time_diff
> 15*MINUTE
)
13980 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
13981 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
13982 SetDrunkValue(newDrunkenValue
);
13984 m_rest_bonus
= fields
[15].GetFloat();
13985 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13986 float bubble0
= 0.031;
13987 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13988 float bubble1
= 0.125;
13990 if((int32
)fields
[16].GetUInt32() > 0)
13992 float bubble
= fields
[17].GetUInt32() > 0
13993 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
13994 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
13996 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
13999 m_cinematic
= fields
[12].GetUInt32();
14000 m_Played_time
[0]= fields
[13].GetUInt32();
14001 m_Played_time
[1]= fields
[14].GetUInt32();
14003 m_resetTalentsCost
= fields
[18].GetUInt32();
14004 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14006 // reserve some flags
14007 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14009 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14010 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14012 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14014 uint32 extraflags
= fields
[25].GetUInt32();
14016 m_stableSlots
= fields
[26].GetUInt32();
14017 if(m_stableSlots
> 4)
14019 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14023 m_atLoginFlags
= fields
[27].GetUInt32();
14026 // Update Honor kills data
14027 m_lastHonorUpdateTime
= logoutTime
;
14028 UpdateHonorFields();
14030 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14031 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14032 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14034 std::string taxi_nodes
= fields
[31].GetCppString();
14038 // clear channel spell data (if saved at channel spell casting)
14039 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14040 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14042 // clear charm/summon related fields
14045 SetCharmerGUID(NULL
);
14046 SetOwnerGUID(NULL
);
14047 SetCreatorGUID(NULL
);
14049 // reset some aura modifiers before aura apply
14051 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14052 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14054 // reset skill modifiers and set correct unlearn flags
14055 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
14057 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
14059 // set correct unlearn bit
14060 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
14063 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
14064 if(!pSkill
) continue;
14066 // enable unlearn button for primary professions only
14067 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
14068 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
14070 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
14073 // make sure the unit is considered out of combat for proper loading
14076 // make sure the unit is considered not in duel for proper loading
14077 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14078 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14080 // remember loaded power/health values to restore after stats initialization and modifier applying
14081 uint32 savedHealth
= GetHealth();
14082 uint32 savedPower
[MAX_POWERS
];
14083 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14084 savedPower
[i
] = GetPower(Powers(i
));
14086 // reset stats before loading any modifiers
14087 InitStatsForLevel();
14088 InitTaxiNodesForLevel();
14089 InitGlyphsForLevel();
14092 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14094 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14097 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14099 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14100 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14101 m_deathState
= DEAD
;
14103 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14105 // after spell load
14106 InitTalentForLevel();
14107 learnSkillRewardedSpells();
14109 // after spell load, learn rewarded spell if need also
14110 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14111 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14113 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14115 // must be before inventory (some items required reputation check)
14116 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14118 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14120 // update items with duration and realtime
14121 UpdateItemDuration(time_diff
, true);
14123 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14125 // unread mails and next delivery time, actual mails not loaded
14126 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14128 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14130 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14133 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14134 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14135 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14137 if(!HasTitle(curTitle
))
14138 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14141 // Not finish taxi flight path
14142 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
))
14144 // problems with taxi path loading
14145 TaxiNodesEntry
const* nodeEntry
= NULL
;
14146 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14147 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14149 if(!nodeEntry
) // don't know taxi start node, to homebind
14151 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14152 SetMapId(m_homebindMapId
);
14153 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
14154 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14156 else // have start node, to it
14158 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14159 SetMapId(nodeEntry
->map_id
);
14160 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14161 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14163 m_taxi
.ClearTaxiDestinations();
14165 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14167 // save source node as recall coord to prevent recall and fall from sky
14168 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14169 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14170 m_recallMap
= nodeEntry
->map_id
;
14171 m_recallX
= nodeEntry
->x
;
14172 m_recallY
= nodeEntry
->y
;
14173 m_recallZ
= nodeEntry
->z
;
14175 // flight will started later
14178 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14180 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14181 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14183 RemoveAllAurasOnDeath();
14185 //apply all stat bonuses from items and auras
14186 SetCanModifyStats(true);
14189 // restore remembered power/health values (but not more max values)
14190 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14191 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14192 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14194 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14198 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14200 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14203 case 0: break; // disable
14204 case 1: SetGameMaster(true); break; // enable
14205 case 2: // save state
14206 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14207 SetGameMaster(true);
14211 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14214 case 0: break; // disable
14215 case 1: SetAcceptTicket(true); break; // enable
14216 case 2: // save state
14217 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14218 SetAcceptTicket(true);
14222 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14225 case 0: break; // disable
14226 case 1: SetGMChat(true); break; // enable
14227 case 2: // save state
14228 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14233 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14236 case 0: break; // disable
14237 case 1: SetAcceptWhispers(true); break; // enable
14238 case 2: // save state
14239 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14240 SetAcceptWhispers(true);
14245 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14247 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14248 m_achievementMgr
.CheckAllAchievementCriteria();
14252 bool Player::isAllowedToLoot(Creature
* creature
)
14254 if(Player
* recipient
= creature
->GetLootRecipient())
14256 if (recipient
== this)
14258 if( Group
* otherGroup
= recipient
->GetGroup())
14260 Group
* thisGroup
= GetGroup();
14263 return thisGroup
== otherGroup
;
14268 // prevent other players from looting if the recipient got disconnected
14269 return !creature
->hasLootRecipient();
14272 void Player::_LoadActions(QueryResult
*result
)
14274 m_actionButtons
.clear();
14276 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14282 Field
*fields
= result
->Fetch();
14284 uint8 button
= fields
[0].GetUInt8();
14286 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
14288 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14290 while( result
->NextRow() );
14296 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14299 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14300 m_modAuras
[i
].clear();
14302 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14308 Field
*fields
= result
->Fetch();
14309 uint64 caster_guid
= fields
[0].GetUInt64();
14310 uint32 spellid
= fields
[1].GetUInt32();
14311 uint32 effindex
= fields
[2].GetUInt32();
14312 uint32 stackcount
= fields
[3].GetUInt32();
14313 int32 damage
= (int32
)fields
[4].GetUInt32();
14314 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14315 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14316 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14318 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14321 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14327 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14331 // negative effects should continue counting down after logout
14332 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14334 if(remaintime
<= int32(timediff
))
14337 remaintime
-= timediff
;
14340 // prevent wrong values of remaincharges
14341 if(spellproto
->procCharges
)
14343 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14344 remaincharges
= spellproto
->procCharges
;
14349 //do not load single target auras (unless they were cast by the player)
14350 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14353 for(uint32 i
=0; i
<stackcount
; i
++)
14355 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14357 damage
= aura
->GetModifier()->m_amount
;
14358 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14360 sLog
.outString("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14363 while( result
->NextRow() );
14368 if(m_class
== CLASS_WARRIOR
)
14369 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14372 void Player::LoadCorpse()
14376 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14380 if(Corpse
*corpse
= GetCorpse())
14382 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14386 //Prevent Dead Player login without corpse
14387 ResurrectPlayer(0.5f
);
14392 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14394 //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());
14395 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14396 //NOTE: the "order by `bag`" is important because it makes sure
14397 //the bagMap is filled before items in the bags are loaded
14398 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14399 //expected to be equipped before offhand items (TODO: fixme)
14401 uint32 zone
= GetZoneId();
14405 std::list
<Item
*> problematicItems
;
14407 // prevent items from being added to the queue when stored
14408 m_itemUpdateQueueBlocked
= true;
14411 Field
*fields
= result
->Fetch();
14412 uint32 bag_guid
= fields
[1].GetUInt32();
14413 uint8 slot
= fields
[2].GetUInt8();
14414 uint32 item_guid
= fields
[3].GetUInt32();
14415 uint32 item_id
= fields
[4].GetUInt32();
14417 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14421 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14422 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14423 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14427 Item
*item
= NewItemOrBag(proto
);
14429 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14431 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14432 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14433 item
->FSetState(ITEM_REMOVED
);
14434 item
->SaveToDB(); // it also deletes item object !
14438 // not allow have in alive state item limited to another map/zone
14439 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14441 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14442 item
->FSetState(ITEM_REMOVED
);
14443 item
->SaveToDB(); // it also deletes item object !
14447 // "Conjured items disappear if you are logged out for more than 15 minutes"
14448 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14450 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14451 item
->FSetState(ITEM_REMOVED
);
14452 item
->SaveToDB(); // it also deletes item object !
14456 bool success
= true;
14460 // the item is not in a bag
14461 item
->SetContainer( NULL
);
14462 item
->SetSlot(slot
);
14464 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14466 ItemPosCountVec dest
;
14467 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14468 item
= StoreItem(dest
, item
, true);
14472 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14475 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14476 QuickEquipItem(dest
, item
);
14480 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14482 ItemPosCountVec dest
;
14483 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14484 item
= BankItem(dest
, item
, true);
14491 // store bags that may contain items in them
14492 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14493 bagMap
[item_guid
] = (Bag
*)item
;
14498 item
->SetSlot(NULL_SLOT
);
14499 // the item is in a bag, find the bag
14500 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14501 if(itr
!= bagMap
.end())
14502 itr
->second
->StoreItem(slot
, item
, true );
14507 // item's state may have changed after stored
14509 item
->SetState(ITEM_UNCHANGED
, this);
14512 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
);
14513 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14514 problematicItems
.push_back(item
);
14516 } while (result
->NextRow());
14519 m_itemUpdateQueueBlocked
= false;
14521 // send by mail problematic items
14522 while(!problematicItems
.empty())
14525 MailItemsInfo mi
; // item list preparing
14527 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14529 Item
* item
= problematicItems
.front();
14530 problematicItems
.pop_front();
14532 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14535 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14537 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14541 _ApplyAllItemMods();
14544 // load mailed item which should receive current player
14545 void Player::_LoadMailedItems(Mail
*mail
)
14547 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail
->messageID
);
14553 Field
*fields
= result
->Fetch();
14554 uint32 item_guid_low
= fields
[0].GetUInt32();
14555 uint32 item_template
= fields
[1].GetUInt32();
14557 mail
->AddItem(item_guid_low
, item_template
);
14559 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14563 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
);
14564 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14565 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14569 Item
*item
= NewItemOrBag(proto
);
14571 if(!item
->LoadFromDB(item_guid_low
, 0))
14573 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14574 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14575 item
->FSetState(ITEM_REMOVED
);
14576 item
->SaveToDB(); // it also deletes item object !
14581 } while (result
->NextRow());
14586 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14588 //set a count of unread mails
14589 //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);
14592 Field
*fieldMail
= resultUnread
->Fetch();
14593 unReadMails
= fieldMail
[0].GetUInt8();
14594 delete resultUnread
;
14597 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14598 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14599 if (resultDelivery
)
14601 Field
*fieldMail
= resultDelivery
->Fetch();
14602 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14603 delete resultDelivery
;
14607 void Player::_LoadMail()
14610 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14611 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());
14616 Field
*fields
= result
->Fetch();
14617 Mail
*m
= new Mail
;
14618 m
->messageID
= fields
[0].GetUInt32();
14619 m
->messageType
= fields
[1].GetUInt8();
14620 m
->sender
= fields
[2].GetUInt32();
14621 m
->receiver
= fields
[3].GetUInt32();
14622 m
->subject
= fields
[4].GetCppString();
14623 m
->itemTextId
= fields
[5].GetUInt32();
14624 bool has_items
= fields
[6].GetBool();
14625 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14626 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14627 m
->money
= fields
[9].GetUInt32();
14628 m
->COD
= fields
[10].GetUInt32();
14629 m
->checked
= fields
[11].GetUInt32();
14630 m
->stationery
= fields
[12].GetUInt8();
14631 m
->mailTemplateId
= fields
[13].GetInt16();
14633 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14635 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14636 m
->mailTemplateId
= 0;
14639 m
->state
= MAIL_STATE_UNCHANGED
;
14642 _LoadMailedItems(m
);
14644 m_mail
.push_back(m
);
14645 } while( result
->NextRow() );
14648 m_mailsLoaded
= true;
14651 void Player::LoadPet()
14653 //fixme: the pet should still be loaded if the player is not in world
14654 // just not added to the map
14657 Pet
*pet
= new Pet
;
14658 if(!pet
->LoadPetFromDB(this,0,0,true))
14663 void Player::_LoadQuestStatus(QueryResult
*result
)
14665 mQuestStatus
.clear();
14669 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14670 //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());
14676 Field
*fields
= result
->Fetch();
14678 uint32 quest_id
= fields
[0].GetUInt32();
14679 // used to be new, no delete?
14680 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14684 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14686 uint32 qstatus
= fields
[1].GetUInt32();
14687 if(qstatus
< MAX_QUEST_STATUS
)
14688 questStatusData
.m_status
= QuestStatus(qstatus
);
14691 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14692 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14695 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14696 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14698 time_t quest_time
= time_t(fields
[4].GetUInt64());
14700 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14702 AddTimedQuest( quest_id
);
14704 if (quest_time
<= sWorld
.GetGameTime())
14705 questStatusData
.m_timer
= 1;
14707 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14712 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14713 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14714 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14715 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14716 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14717 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14718 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14719 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14721 questStatusData
.uState
= QUEST_UNCHANGED
;
14723 // add to quest log
14724 if( slot
< MAX_QUEST_LOG_SIZE
&&
14725 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14726 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14727 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14729 SetQuestSlot(slot
,quest_id
,quest_time
);
14731 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14732 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14734 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14735 if(questStatusData
.m_creatureOrGOcount
[idx
])
14736 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14741 if(questStatusData
.m_rewarded
)
14743 // learn rewarded spell if unknown
14744 learnQuestRewardedSpells(pQuest
);
14746 // set rewarded title if any
14747 if(pQuest
->GetCharTitleId())
14749 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14750 SetTitle(titleEntry
);
14754 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14757 while( result
->NextRow() );
14762 // clear quest log tail
14763 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14767 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14769 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14770 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14772 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14776 uint32 quest_daily_idx
= 0;
14780 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14782 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14786 Field
*fields
= result
->Fetch();
14788 uint32 quest_id
= fields
[0].GetUInt32();
14790 // save _any_ from daily quest times (it must be after last reset anyway)
14791 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14793 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14797 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14800 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14802 while( result
->NextRow() );
14807 m_DailyQuestChanged
= false;
14810 void Player::_LoadReputation(QueryResult
*result
)
14812 m_factions
.clear();
14814 // Set initial reputations (so everything is nifty before DB data load)
14815 SetInitialFactions();
14817 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14823 Field
*fields
= result
->Fetch();
14825 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
14826 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
14828 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
14830 // update standing to current
14831 faction
->Standing
= int32(fields
[1].GetUInt32());
14833 uint32 dbFactionFlags
= fields
[2].GetUInt32();
14835 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
14836 SetFactionVisible(faction
); // have internal checks for forced invisibility
14838 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
14839 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
14841 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
14842 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14843 else // DB not at war
14845 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14846 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
14847 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14850 // set atWar for hostile
14851 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
14852 SetFactionAtWar(faction
,true);
14854 // reset changed flag if values similar to saved in DB
14855 if(faction
->Flags
==dbFactionFlags
)
14856 faction
->Changed
= false;
14859 while( result
->NextRow() );
14865 void Player::_LoadSpells(QueryResult
*result
)
14867 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
14868 delete itr
->second
;
14871 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14877 Field
*fields
= result
->Fetch();
14879 addSpell(fields
[0].GetUInt16(), fields
[2].GetBool(), false, true, fields
[1].GetUInt16(), fields
[3].GetBool());
14881 while( result
->NextRow() );
14887 void Player::_LoadTutorials(QueryResult
*result
)
14889 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14895 Field
*fields
= result
->Fetch();
14897 for (int iI
=0; iI
<8; iI
++)
14898 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14900 while( result
->NextRow() );
14905 m_TutorialsChanged
= false;
14908 void Player::_LoadGroup(QueryResult
*result
)
14910 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14913 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14915 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14918 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14919 SetGroup(group
, subgroup
);
14920 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14922 // the group leader may change the instance difficulty while the player is offline
14923 SetDifficulty(group
->GetDifficulty());
14929 void Player::_LoadBoundInstances(QueryResult
*result
)
14931 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14932 m_boundInstances
[i
].clear();
14934 Group
*group
= GetGroup();
14936 //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));
14941 Field
*fields
= result
->Fetch();
14942 bool perm
= fields
[1].GetBool();
14943 uint32 mapId
= fields
[2].GetUInt32();
14944 uint32 instanceId
= fields
[0].GetUInt32();
14945 uint8 difficulty
= fields
[3].GetUInt8();
14946 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14947 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14948 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14949 // and in that case it is not used
14953 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
);
14954 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14958 // since non permanent binds are always solo bind, they can always be reset
14959 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
14960 if(save
) BindToInstance(save
, perm
, true);
14961 } while(result
->NextRow());
14966 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
14968 // some instances only have one difficulty
14969 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
14970 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
14972 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14973 if(itr
!= m_boundInstances
[difficulty
].end())
14974 return &itr
->second
;
14979 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
14981 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14982 UnbindInstance(itr
, difficulty
, unload
);
14985 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
14987 if(itr
!= m_boundInstances
[difficulty
].end())
14989 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
14990 itr
->second
.save
->RemovePlayer(this); // save can become invalid
14991 m_boundInstances
[difficulty
].erase(itr
++);
14995 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
14999 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15002 // update the save when the group kills a boss
15003 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15004 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());
15007 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15009 if(bind
.save
!= save
)
15011 if(bind
.save
) bind
.save
->RemovePlayer(this);
15012 save
->AddPlayer(this);
15015 if(permanent
) save
->SetCanReset(false);
15018 bind
.perm
= permanent
;
15019 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());
15026 void Player::SendRaidInfo()
15028 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15030 uint32 counter
= 0, i
;
15031 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15032 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
15033 if(itr
->second
.perm
) counter
++;
15036 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15038 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
15040 if(itr
->second
.perm
)
15042 InstanceSave
*save
= itr
->second
.save
;
15043 data
<< (save
->GetMapId());
15044 data
<< (uint32
)(save
->GetResetTime() - time(NULL
));
15045 data
<< save
->GetInstanceId();
15046 data
<< uint32(counter
);
15051 GetSession()->SendPacket(&data
);
15055 - called on every successful teleportation to a map
15057 void Player::SendSavedInstances()
15059 bool hasBeenSaved
= false;
15062 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15064 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15066 if(itr
->second
.perm
) // only permanent binds are sent
15068 hasBeenSaved
= true;
15074 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15075 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15076 data
<< uint32(hasBeenSaved
);
15077 GetSession()->SendPacket(&data
);
15082 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15084 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15086 if(itr
->second
.perm
)
15088 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15089 data
<< uint32(itr
->second
.save
->GetMapId());
15090 GetSession()->SendPacket(&data
);
15096 /// convert the player's binds to the group
15097 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15099 bool has_binds
= false;
15100 bool has_solo
= false;
15102 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15103 assert(player_guid
);
15105 // copy all binds to the group, when changing leader it's assumed the character
15106 // will not have any solo binds
15110 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15112 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15115 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15116 // permanent binds are not removed
15117 if(!itr
->second
.perm
)
15119 player
->UnbindInstance(itr
, i
, true); // increments itr
15128 // if the player's not online we don't know what binds it has
15129 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
));
15130 // the following should not get executed when changing leaders
15131 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15134 bool Player::_LoadHomeBind(QueryResult
*result
)
15137 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15140 Field
*fields
= result
->Fetch();
15141 m_homebindMapId
= fields
[0].GetUInt32();
15142 m_homebindZoneId
= fields
[1].GetUInt16();
15143 m_homebindX
= fields
[2].GetFloat();
15144 m_homebindY
= fields
[3].GetFloat();
15145 m_homebindZ
= fields
[4].GetFloat();
15148 // accept saved data only for valid position (and non instanceable)
15149 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15150 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
15155 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15160 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15161 if(!info
) return false;
15163 m_homebindMapId
= info
->mapId
;
15164 m_homebindZoneId
= info
->zoneId
;
15165 m_homebindX
= info
->positionX
;
15166 m_homebindY
= info
->positionY
;
15167 m_homebindZ
= info
->positionZ
;
15169 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
);
15172 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15173 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15178 /*********************************************************/
15179 /*** SAVE SYSTEM ***/
15180 /*********************************************************/
15182 void Player::SaveToDB()
15184 // delay auto save at any saves (manual, in code, or autosave)
15185 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15187 // first save/honor gain after midnight will also update the player's honor fields
15188 UpdateHonorFields();
15190 // Must saved before enter into BattleGround
15191 if(InBattleGround())
15194 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15195 //save, far from tavern/city
15196 //save, but in tavern/city
15197 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15200 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15201 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15202 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15203 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15204 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15205 uint32 tmp_displayid
= GetDisplayId();
15207 // Set player sit state to standing on save, also stealth and shifted form
15208 SetByteValue(UNIT_FIELD_BYTES_1
, 0, 0); // stand state
15209 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15210 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0); // stand flags?
15211 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15212 SetDisplayId(GetNativeDisplayId());
15214 bool inworld
= IsInWorld();
15216 CharacterDatabase
.BeginTransaction();
15218 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15220 std::string sql_name
= m_name
;
15221 CharacterDatabase
.escape_string(sql_name
);
15223 std::ostringstream ss
;
15224 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15225 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15226 "taximask, online, cinematic, "
15227 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15228 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15229 "death_expire_time, taxi_path) VALUES ("
15230 << GetGUIDLow() << ", "
15231 << GetSession()->GetAccountId() << ", '"
15232 << sql_name
<< "', "
15234 << m_class
<< ", ";
15236 bool save_to_dest
= false;
15237 if(IsBeingTeleported())
15239 // don't save to battlegrounds or arenas
15240 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
15241 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
15242 save_to_dest
= true;
15247 ss
<< GetMapId() << ", "
15248 << (uint32
)GetDifficulty() << ", "
15249 << finiteAlways(GetPositionX()) << ", "
15250 << finiteAlways(GetPositionY()) << ", "
15251 << finiteAlways(GetPositionZ()) << ", "
15252 << finiteAlways(GetOrientation()) << ", '";
15256 ss
<< GetTeleportDest().mapid
<< ", "
15257 << (uint32
)GetDifficulty() << ", "
15258 << finiteAlways(GetTeleportDest().x
) << ", "
15259 << finiteAlways(GetTeleportDest().y
) << ", "
15260 << finiteAlways(GetTeleportDest().z
) << ", "
15261 << finiteAlways(GetTeleportDest().o
) << ", '";
15265 for( i
= 0; i
< m_valuesCount
; i
++ )
15267 ss
<< GetUInt32Value(i
) << " ";
15272 for( i
= 0; i
< 8; i
++ )
15273 ss
<< m_taxi
.GetTaximask(i
) << " ";
15276 ss
<< (inworld
? 1 : 0);
15282 ss
<< m_Played_time
[0];
15284 ss
<< m_Played_time
[1];
15287 ss
<< finiteAlways(m_rest_bonus
);
15289 ss
<< (uint64
)time(NULL
);
15291 ss
<< is_save_resting
;
15293 ss
<< m_resetTalentsCost
;
15295 ss
<< (uint64
)m_resetTalentsTime
;
15298 ss
<< finiteAlways(m_movementInfo
.t_x
);
15300 ss
<< finiteAlways(m_movementInfo
.t_y
);
15302 ss
<< finiteAlways(m_movementInfo
.t_z
);
15304 ss
<< finiteAlways(m_movementInfo
.t_o
);
15307 ss
<< m_transport
->GetGUIDLow();
15312 ss
<< m_ExtraFlags
;
15315 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15318 ss
<< uint32(m_atLoginFlags
);
15324 ss
<< (uint64
)m_deathExpireTime
;
15327 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15330 CharacterDatabase
.Execute( ss
.str().c_str() );
15332 if(m_mailsUpdated
) //save mails only when needed
15336 _SaveQuestStatus();
15337 _SaveDailyQuestStatus();
15340 _SaveSpellCooldowns();
15345 CharacterDatabase
.CommitTransaction();
15347 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15348 SetDisplayId(tmp_displayid
);
15349 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15350 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15351 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15352 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15354 // save pet (hunter pet level and experience and all type pets health/mana).
15355 if(Pet
* pet
= GetPet())
15356 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15357 m_achievementMgr
.SaveToDB();
15360 // fast save function for item/money cheating preventing - save only inventory and money state
15361 void Player::SaveInventoryAndGoldToDB()
15364 //money is in data field
15365 SaveDataFieldToDB();
15368 void Player::_SaveActions()
15370 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15372 switch (itr
->second
.uState
)
15374 case ACTIONBUTTON_NEW
:
15375 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15376 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15377 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15380 case ACTIONBUTTON_CHANGED
:
15381 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15382 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15383 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15386 case ACTIONBUTTON_DELETED
:
15387 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15388 m_actionButtons
.erase(itr
++);
15397 void Player::_SaveAuras()
15399 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15401 AuraMap
const& auras
= GetAuras();
15406 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15407 uint32 stackCounter
= 1;
15409 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15411 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15413 AuraMap::const_iterator itr2
= itr
;
15414 // save previous spellEffectPair to db
15416 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15418 //skip all auras from spells that are passive or need a shapeshift
15419 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15421 //do not save single target auras (unless they were cast by the player)
15422 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15425 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15426 for (i
= 0; i
< 3; i
++)
15427 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15428 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15433 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15434 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15435 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->m_procCharges
));
15440 if(itr
== auras
.end())
15444 if (lastEffectPair
== itr
->first
)
15448 lastEffectPair
= itr
->first
;
15454 void Player::_SaveInventory()
15456 // force items in buyback slots to new state
15457 // and remove those that aren't already
15458 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15460 Item
*item
= m_items
[i
];
15461 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15462 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15463 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15464 m_items
[i
]->FSetState(ITEM_NEW
);
15467 // update enchantment durations
15468 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15470 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15474 if (m_itemUpdateQueue
.empty()) return;
15476 // do not save if the update queue is corrupt
15477 bool error
= false;
15478 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15480 Item
*item
= m_itemUpdateQueue
[i
];
15481 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15482 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15486 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());
15489 else if (test
!= item
)
15491 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());
15498 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15499 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15503 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15505 Item
*item
= m_itemUpdateQueue
[i
];
15506 if(!item
) continue;
15508 Bag
*container
= item
->GetContainer();
15509 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15511 switch(item
->GetState())
15514 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());
15517 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());
15520 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15522 case ITEM_UNCHANGED
:
15526 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15528 m_itemUpdateQueue
.clear();
15531 void Player::_SaveMail()
15533 if (!m_mailsLoaded
)
15536 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
15539 if (m
->state
== MAIL_STATE_CHANGED
)
15541 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'",
15542 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15543 if(m
->removedItems
.size())
15545 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15546 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15547 m
->removedItems
.clear();
15549 m
->state
= MAIL_STATE_UNCHANGED
;
15551 else if (m
->state
== MAIL_STATE_DELETED
)
15554 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15555 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15557 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15558 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15559 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15563 //deallocate deleted mails...
15564 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15566 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15571 itr
= m_mail
.begin();
15577 m_mailsUpdated
= false;
15580 void Player::_SaveQuestStatus()
15582 // we don't need transactions here.
15583 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15585 switch (i
->second
.uState
)
15588 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15589 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15590 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]);
15592 case QUEST_CHANGED
:
15593 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' ",
15594 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
);
15596 case QUEST_UNCHANGED
:
15599 i
->second
.uState
= QUEST_UNCHANGED
;
15603 void Player::_SaveDailyQuestStatus()
15605 if(!m_DailyQuestChanged
)
15608 m_DailyQuestChanged
= false;
15610 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15612 // we don't need transactions here.
15613 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15614 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15615 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15616 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15617 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15620 void Player::_SaveReputation()
15622 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15624 if (itr
->second
.Changed
)
15626 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15627 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
);
15628 itr
->second
.Changed
= false;
15633 void Player::_SaveSpells()
15635 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
15638 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15639 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15640 if (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15641 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);
15643 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15644 _removeSpell(itr
->first
);
15646 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15650 void Player::_SaveTutorials()
15652 if(!m_TutorialsChanged
)
15656 // it's better than rebuilding indexes multiple times
15657 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15660 Rows
= result
->Fetch()[0].GetUInt32();
15666 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'",
15667 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
);
15671 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]);
15674 m_TutorialsChanged
= false;
15677 void Player::outDebugValues() const
15679 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15682 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15683 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15684 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15685 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15686 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15687 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15688 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15689 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15690 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15691 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15692 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15693 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15696 /*********************************************************/
15697 /*** FLOOD FILTER SYSTEM ***/
15698 /*********************************************************/
15700 void Player::UpdateSpeakTime()
15702 // ignore chat spam protection for GMs in any mode
15703 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15706 time_t current
= time (NULL
);
15707 if(m_speakTime
> current
)
15709 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15714 if(m_speakCount
>= max_count
)
15716 // prevent overwrite mute time, if message send just before mutes set, for example.
15717 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15718 if(GetSession()->m_muteTime
< new_mute
)
15719 GetSession()->m_muteTime
= new_mute
;
15727 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15730 bool Player::CanSpeak() const
15732 return GetSession()->m_muteTime
<= time (NULL
);
15735 /*********************************************************/
15736 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15737 /*********************************************************/
15739 void Player::SendAttackSwingNotInRange()
15741 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15742 GetSession()->SendPacket( &data
);
15745 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15747 std::ostringstream ss
;
15748 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15749 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15750 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15751 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15752 sLog
.outDebug(ss
.str().c_str());
15753 CharacterDatabase
.Execute(ss
.str().c_str());
15756 void Player::SaveDataFieldToDB()
15758 std::ostringstream ss
;
15759 ss
<<"UPDATE characters SET data='";
15761 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
15763 ss
<< GetUInt32Value(i
) << " ";
15765 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15767 CharacterDatabase
.Execute(ss
.str().c_str());
15770 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15772 std::ostringstream ss2
;
15773 ss2
<<"UPDATE characters SET data='";
15775 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15777 ss2
<<tokens
[i
]<<" ";
15779 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15781 return CharacterDatabase
.Execute(ss2
.str().c_str());
15784 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15787 snprintf(buf
,11,"%u",value
);
15789 if(index
>= tokens
.size())
15792 tokens
[index
] = buf
;
15795 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15798 if(!LoadValuesArrayFromDB(tokens
,guid
))
15801 if(index
>= tokens
.size())
15805 snprintf(buf
,11,"%u",value
);
15806 tokens
[index
] = buf
;
15808 SaveValuesArrayInDB(tokens
,guid
);
15811 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15814 memcpy(&temp
, &value
, sizeof(value
));
15815 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15818 void Player::SendAttackSwingNotStanding()
15820 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15821 GetSession()->SendPacket( &data
);
15824 void Player::SendAttackSwingDeadTarget()
15826 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15827 GetSession()->SendPacket( &data
);
15830 void Player::SendAttackSwingCantAttack()
15832 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15833 GetSession()->SendPacket( &data
);
15836 void Player::SendAttackSwingCancelAttack()
15838 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15839 GetSession()->SendPacket( &data
);
15842 void Player::SendAttackSwingBadFacingAttack()
15844 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15845 GetSession()->SendPacket( &data
);
15848 void Player::SendAutoRepeatCancel()
15850 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15851 data
.append(GetPackGUID()); // may be it's target guid
15852 GetSession()->SendPacket( &data
);
15855 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
15857 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
15860 GetSession()->SendPacket( &data
);
15862 SendMessageToSet( &data
, true );
15865 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15867 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15869 data
<< Experience
;
15870 GetSession()->SendPacket(&data
);
15873 void Player::SendDungeonDifficulty(bool IsInGroup
)
15875 uint8 val
= 0x00000001;
15876 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15877 data
<< (uint32
)GetDifficulty();
15878 data
<< uint32(val
);
15879 data
<< uint32(IsInGroup
);
15880 GetSession()->SendPacket(&data
);
15883 void Player::SendResetFailedNotify(uint32 mapid
)
15885 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15886 data
<< uint32(mapid
);
15887 GetSession()->SendPacket(&data
);
15890 /// Reset all solo instances and optionally send a message on success for each
15891 void Player::ResetInstances(uint8 method
)
15893 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15895 // we assume that when the difficulty changes, all instances that can be reset will be
15896 uint8 dif
= GetDifficulty();
15898 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15900 InstanceSave
*p
= itr
->second
.save
;
15901 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15902 if(!entry
|| !p
->CanReset())
15908 if(method
== INSTANCE_RESET_ALL
)
15910 // the "reset all instances" method can only reset normal maps
15911 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15918 // if the map is loaded, reset it
15919 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15920 if(map
&& map
->IsDungeon())
15921 ((InstanceMap
*)map
)->Reset(method
);
15923 // since this is a solo instance there should not be any players inside
15924 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15925 SendResetInstanceSuccess(p
->GetMapId());
15928 m_boundInstances
[dif
].erase(itr
++);
15930 // the following should remove the instance save from the manager and delete it as well
15931 p
->RemovePlayer(this);
15935 void Player::SendResetInstanceSuccess(uint32 MapId
)
15937 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
15939 GetSession()->SendPacket(&data
);
15942 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
15944 // TODO: find what other fail reasons there are besides players in the instance
15945 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
15948 GetSession()->SendPacket(&data
);
15951 /*********************************************************/
15952 /*** Update timers ***/
15953 /*********************************************************/
15955 ///checks the 15 afk reports per 5 minutes limit
15956 void Player::UpdateAfkReport(time_t currTime
)
15958 if(m_bgAfkReportedTimer
<= currTime
)
15960 m_bgAfkReportedCount
= 0;
15961 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
15965 void Player::UpdateContestedPvP(uint32 diff
)
15967 if(!m_contestedPvPTimer
||isInCombat())
15969 if(m_contestedPvPTimer
<= diff
)
15971 ResetContestedPvP();
15974 m_contestedPvPTimer
-= diff
;
15977 void Player::UpdatePvPFlag(time_t currTime
)
15981 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
15987 void Player::UpdateDuelFlag(time_t currTime
)
15989 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
15992 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
15993 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
15995 duel
->startTimer
= 0;
15996 duel
->startTime
= currTime
;
15997 duel
->opponent
->duel
->startTimer
= 0;
15998 duel
->opponent
->duel
->startTime
= currTime
;
16001 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16006 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16008 //returning of reagents only for players, so best done here
16009 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16010 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16014 for(uint32 i
= 0; i
< 7; ++i
)
16016 if(spellInfo
->Reagent
[i
] > 0)
16018 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16019 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16020 if( msg
== EQUIP_ERR_OK
)
16022 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16024 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16029 m_temporaryUnsummonedPetNumber
= 0;
16032 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16035 // only if current pet in slot
16036 switch(pet
->getPetType())
16042 m_guardianPets
.erase(pet
->GetGUID());
16045 if(GetPetGUID() == pet
->GetGUID())
16054 switch(pet
->GetEntry())
16056 //warlock pets except imp are removed(?) when logging out
16061 mode
= PET_SAVE_NOT_IN_SLOT
;
16066 pet
->SavePetToDB(mode
);
16068 pet
->CleanupsBeforeDelete();
16069 pet
->AddObjectToRemoveList();
16070 pet
->m_removed
= true;
16072 if(pet
->isControlled())
16074 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16077 GetSession()->SendPacket(&data
);
16080 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16084 void Player::RemoveMiniPet()
16086 if(Pet
* pet
= GetMiniPet())
16088 pet
->Remove(PET_SAVE_AS_DELETED
);
16093 Pet
* Player::GetMiniPet()
16097 return ObjectAccessor::GetPet(m_miniPet
);
16100 void Player::RemoveGuardians()
16102 while(!m_guardianPets
.empty())
16104 uint64 guid
= *m_guardianPets
.begin();
16105 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16106 pet
->Remove(PET_SAVE_AS_DELETED
);
16108 m_guardianPets
.erase(guid
);
16112 bool Player::HasGuardianWithEntry(uint32 entry
)
16114 // pet guid middle part is entry (and creature also)
16115 // and in guardian list must be guardians with same entry _always_
16116 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16117 if(GUID_ENPART(*itr
)==entry
)
16123 void Player::Uncharm()
16125 Unit
* charm
= GetCharm();
16129 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16130 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16133 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, std::string text
, uint32 language
) const
16135 *data
<< (uint8
)msgtype
;
16136 *data
<< (uint32
)language
;
16137 *data
<< (uint64
)GetGUID();
16138 *data
<< (uint32
)language
; //language 2.1.0 ?
16139 *data
<< (uint64
)GetGUID();
16140 *data
<< (uint32
)(text
.length()+1);
16142 *data
<< (uint8
)chatTag();
16145 void Player::Say(const std::string text
, const uint32 language
)
16147 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16148 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16149 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16152 void Player::Yell(const std::string text
, const uint32 language
)
16154 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16155 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16156 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16159 void Player::TextEmote(const std::string text
)
16161 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16162 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16163 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16166 void Player::Whisper(std::string text
, uint32 language
,uint64 receiver
)
16168 if (language
!= LANG_ADDON
) // if not addon data
16169 language
= LANG_UNIVERSAL
; // whispers should always be readable
16171 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16173 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16174 if(!rPlayer
->isDND() || isGameMaster())
16176 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16177 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16178 rPlayer
->GetSession()->SendPacket(&data
);
16180 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16181 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16182 GetSession()->SendPacket(&data
);
16186 // announce to player that player he is whispering to is dnd and cannot receive his message
16187 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16190 if(!isAcceptWhispers())
16192 SetAcceptWhispers(true);
16193 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16196 // announce to player that player he is whispering to is afk
16197 if(rPlayer
->isAFK())
16198 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16200 // if player whisper someone, auto turn of dnd to be able to receive an answer
16201 if(isDND() && !rPlayer
->isGameMaster())
16205 void Player::PetSpellInitialize()
16207 Pet
* pet
= GetPet();
16212 sLog
.outDebug("Pet Spells Groups");
16214 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16216 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16217 data
<< uint64(pet
->GetGUID());
16218 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16220 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16223 for(uint32 i
= 0; i
< 10; i
++)
16225 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16228 size_t spellsCountPos
= data
.wpos();
16232 data
<< uint8(addlist
); // placeholder
16234 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16237 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16239 if(itr
->second
->state
== PETSPELL_REMOVED
)
16242 data
<< uint16(itr
->first
);
16243 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16248 data
.put
<uint8
>(spellsCountPos
, addlist
);
16250 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16251 data
<< uint8(cooldownsCount
);
16253 time_t curTime
= time(NULL
);
16255 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16257 time_t cooldown
= 0;
16259 if(itr
->second
> curTime
)
16260 cooldown
= (itr
->second
- curTime
) * 1000;
16262 data
<< uint16(itr
->first
); // spellid
16263 data
<< uint16(0); // spell category?
16264 data
<< uint32(itr
->second
); // cooldown
16265 data
<< uint32(0); // category cooldown
16268 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16270 time_t cooldown
= 0;
16272 if(itr
->second
> curTime
)
16273 cooldown
= (itr
->second
- curTime
) * 1000;
16275 data
<< uint16(itr
->first
); // spellid
16276 data
<< uint16(0); // spell category?
16277 data
<< uint32(0); // cooldown
16278 data
<< uint32(itr
->second
); // category cooldown
16281 GetSession()->SendPacket(&data
);
16284 void Player::PossessSpellInitialize()
16286 Unit
* charm
= GetCharm();
16291 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16295 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16300 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16303 data
<< uint64(charm
->GetGUID());
16304 data
<< uint32(0x00000000);
16306 data
<< uint8(0) << uint8(0) << uint16(0);
16308 for(uint32 i
= 0; i
< 10; i
++) //40
16310 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16313 data
<< uint8(addlist
); //1
16316 data
<< uint8(count
); // cooldowns count
16318 GetSession()->SendPacket(&data
);
16321 void Player::CharmSpellInitialize()
16323 Unit
* charm
= GetCharm();
16328 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16331 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16337 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16339 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16341 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16343 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16345 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16351 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16353 data
<< uint64(charm
->GetGUID());
16354 data
<< uint32(0x00000000);
16356 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16357 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16359 data
<< uint8(0) << uint8(0);
16362 for(uint32 i
= 0; i
< 10; i
++) //40
16364 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16367 data
<< uint8(addlist
); //1
16371 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16373 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16374 if(cspell
->spellId
)
16376 data
<< uint16(cspell
->spellId
);
16377 data
<< uint16(cspell
->active
);
16383 data
<< uint8(count
); // cooldowns count
16385 GetSession()->SendPacket(&data
);
16388 int32
Player::GetTotalFlatMods(uint32 spellId
, SpellModOp op
)
16390 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16391 if (!spellInfo
) return 0;
16393 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16395 SpellModifier
*mod
= *itr
;
16397 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16400 if (mod
->type
== SPELLMOD_FLAT
)
16401 total
+= mod
->value
;
16406 int32
Player::GetTotalPctMods(uint32 spellId
, SpellModOp op
)
16408 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16409 if (!spellInfo
) return 0;
16411 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16413 SpellModifier
*mod
= *itr
;
16415 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16418 if (mod
->type
== SPELLMOD_PCT
)
16419 total
+= mod
->value
;
16424 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16426 if (!mod
|| !spellInfo
)
16429 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16431 // prevent apply to any spell except spell that trigger expire
16434 if(mod
->lastAffected
!= spell
)
16437 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16441 return spellmgr
.IsAffectedBySpell(spellInfo
,mod
->spellId
,mod
->effectId
,mod
->mask
);
16444 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16446 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16448 for(int eff
=0;eff
<64;++eff
)
16450 uint64 _mask
= uint64(1) << eff
;
16451 if ( mod
->mask
& _mask
)
16454 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16456 if ((*itr
)->type
== mod
->type
&& (*itr
)->mask
& _mask
)
16457 val
+= (*itr
)->value
;
16459 val
+= apply
? mod
->value
: -(mod
->value
);
16460 WorldPacket
data(Opcode
, (1+1+4));
16461 data
<< uint8(eff
);
16462 data
<< uint8(mod
->op
);
16463 data
<< int32(val
);
16464 SendDirectMessage(&data
);
16469 m_spellMods
[mod
->op
].push_back(mod
);
16472 if (mod
->charges
== -1)
16473 --m_SpellModRemoveCount
;
16474 m_spellMods
[mod
->op
].remove(mod
);
16479 void Player::RemoveSpellMods(Spell
const* spell
)
16481 if(!spell
|| (m_SpellModRemoveCount
== 0))
16484 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16486 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16488 SpellModifier
*mod
= *itr
;
16491 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16493 RemoveAurasDueToSpell(mod
->spellId
);
16494 if (m_spellMods
[i
].empty())
16497 itr
= m_spellMods
[i
].begin();
16503 // send Proficiency
16504 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16506 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16507 data
<< pr1
<< pr2
;
16508 GetSession()->SendPacket (&data
);
16511 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16513 QueryResult
*result
= NULL
;
16515 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16517 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16520 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.
16521 { // and SendPetitionQueryOpcode reads data from the DB
16522 Field
*fields
= result
->Fetch();
16523 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16524 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16526 // send update if charter owner in game
16527 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16529 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16531 } while ( result
->NextRow() );
16536 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16538 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16541 CharacterDatabase
.BeginTransaction();
16544 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16545 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16549 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16550 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16552 CharacterDatabase
.CommitTransaction();
16555 void Player::SetRestBonus (float rest_bonus_new
)
16557 // Prevent resting on max level
16558 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16559 rest_bonus_new
= 0;
16561 if(rest_bonus_new
< 0)
16562 rest_bonus_new
= 0;
16564 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16566 if(rest_bonus_new
> rest_bonus_max
)
16567 m_rest_bonus
= rest_bonus_max
;
16569 m_rest_bonus
= rest_bonus_new
;
16571 // update data for client
16572 if(m_rest_bonus
>10)
16573 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16574 else if(m_rest_bonus
<=1)
16575 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16578 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16581 void Player::HandleStealthedUnitsDetection()
16583 std::list
<Unit
*> stealthedUnits
;
16585 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16587 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16588 cell
.SetNoCreate();
16590 MaNGOS::AnyStealthedCheck u_check
;
16591 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(stealthedUnits
, u_check
);
16593 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16594 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16596 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16597 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16598 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16600 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16604 i
= stealthedUnits
.erase(i
);
16608 if ((*i
)->isVisibleForOrDetect(this,true))
16611 (*i
)->SendUpdateToPlayer(this);
16612 m_clientGUIDs
.insert((*i
)->GetGUID());
16614 #ifdef MANGOS_DEBUG
16615 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16616 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16619 // target aura duration for caster show only if target exist at caster client
16620 // send data at target visibility change (adding to client)
16621 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16622 SendAurasForTarget(*i
);
16624 i
= stealthedUnits
.erase(i
);
16632 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16634 if(nodes
.size() < 2)
16637 // not let cheating with start flight mounted
16640 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16641 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16642 GetSession()->SendPacket(&data
);
16646 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16648 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16649 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16650 GetSession()->SendPacket(&data
);
16654 // 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
16655 if(GetSession()->isLogingOut() ||
16656 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16657 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16658 IsNonMeleeSpellCasted(false) ||
16661 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16662 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16663 GetSession()->SendPacket(&data
);
16667 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16670 uint32 sourcenode
= nodes
[0];
16672 // starting node too far away (cheat?)
16673 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16674 if( !node
|| node
->map_id
!= GetMapId() ||
16675 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16676 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16677 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16678 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16680 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16681 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16682 GetSession()->SendPacket(&data
);
16686 // Prepare to flight start now
16688 // stop combat at start taxi flight if any
16691 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16694 // clean not finished taxi path if any
16695 m_taxi
.ClearTaxiDestinations();
16697 // 0 element current node
16698 m_taxi
.AddTaxiDestination(sourcenode
);
16700 // fill destinations path tail
16701 uint32 sourcepath
= 0;
16702 uint32 totalcost
= 0;
16704 uint32 prevnode
= sourcenode
;
16705 uint32 lastnode
= 0;
16707 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16711 lastnode
= nodes
[i
];
16712 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16716 m_taxi
.ClearTaxiDestinations();
16722 if(prevnode
== sourcenode
)
16725 m_taxi
.AddTaxiDestination(lastnode
);
16727 prevnode
= lastnode
;
16730 if(!mount_id
) // if not provide then attempt use default.
16731 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16733 if (mount_id
== 0 || sourcepath
== 0)
16735 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16736 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16737 GetSession()->SendPacket(&data
);
16738 m_taxi
.ClearTaxiDestinations();
16742 uint32 money
= GetMoney();
16746 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16749 if(money
< totalcost
)
16751 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16752 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16753 GetSession()->SendPacket(&data
);
16754 m_taxi
.ClearTaxiDestinations();
16758 //Checks and preparations done, DO FLIGHT
16759 ModifyMoney(-(int32
)totalcost
);
16761 // prevent stealth flight
16762 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16764 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16765 data
<< uint32(ERR_TAXIOK
);
16766 GetSession()->SendPacket(&data
);
16768 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16770 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16775 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16777 // last check 2.0.10
16778 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16780 data
<< uint8(0x0); // flags (0x1, 0x2)
16781 time_t curTime
= time(NULL
);
16782 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16784 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16786 uint32 unSpellId
= itr
->first
;
16787 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16794 // Not send cooldown for this spells
16795 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16798 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16801 data
<< unTimeMs
; // in m.secs
16802 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
16805 GetSession()->SendPacket(&data
);
16808 void Player::InitDataForForm(bool reapplyMods
)
16810 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16811 if(ssEntry
&& ssEntry
->attackSpeed
)
16813 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16814 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16815 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16818 SetRegularAttackTime();
16824 if(getPowerType()!=POWER_ENERGY
)
16825 setPowerType(POWER_ENERGY
);
16829 case FORM_DIREBEAR
:
16831 if(getPowerType()!=POWER_RAGE
)
16832 setPowerType(POWER_RAGE
);
16835 default: // 0, for example
16837 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16838 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16839 setPowerType(Powers(cEntry
->powerType
));
16844 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16846 UpdateEquipSpellsAtFormChange();
16848 UpdateAttackPowerAndDamage();
16849 UpdateAttackPowerAndDamage(true);
16852 // Return true is the bought item has a max count to force refresh of window by caller
16853 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16855 // cheating attempt
16856 if(count
< 1) count
= 1;
16861 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16864 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16868 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16871 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16872 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16876 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16877 if(!vItems
|| vItems
->Empty())
16879 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16883 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16884 if(vendor_slot
>= vItems
->GetItemCount())
16886 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16890 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16892 // check current item amount if it limited
16893 if( crItem
->maxcount
!= 0 )
16895 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16897 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16902 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16904 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16908 if(crItem
->ExtendedCost
)
16910 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16913 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16917 // honor points price
16918 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16920 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16924 // arena points price
16925 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16927 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16932 for (uint8 i
= 0; i
< 5; ++i
)
16934 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16936 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16941 // check for personal arena rating requirement
16942 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16944 // probably not the proper equip err
16945 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
16950 uint32 price
= pProto
->BuyPrice
* count
;
16952 // reputation discount
16953 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
16955 if( GetMoney() < price
)
16957 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
16961 uint8 bag
= 0; // init for case invalid bagGUID
16963 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
16966 if( bagguid
== GetGUID() )
16968 bag
= INVENTORY_SLOT_BAG_0
;
16972 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
16974 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
16977 if( bagguid
== pBag
->GetGUID() )
16987 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
16989 ItemPosCountVec dest
;
16990 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
16991 if( msg
!= EQUIP_ERR_OK
)
16993 SendEquipError( msg
, NULL
, NULL
);
16997 ModifyMoney( -(int32
)price
);
16998 if(crItem
->ExtendedCost
) // case for new honor system
17000 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17001 if(iece
->reqhonorpoints
)
17002 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17003 if(iece
->reqarenapoints
)
17004 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17005 for (uint8 i
= 0; i
< 5; ++i
)
17007 if(iece
->reqitem
[i
])
17008 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17012 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17014 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17016 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17017 data
<< pCreature
->GetGUID();
17018 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17019 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17020 data
<< (uint32
)count
;
17021 GetSession()->SendPacket(&data
);
17023 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17026 else if( IsEquipmentPos( bag
, slot
) )
17029 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, pProto
->BuyCount
* count
, false );
17030 if( msg
!= EQUIP_ERR_OK
)
17032 SendEquipError( msg
, NULL
, NULL
);
17036 ModifyMoney( -(int32
)price
);
17037 if(crItem
->ExtendedCost
) // case for new honor system
17039 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17040 if(iece
->reqhonorpoints
)
17041 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17042 if(iece
->reqarenapoints
)
17043 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17044 for (uint8 i
= 0; i
< 5; ++i
)
17046 if(iece
->reqitem
[i
])
17047 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17051 if(Item
*it
= EquipNewItem( dest
, item
, pProto
->BuyCount
* count
, true ))
17053 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17055 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17056 data
<< pCreature
->GetGUID();
17057 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17058 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17059 data
<< (uint32
)count
;
17060 GetSession()->SendPacket(&data
);
17062 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17064 AutoUnequipOffhandIfNeed();
17069 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17073 return crItem
->maxcount
!=0;
17076 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17078 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17079 // the personal rating of the arena team must match the required limit as well
17080 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17081 uint32 max_personal_rating
= 0;
17082 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17084 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17086 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17087 uint32 t_rating
= at
->GetRating();
17088 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17089 if(max_personal_rating
< p_rating
)
17090 max_personal_rating
= p_rating
;
17093 return max_personal_rating
;
17096 void Player::UpdateHomebindTime(uint32 time
)
17098 // GMs never get homebind timer online
17099 if (m_InstanceValid
|| isGameMaster())
17101 if(m_HomebindTimer
) // instance valid, but timer not reset
17104 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17107 GetSession()->SendPacket(&data
);
17109 // instance is valid, reset homebind timer
17110 m_HomebindTimer
= 0;
17112 else if (m_HomebindTimer
> 0)
17114 if (time
>= m_HomebindTimer
)
17116 // teleport to homebind location
17117 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17120 m_HomebindTimer
-= time
;
17124 // instance is invalid, start homebind timer
17125 m_HomebindTimer
= 60000;
17126 // send message to player
17127 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17128 data
<< m_HomebindTimer
;
17130 GetSession()->SendPacket(&data
);
17131 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17135 void Player::UpdatePvP(bool state
, bool ovrride
)
17137 if(!state
|| ovrride
)
17140 if(Pet
* pet
= GetPet())
17141 pet
->SetPvP(state
);
17142 if(Unit
* charmed
= GetCharm())
17143 charmed
->SetPvP(state
);
17145 pvpInfo
.endTimer
= 0;
17149 if(pvpInfo
.endTimer
!= 0)
17150 pvpInfo
.endTimer
= time(NULL
);
17155 if(Pet
* pet
= GetPet())
17156 pet
->SetPvP(state
);
17157 if(Unit
* charmed
= GetCharm())
17158 charmed
->SetPvP(state
);
17163 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17167 sc
.itemid
= itemid
;
17168 m_spellCooldowns
[spellid
] = sc
;
17171 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
17173 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
17176 // Get spell cooldown
17177 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
17179 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
17183 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
17185 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17186 data
<< spellInfo
->Id
;
17188 SendDirectMessage(&data
);
17190 //slot to be excluded while counting
17191 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17193 if(!enchantmentcondition
)
17196 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17201 uint8 curcount
[4] = {0, 0, 0, 0};
17203 //counting current equipped gem colors
17204 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17208 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17209 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17211 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17213 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17217 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17221 uint32 gemid
= enchantEntry
->GemID
;
17225 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17229 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17233 uint8 GemColor
= gemProperty
->color
;
17235 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17237 if(tmpcolormask
& GemColor
)
17244 bool activate
= true;
17246 for(int i
= 0; i
< 5; i
++)
17248 if(!Condition
->Color
[i
])
17251 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17253 // if have <CompareColor> use them as count, else use <value> from Condition
17254 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17256 switch(Condition
->Comparator
[i
])
17258 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17259 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17261 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17262 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17264 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17265 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17270 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");
17275 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17277 //cycle all equipped items
17278 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17280 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17281 if(slot
== exceptslot
)
17284 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17286 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17289 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17291 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17295 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17299 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17302 //was enchant active with/without item?
17303 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17304 //should it now be?
17305 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17307 // ignore item gem conditions
17308 //if state changed, (dis)apply enchant
17309 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17316 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17317 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17319 //cycle all equipped items
17320 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17322 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17323 if(slot
== exceptslot
)
17326 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17328 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17331 //cycle all (gem)enchants
17332 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17334 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17335 if(!enchant_id
) //if no enchant go to next enchant(slot)
17338 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17342 //only metagems to be (de)activated, so only enchants with condition
17343 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17345 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17350 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17352 if(BattleGround
*bg
= GetBattleGround())
17354 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
17356 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17358 // call after remove to be sure that player resurrected for correct cast
17360 CastSpell(this, 26013, true); // Deserter
17364 bool Player::CanJoinToBattleground() const
17366 // check Deserter debuff
17367 if(GetDummyAura(26013))
17373 bool Player::CanReportAfkDueToLimit()
17375 // a player can complain about 15 people per 5 minutes
17376 if(m_bgAfkReportedCount
>= 15)
17378 ++m_bgAfkReportedCount
;
17382 ///This player has been blamed to be inactive in a battleground
17383 void Player::ReportedAfkBy(Player
* reporter
)
17385 BattleGround
*bg
= GetBattleGround();
17386 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17389 // check if player has 'Idle' or 'Inactive' debuff
17390 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17392 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17393 // 3 players have to complain to apply debuff
17394 if(m_bgAfkReporter
.size() >= 3)
17396 // cast 'Idle' spell
17397 CastSpell(this, 43680, true);
17398 m_bgAfkReporter
.clear();
17403 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17405 // gamemaster in GM mode see all, including ghosts
17406 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17409 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17410 if (InBattleGround())
17412 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17417 // Live player see live player or dead player with not realized corpse
17418 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17420 return isAlive() || m_deathTimer
> 0;
17423 // Ghost see other friendly ghosts, that's for sure
17424 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17427 // Dead player see live players near own corpse
17430 Corpse
*corpse
= pl
->GetCorpse();
17433 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17434 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17439 // and not see any other
17443 bool Player::IsVisibleGloballyFor( Player
* u
) const
17448 // Always can see self
17452 // Visible units, always are visible for all players
17453 if (GetVisibility() == VISIBILITY_ON
)
17456 // GMs are visible for higher gms (or players are visible for gms)
17457 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17458 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17460 // non faction visibility non-breakable for non-GMs
17461 if (GetVisibility() == VISIBILITY_OFF
)
17464 // non-gm stealth/invisibility not hide from global player lists
17468 void Player::UpdateVisibilityOf(WorldObject
* target
)
17470 if(HaveAtClient(target
))
17472 if(!target
->isVisibleForInState(this,true))
17474 target
->DestroyForPlayer(this);
17475 m_clientGUIDs
.erase(target
->GetGUID());
17477 #ifdef MANGOS_DEBUG
17478 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17479 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17485 if(target
->isVisibleForInState(this,false))
17487 target
->SendUpdateToPlayer(this);
17488 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17489 m_clientGUIDs
.insert(target
->GetGUID());
17491 #ifdef MANGOS_DEBUG
17492 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17493 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17496 // target aura duration for caster show only if target exist at caster client
17497 // send data at target visibility change (adding to client)
17498 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17499 SendAurasForTarget((Unit
*)target
);
17501 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17502 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17508 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17510 s64
.insert(target
->GetGUID());
17514 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17516 if(!target
->IsTransport())
17517 s64
.insert(target
->GetGUID());
17521 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17523 if(HaveAtClient(target
))
17525 if(!target
->isVisibleForInState(this,true))
17527 target
->BuildOutOfRangeUpdateBlock(&data
);
17528 m_clientGUIDs
.erase(target
->GetGUID());
17530 #ifdef MANGOS_DEBUG
17531 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17532 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
));
17538 if(target
->isVisibleForInState(this,false))
17540 visibleNow
.insert(target
);
17541 target
->BuildUpdate(data_updates
);
17542 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17543 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17545 #ifdef MANGOS_DEBUG
17546 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17547 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
));
17553 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17554 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17555 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17556 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17557 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17559 void Player::InitPrimaryProffesions()
17561 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17564 void Player::SendComboPoints()
17566 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17569 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17570 data
.append(combotarget
->GetPackGUID());
17571 data
<< uint8(m_comboPoints
);
17572 GetSession()->SendPacket(&data
);
17576 void Player::AddComboPoints(Unit
* target
, int8 count
)
17581 // without combo points lost (duration checked in aura)
17582 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17584 if(target
->GetGUID() == m_comboTarget
)
17586 m_comboPoints
+= count
;
17591 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17592 target
->RemoveComboPointHolder(GetGUIDLow());
17594 m_comboTarget
= target
->GetGUID();
17595 m_comboPoints
= count
;
17597 target
->AddComboPointHolder(GetGUIDLow());
17600 if (m_comboPoints
> 5) m_comboPoints
= 5;
17601 if (m_comboPoints
< 0) m_comboPoints
= 0;
17606 void Player::ClearComboPoints()
17611 // without combopoints lost (duration checked in aura)
17612 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17618 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17619 target
->RemoveComboPointHolder(GetGUIDLow());
17624 void Player::SetGroup(Group
*group
, int8 subgroup
)
17626 if(group
== NULL
) m_group
.unlink();
17629 // never use SetGroup without a subgroup unless you specify NULL for group
17630 assert(subgroup
>= 0);
17631 m_group
.link(group
, this);
17632 m_group
.setSubGroup((uint8
)subgroup
);
17636 void Player::SendInitialPacketsBeforeAddToMap()
17638 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17639 data
<< uint32(0); // unknown, may be rest state time or experience
17640 GetSession()->SendPacket(&data
);
17643 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17644 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17645 data
<< (uint32
) m_homebindMapId
;
17646 data
<< (uint32
) m_homebindZoneId
;
17647 GetSession()->SendPacket(&data
);
17649 // SMSG_SET_PROFICIENCY
17650 // SMSG_UPDATE_AURA_DURATION
17653 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17654 for (int i
= 0; i
< 8; ++i
)
17655 data
<< uint32( GetTutorialInt(i
) );
17656 GetSession()->SendPacket(&data
);
17658 SendInitialSpells();
17660 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17661 data
<< uint32(0); // count, for(count) uint32;
17662 GetSession()->SendPacket(&data
);
17664 SendInitialActionButtons();
17665 SendInitialReputations();
17666 m_achievementMgr
.SendAllAchievementData();
17667 UpdateZone(GetZoneId());
17668 SendInitWorldStates();
17670 // SMSG_SET_AURA_SINGLE
17672 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17673 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17674 data
<< (float)0.01666667f
; // game speed
17675 GetSession()->SendPacket( &data
);
17677 data
.Initialize(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17678 data
<< uint32(0x00000000); // on blizz it increments periodically
17679 GetSession()->SendPacket(&data
);
17681 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17682 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17683 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17688 void Player::SendInitialPacketsAfterAddToMap()
17690 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17691 data
<< uint32(0x00000000); // on blizz it increments periodically
17692 GetSession()->SendPacket(&data
);
17694 CastSpell(this, 836, true); // LOGINEFFECT
17696 // set some aura effects that send packet to player client after add player to map
17697 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17698 // same auras state lost at far teleport, send it one more time in this case also
17699 static const AuraType auratypes
[] =
17701 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17702 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17703 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17705 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17707 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17708 if(!auraList
.empty())
17709 auraList
.front()->ApplyModifier(true,true);
17712 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17713 SetMovement(MOVE_ROOT
);
17715 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17716 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17718 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
17719 data
.append(GetPackGUID());
17721 SendMessageToSet(&data
,true);
17724 SendAurasForTarget(this);
17725 SendEnchantmentDurations(); // must be after add to map
17726 SendItemDurations(); // must be after add to map
17729 void Player::SendUpdateToOutOfRangeGroupMembers()
17731 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17733 if(Group
* group
= GetGroup())
17734 group
->UpdatePlayerOutOfRange(this);
17736 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17737 m_auraUpdateMask
= 0;
17738 if(Pet
*pet
= GetPet())
17739 pet
->ResetAuraUpdateMask();
17742 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
17744 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17745 data
<< uint32(mapid
);
17746 data
<< uint8(reason
); // transfer abort reason
17749 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
17750 case TRANSFER_ABORT_DIFFICULTY
:
17751 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
17752 data
<< uint8(arg
);
17755 GetSession()->SendPacket(&data
);
17758 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17760 // type of warning, based on the time remaining until reset
17763 type
= RAID_INSTANCE_WELCOME
;
17764 else if(time
> 900 && time
<= 3600)
17765 type
= RAID_INSTANCE_WARNING_HOURS
;
17766 else if(time
> 300 && time
<= 900)
17767 type
= RAID_INSTANCE_WARNING_MIN
;
17769 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17770 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17771 data
<< uint32(type
);
17772 data
<< uint32(mapid
);
17773 data
<< uint32(time
);
17774 GetSession()->SendPacket(&data
);
17777 void Player::ApplyEquipCooldown( Item
* pItem
)
17779 for(int i
= 0; i
<5; ++i
)
17781 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17784 if( !spellData
.SpellId
)
17787 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17788 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17791 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17793 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17794 data
<< pItem
->GetGUID();
17795 data
<< uint32(spellData
.SpellId
);
17796 GetSession()->SendPacket(&data
);
17800 void Player::resetSpells()
17802 // not need after this call
17803 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17805 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17806 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17809 // make full copy of map (spells removed and marked as deleted at another spell remove
17810 // and we can't use original map for safe iterative with visit each spell at loop end
17811 PlayerSpellMap smap
= GetSpellMap();
17813 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17814 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17816 learnDefaultSpells();
17817 learnQuestRewardedSpells();
17820 void Player::learnDefaultSpells(bool loading
)
17822 // learn default race/class spells
17823 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17824 std::list
<CreateSpellPair
>::const_iterator spell_itr
;
17825 for (spell_itr
= info
->spell
.begin(); spell_itr
!=info
->spell
.end(); ++spell_itr
)
17827 uint16 tspell
= spell_itr
->first
;
17830 sLog
.outDebug("PLAYER: Adding initial spell, id = %u",tspell
);
17831 if(loading
|| !spell_itr
->second
) // not care about passive spells or loading case
17832 addSpell(tspell
,spell_itr
->second
);
17833 else // but send in normal spell in game learn case
17834 learnSpell(tspell
);
17839 void Player::learnQuestRewardedSpells(Quest
const* quest
)
17841 uint32 spell_id
= quest
->GetRewSpellCast();
17843 // skip quests without rewarded spell
17847 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
17851 // check learned spells state
17852 bool found
= false;
17853 for(int i
=0; i
< 3; ++i
)
17855 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
17862 // skip quests with not teaching spell or already known spell
17866 // prevent learn non first rank unknown profession and second specialization for same profession)
17867 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
17868 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
17870 // not have first rank learned (unlearned prof?)
17871 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
17872 if( !HasSpell(first_spell
) )
17875 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
17880 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
17882 // search other specialization for same prof
17883 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17885 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
17888 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
17892 // compare only specializations
17893 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
17896 // compare same chain spells
17897 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
17900 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17901 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
17907 CastSpell( this, spell_id
, true);
17910 void Player::learnQuestRewardedSpells()
17912 // learn spells received from quest completing
17913 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
17915 // skip no rewarded quests
17916 if(!itr
->second
.m_rewarded
)
17919 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
17923 learnQuestRewardedSpells(quest
);
17927 void Player::learnSkillRewardedSpells(uint32 skill_id
)
17929 uint32 raceMask
= getRaceMask();
17930 uint32 classMask
= getClassMask();
17931 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
17933 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
17934 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
17936 // Check race if set
17937 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
17939 // Check class if set
17940 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
17943 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
17945 // Ok need learn spell
17946 learnSpell(pAbility
->spellId
);
17951 void Player::learnSkillRewardedSpells()
17953 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
17955 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
17958 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
17960 learnSkillRewardedSpells(pskill
);
17964 void Player::SendAurasForTarget(Unit
*target
)
17966 if(target
->GetVisibleAuras()->empty()) // speedup things
17969 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
17970 data
.append(target
->GetPackGUID());
17972 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
17973 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
17975 for(uint32 j
= 0; j
< 3; ++j
)
17977 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
17979 data
<< uint8(aura
->GetAuraSlot());
17980 data
<< uint32(aura
->GetId());
17984 uint8 auraFlags
= aura
->GetAuraFlags();
17986 data
<< uint8(auraFlags
);
17988 data
<< uint8(aura
->GetAuraLevel());
17990 data
<< uint8(aura
->m_procCharges
>= 0 ? aura
->m_procCharges
: 0 );
17992 if(!(auraFlags
& AFLAG_NOT_CASTER
))
17994 data
<< uint8(0); // packed GUID of someone (caster?)
17997 if(auraFlags
& AFLAG_DURATION
) // include aura duration
17999 data
<< uint32(aura
->GetAuraMaxDuration());
18000 data
<< uint32(aura
->GetAuraDuration());
18008 GetSession()->SendPacket(&data
);
18011 void Player::SetDailyQuestStatus( uint32 quest_id
)
18013 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18015 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18017 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18018 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18019 m_DailyQuestChanged
= true;
18025 void Player::ResetDailyQuestStatus()
18027 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18028 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18030 // DB data deleted in caller
18031 m_DailyQuestChanged
= false;
18032 m_lastDailyQuestTime
= 0;
18035 BattleGround
* Player::GetBattleGround() const
18037 if(GetBattleGroundId()==0)
18040 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
18043 bool Player::InArena() const
18045 BattleGround
*bg
= GetBattleGround();
18046 if(!bg
|| !bg
->isArena())
18052 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
18054 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(bgTypeId
);
18058 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18064 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
18072 return 10*(queue_id
+1);
18075 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
18078 return 255; // hardcoded max level
18080 return 10*(queue_id
+2)-1;
18083 uint32
Player::GetBattleGroundQueueIdFromLevel() const
18085 uint32 level
= getLevel();
18088 else if (level
> 79)
18091 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18094 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18096 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18097 if(!vendor_faction
)
18100 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18101 if(rank
<= REP_NEUTRAL
)
18104 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18107 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18109 uint32 racemask
= getRaceMask();
18110 uint32 classmask
= getClassMask();
18112 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18113 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18115 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18117 // skip wrong race skills
18118 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18121 // skip wrong class skills
18122 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18128 bool Player::HasQuestForGO(int32 GOId
)
18130 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
18132 QuestStatusData qs
=i
->second
;
18133 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18135 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
18139 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18142 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18144 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18147 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18155 void Player::UpdateForQuestsGO()
18157 if(m_clientGUIDs
.empty())
18161 WorldPacket packet
;
18162 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18164 if(IS_GAMEOBJECT_GUID(*itr
))
18166 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18168 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18171 udata
.BuildPacket(&packet
);
18172 GetSession()->SendPacket(&packet
);
18175 void Player::SummonIfPossible(bool agree
)
18179 m_summon_expire
= 0;
18183 // expire and auto declined
18184 if(m_summon_expire
< time(NULL
))
18187 // stop taxi flight at summon
18190 GetMotionMaster()->MovementExpired();
18191 m_taxi
.ClearTaxiDestinations();
18194 // drop flag at summon
18195 if(BattleGround
*bg
= GetBattleGround())
18196 bg
->EventPlayerDroppedFlag(this);
18198 m_summon_expire
= 0;
18200 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18203 void Player::RemoveItemDurations( Item
*item
)
18205 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18209 m_itemDuration
.erase(itr
);
18215 void Player::AddItemDurations( Item
*item
)
18217 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18219 m_itemDuration
.push_back(item
);
18220 item
->SendTimeUpdate(this);
18224 void Player::AutoUnequipOffhandIfNeed()
18226 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18230 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
18232 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
18235 ItemPosCountVec off_dest
;
18236 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18237 if( off_msg
== EQUIP_ERR_OK
)
18239 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18240 StoreItem( off_dest
, offItem
, true );
18244 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18248 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18250 if(spellInfo
->EquippedItemClass
< 0)
18253 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18254 // for optimize check 2 used cases only
18255 switch(spellInfo
->EquippedItemClass
)
18257 case ITEM_CLASS_WEAPON
:
18259 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18260 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18261 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18265 case ITEM_CLASS_ARMOR
:
18267 // tabard not have dependent spells
18268 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18269 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18270 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18273 // shields can be equipped to offhand slot
18274 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18275 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18278 // ranged slot can have some armor subclasses
18279 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18280 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18286 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18293 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18295 AuraMap
& auras
= GetAuras();
18296 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18298 Aura
* aura
= itr
->second
;
18300 // skip passive (passive item dependent spells work in another way) and not self applied auras
18301 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18302 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18308 // skip if not item dependent or have alternative item
18309 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18315 // no alt item, remove aura, restart check
18316 RemoveAurasDueToSpell(aura
->GetId());
18317 itr
= auras
.begin();
18320 // currently casted spells can be dependent from item
18321 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18323 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18324 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18329 uint32
Player::GetResurrectionSpellId()
18331 // search priceless resurrection possibilities
18333 uint32 spell_id
= 0;
18334 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18335 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18337 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18338 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18340 switch((*itr
)->GetId())
18342 case 20707: spell_id
= 3026; break; // rank 1
18343 case 20762: spell_id
= 20758; break; // rank 2
18344 case 20763: spell_id
= 20759; break; // rank 3
18345 case 20764: spell_id
= 20760; break; // rank 4
18346 case 20765: spell_id
= 20761; break; // rank 5
18347 case 27239: spell_id
= 27240; break; // rank 6
18349 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18355 // Twisting Nether // prio: 2 (max)
18356 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18363 // Reincarnation (passive spell) // prio: 1
18364 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18370 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18372 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18374 // prepare data for near group iteration (PvP and !PvP cases)
18376 bool honored_kill
= false;
18378 if(Group
*pGroup
= GetGroup())
18381 uint32 sum_level
= 0;
18382 Player
* member_with_max_level
= NULL
;
18383 Player
* not_gray_member_with_max_level
= NULL
;
18385 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18387 if(member_with_max_level
)
18389 /// not get Xp in PvP or no not gray players in group
18390 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18392 /// skip in check PvP case (for speed, not used)
18393 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18394 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18395 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18397 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18399 Player
* pGroupGuy
= itr
->getSource();
18403 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18404 continue; // member (alive or dead) or his corpse at req. distance
18406 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18407 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18408 honored_kill
= true;
18410 // xp and reputation only in !PvP case
18413 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18415 // if is in dungeon then all receive full reputation at kill
18416 // rewarded any alive/dead/near_corpse group member
18417 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18419 // XP updated only for alive group member
18420 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18421 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18423 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18425 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18426 if(Pet
* pet
= pGroupGuy
->GetPet())
18427 pet
->GivePetXP(itr_xp
/2);
18430 // quest objectives updated only for alive group member or dead but with not released body
18431 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18433 // normal creature (not pet/etc) can be only in !PvP case
18434 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18435 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18441 else // if (!pGroup)
18443 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18445 // honor can be in PvP and !PvP (racial leader) cases
18446 if(RewardHonor(pVictim
,1))
18447 honored_kill
= true;
18449 // xp and reputation only in !PvP case
18452 RewardReputation(pVictim
,1);
18453 GiveXP(xp
, pVictim
);
18455 if(Pet
* pet
= GetPet())
18456 pet
->GivePetXP(xp
);
18458 // normal creature (not pet/etc) can be only in !PvP case
18459 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18460 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18463 return xp
|| honored_kill
;
18466 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18468 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18474 Corpse
* corpse
= GetCorpse();
18478 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18481 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18483 Item
* item
= GetWeaponForAttack(attType
,true);
18485 // unarmed only with base attack
18486 if(attType
!= BASE_ATTACK
&& !item
)
18489 // weapon skill or (unarmed for base attack)
18490 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18491 return GetBaseSkillValue(skill
);
18494 void Player::ResurectUsingRequestData()
18496 ResurrectPlayer(0.0f
,false);
18498 if(GetMaxHealth() > m_resurrectHealth
)
18499 SetHealth( m_resurrectHealth
);
18501 SetHealth( GetMaxHealth() );
18503 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18504 SetPower(POWER_MANA
, m_resurrectMana
);
18506 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18508 SetPower(POWER_RAGE
, 0 );
18510 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18512 SpawnCorpseBones();
18514 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18517 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18519 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18520 data
.append(target
->GetPackGUID());
18521 data
<< uint8(allowMove
);
18522 GetSession()->SendPacket(&data
);
18525 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18527 // remove new continent flight forms
18528 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), newZone
);
18529 if( !isGameMaster() && v_map
!= 530 && v_map
!= 571)
18531 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18532 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18535 // Some spells applied at enter into zone (with subzones)
18537 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18538 if ( newZone
== 2367 ) // Old Hillsbrad Foothills
18540 uint32 spellid
= 0;
18542 if( GetTeam() == HORDE
)
18543 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18544 // and some alliance races
18545 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18546 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
18548 if(spellid
&& !HasAura(spellid
,0) )
18549 CastSpell(this,spellid
,true);
18553 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18555 // remove auras from spells with area limitations
18556 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18558 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18559 if(!IsSpellAllowedInLocation(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
))
18565 // unmount if enter in this subzone
18567 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
18568 // Dragonmaw Illusion
18569 else if( newArea
== 3759 || newArea
== 3966 || newArea
== 3939 )
18571 if( GetDummyAura(40214) )
18573 if( !HasAura(40216,0) )
18574 CastSpell(this,40216,true);
18575 if( !HasAura(42016,0) )
18576 CastSpell(this,42016,true);
18581 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18583 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18584 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18586 return copseReclaimDelay
[0];
18589 time_t now
= time(NULL
);
18590 // 0..2 full period
18591 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18592 return copseReclaimDelay
[count
];
18595 void Player::UpdateCorpseReclaimDelay()
18597 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18599 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18600 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18603 time_t now
= time(NULL
);
18604 if(now
< m_deathExpireTime
)
18606 // full and partly periods 1..3
18607 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18608 if(count
< MAX_DEATH_COUNT
)
18609 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18611 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18614 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18617 void Player::SendCorpseReclaimDelay(bool load
)
18619 Corpse
* corpse
= GetCorpse();
18626 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18629 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18632 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18633 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18635 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18636 if(count
>=MAX_DEATH_COUNT
)
18637 count
= MAX_DEATH_COUNT
-1;
18642 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18644 time_t now
= time(NULL
);
18645 if(now
>= expected_time
)
18648 delay
= expected_time
-now
;
18651 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18653 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18654 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18655 data
<< uint32(delay
*1000);
18656 GetSession()->SendPacket( &data
);
18659 Player
* Player::GetNextRandomRaidMember(float radius
)
18661 Group
*pGroup
= GetGroup();
18665 std::vector
<Player
*> nearMembers
;
18666 nearMembers
.reserve(pGroup
->GetMembersCount());
18668 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18670 Player
* Target
= itr
->getSource();
18672 // IsHostileTo check duel and controlled by enemy
18673 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18674 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18675 nearMembers
.push_back(Target
);
18678 if (nearMembers
.empty())
18681 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18682 return nearMembers
[randTarget
];
18685 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18687 float water_z
= m
->GetWaterLevel(x
,y
);
18688 float height_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
18689 uint8 flag1
= m
->GetTerrainType(x
,y
);
18691 //!Underwater check, not in water if underground or above water level
18692 if (height_z
<= INVALID_HEIGHT
|| z
< (height_z
-2) || z
> (water_z
- 2) )
18693 m_isunderwater
&= 0x7A;
18694 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
18695 m_isunderwater
|= 0x01;
18697 //!in lava check, anywhere under lava level
18698 if ((height_z
<= INVALID_HEIGHT
|| z
< (height_z
- 0)) && (flag1
== 0x00) && IsInWater())
18699 m_isunderwater
|= 0x80;
18702 void Player::SetCanParry( bool value
)
18704 if(m_canParry
==value
)
18707 m_canParry
= value
;
18708 UpdateParryPercentage();
18711 void Player::SetCanBlock( bool value
)
18713 if(m_canBlock
==value
)
18716 m_canBlock
= value
;
18717 UpdateBlockPercentage();
18720 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
18722 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
18723 if(itr
->pos
== pos
)
18729 bool Player::isAllowUseBattleGroundObject()
18731 return ( //InBattleGround() && // in battleground - not need, check in other cases
18732 !IsMounted() && // not mounted
18733 !HasStealthAura() && // not stealthed
18734 !HasInvisibilityAura() && // not invisible
18735 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
18736 isAlive() // live player
18740 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
18742 uint32 level
= getLevel();
18744 if(level
> sGtBarberShopCostBaseStore
.GetNumRows())
18745 level
= GT_MAX_LEVEL
; // max level in this dbc
18747 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
18748 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
18749 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
18751 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
18754 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
18756 if(!bsc
) // shouldn't happen
18761 if(hairstyle
!= newhairstyle
)
18762 cost
+= bsc
->cost
; // full price
18764 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
18765 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
18767 if(facialhair
!= newfacialhair
)
18768 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
18770 return uint32(cost
);
18773 void Player::InitGlyphsForLevel()
18775 uint32 level
= getLevel();
18778 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18780 value
|= (0x01 | 0x02);
18790 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
18793 void Player::EnterVehicle(Vehicle
*vehicle
)
18795 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
18799 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
18803 vehicle
->SetCharmerGUID(GetGUID());
18804 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
18805 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNKNOWN5
);
18806 vehicle
->setFaction(getFaction());
18808 SetCharm(vehicle
); // charm
18809 SetFarSight(vehicle
->GetGUID()); // set view
18811 SetClientControl(vehicle
, 1); // redirect controls to vehicle
18813 WorldPacket
data(SMSG_SHOW_VEHICLE_UI
, 0); // shows vehicle UI?
18814 GetSession()->SendPacket(&data
);
18816 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
18817 data
.append(GetPackGUID());
18818 data
<< uint32(0); // counter?
18819 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
18820 data
<< uint16(0); // special flags
18821 data
<< uint32(getMSTime()); // time
18822 data
<< vehicle
->GetPositionX(); // x
18823 data
<< vehicle
->GetPositionY(); // y
18824 data
<< vehicle
->GetPositionZ(); // z
18825 data
<< vehicle
->GetOrientation(); // o
18826 // transport part, TODO: load/calculate seat offsets
18827 data
<< uint64(vehicle
->GetGUID()); // transport guid
18828 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
18829 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
18830 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
18831 data
<< float(0); // transport orientation
18832 data
<< uint32(getMSTime()); // transport time
18833 data
<< uint8(0); // seat
18834 // end of transport part
18835 data
<< uint32(0); // fall time
18836 GetSession()->SendPacket(&data
);
18838 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
18839 data
<< uint64(vehicle
->GetGUID());
18840 data
<< uint32(0x00000000);
18841 data
<< uint32(0x00000000);
18842 data
<< uint32(0x00000101);
18844 for(uint32 i
= 0; i
< 10; ++i
)
18845 data
<< uint16(0) << uint8(0) << uint8(i
+8);
18849 GetSession()->SendPacket(&data
);
18852 void Player::ExitVehicle(Vehicle
*vehicle
)
18854 vehicle
->SetCharmerGUID(0);
18855 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
18856 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNKNOWN5
);
18857 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
18862 SetClientControl(vehicle
, 0);
18864 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
18865 data
.append(GetPackGUID());
18866 data
<< uint32(0); // counter?
18867 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
18868 data
<< uint16(0x40); // special flags
18869 data
<< uint32(getMSTime()); // time
18870 data
<< vehicle
->GetPositionX(); // x
18871 data
<< vehicle
->GetPositionY(); // y
18872 data
<< vehicle
->GetPositionZ(); // z
18873 data
<< vehicle
->GetOrientation(); // o
18874 data
<< uint32(0); // fall time
18875 GetSession()->SendPacket(&data
);
18877 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
18880 GetSession()->SendPacket(&data
);
18882 // only for flyable vehicles?
18883 CastSpell(this, 45472, true); // Parachute
18886 bool Player::HasTitle(uint32 bitIndex
)
18888 if (bitIndex
> 128)
18891 uint32 fieldIndexOffset
= bitIndex
/32;
18892 uint32 flag
= 1 << (bitIndex
%32);
18893 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
18896 void Player::SetTitle(CharTitlesEntry
const* title
)
18898 uint32 fieldIndexOffset
= title
->bit_index
/32;
18899 uint32 flag
= 1 << (title
->bit_index
%32);
18900 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
18903 void Player::ConvertRune(uint8 index
, uint8 newType
)
18905 SetCurrentRune(index
, newType
);
18907 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
18908 data
<< uint8(index
);
18909 data
<< uint8(newType
);
18910 GetSession()->SendPacket(&data
);
18913 void Player::ResyncRunes(uint8 count
)
18915 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
18916 for(uint32 i
= 0; i
< count
; ++i
)
18918 data
<< uint8(GetCurrentRune(i
)); // rune type
18919 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
18921 GetSession()->SendPacket(&data
);
18924 void Player::AddRunePower(uint8 index
)
18926 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
18927 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
18928 GetSession()->SendPacket(&data
);
18931 void Player::InitRunes()
18933 if(getClass() != CLASS_DEATH_KNIGHT
)
18936 m_runes
= new Runes
;
18938 m_runes
->runeState
= 0;
18940 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
18942 SetBaseRune(i
, i
/ 2); // init base types
18943 SetCurrentRune(i
, i
/ 2); // init current types
18944 SetRuneCooldown(i
, 0); // reset cooldowns
18945 m_runes
->SetRuneState(i
);
18948 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
18949 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);