2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "Database/DatabaseEnv.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #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"
51 #include "Transports.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
57 #include "Database/DatabaseImpl.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 CHARACTER_FLAG_NONE
= 0x00000000,
81 CHARACTER_FLAG_UNK1
= 0x00000001,
82 CHARACTER_FLAG_UNK2
= 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
84 CHARACTER_FLAG_UNK4
= 0x00000008,
85 CHARACTER_FLAG_UNK5
= 0x00000010,
86 CHARACTER_FLAG_UNK6
= 0x00000020,
87 CHARACTER_FLAG_UNK7
= 0x00000040,
88 CHARACTER_FLAG_UNK8
= 0x00000080,
89 CHARACTER_FLAG_UNK9
= 0x00000100,
90 CHARACTER_FLAG_UNK10
= 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
93 CHARACTER_FLAG_UNK13
= 0x00001000,
94 CHARACTER_FLAG_GHOST
= 0x00002000,
95 CHARACTER_FLAG_RENAME
= 0x00004000,
96 CHARACTER_FLAG_UNK16
= 0x00008000,
97 CHARACTER_FLAG_UNK17
= 0x00010000,
98 CHARACTER_FLAG_UNK18
= 0x00020000,
99 CHARACTER_FLAG_UNK19
= 0x00040000,
100 CHARACTER_FLAG_UNK20
= 0x00080000,
101 CHARACTER_FLAG_UNK21
= 0x00100000,
102 CHARACTER_FLAG_UNK22
= 0x00200000,
103 CHARACTER_FLAG_UNK23
= 0x00400000,
104 CHARACTER_FLAG_UNK24
= 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
106 CHARACTER_FLAG_DECLINED
= 0x02000000,
107 CHARACTER_FLAG_UNK27
= 0x04000000,
108 CHARACTER_FLAG_UNK28
= 0x08000000,
109 CHARACTER_FLAG_UNK29
= 0x10000000,
110 CHARACTER_FLAG_UNK30
= 0x20000000,
111 CHARACTER_FLAG_UNK31
= 0x40000000,
112 CHARACTER_FLAG_UNK32
= 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
126 memset(m_taximask
, 0, sizeof(m_taximask
));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
131 // class specific initial known nodes
134 case CLASS_DEATH_KNIGHT
:
136 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
137 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
142 // race specific initial known nodes: capital and taxi hub masks
145 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
146 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF
: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race
))
161 case ALLIANCE
: SetTaximaskNode(100); break;
162 case HORDE
: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data
)
171 Tokens tokens
= StrSplit(data
, " ");
174 Tokens::iterator iter
;
175 for (iter
= tokens
.begin(), index
= 0;
176 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
178 // load and set bits only for existed taxi nodes
179 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
187 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
188 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
192 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
193 data
<< uint32(m_taximask
[i
]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
199 ClearTaxiDestinations();
201 Tokens tokens
= StrSplit(values
," ");
203 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
205 uint32 node
= uint32(atol(iter
->c_str()));
206 AddTaxiDestination(node
);
209 if(m_TaxiDestinations
.empty())
213 if(m_TaxiDestinations
.size() < 2)
216 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
220 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
,true))
232 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations
.empty())
237 std::ostringstream ss
;
239 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
240 ss
<< m_TaxiDestinations
[i
] << " ";
245 uint32
PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations
.size() < 2)
253 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
258 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
261 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
262 ss
<< taxi
.m_taximask
[i
] << " ";
267 //== Player ====================================================
269 UpdateMask
Player::updateVisualBits
;
271 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
278 m_objectType
|= TYPEMASK_PLAYER
;
279 m_objectTypeId
= TYPEID_PLAYER
;
281 m_valuesCount
= PLAYER_END
;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER
)
293 SetAcceptWhispers(true);
301 m_usedTalentCount
= 0;
302 m_questRewardTalentCount
= 0;
305 m_weaponChangeTimer
= 0;
308 m_zoneUpdateTimer
= 0;
312 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount
= 0;
322 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL
);
328 m_groupUpdateMask
= 0;
329 m_auraUpdateMask
= 0;
333 m_GuildIdInvited
= 0;
334 m_ArenaTeamIdInvited
= 0;
336 m_atLoginFlags
= AT_LOGIN_NONE
;
338 mSemaphoreTeleport_Near
= false;
339 mSemaphoreTeleport_Far
= false;
346 PlayerTalkClass
= new PlayerMenu( GetSession() );
347 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
349 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
350 m_Tutorials
[ aX
] = 0x00;
351 m_TutorialsChanged
= false;
353 m_DailyQuestChanged
= false;
354 m_lastDailyQuestTime
= 0;
356 for (int i
=0; i
<MAX_TIMERS
; ++i
)
357 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
359 m_MirrorTimerFlags
= UNDERWATER_NONE
;
360 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
366 m_deathExpireTime
= 0;
370 m_DetectInvTimer
= 1*IN_MILISECONDS
;
372 m_bgBattleGroundID
= 0;
373 m_bgTypeID
= BATTLEGROUND_TYPE_NONE
;
374 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
376 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
377 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
381 m_logintime
= time(NULL
);
382 m_Last_tick
= m_logintime
;
383 m_WeaponProficiency
= 0;
384 m_ArmorProficiency
= 0;
387 m_canDualWield
= false;
388 m_canTitanGrip
= false;
391 m_temporaryUnsummonedPetNumber
= 0;
392 //cache for UNIT_CREATED_BY_SPELL to allow
393 //returning reagents for temporarily removed pets
394 //when dying/logging out
397 ////////////////////Rest System/////////////////////
404 rest_type
=REST_TYPE_NO
;
405 ////////////////////Rest System/////////////////////
407 m_mailsLoaded
= false;
408 m_mailsUpdated
= false;
410 m_nextMailDelivereTime
= 0;
412 m_resetTalentsCost
= 0;
413 m_resetTalentsTime
= 0;
414 m_itemUpdateQueueBlocked
= false;
416 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
417 m_forced_speed_changes
[i
] = 0;
421 /////////////////// Instance System /////////////////////
424 m_InstanceValid
= true;
425 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
429 for (int i
= 0; i
< BASEMOD_END
; ++i
)
431 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
432 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
435 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
436 m_baseRatingValue
[i
] = 0;
438 m_baseSpellDamage
= 0;
439 m_baseSpellHealing
= 0;
444 m_lastHonorUpdateTime
= time(NULL
);
453 //Default movement to run mode
454 m_unit_movement_flags
= 0;
459 m_bgAfkReportedTimer
= 0;
460 m_contestedPvPTimer
= 0;
462 m_declinedname
= NULL
;
471 CleanupsBeforeDelete();
473 // it must be unloaded already in PlayerLogout and accessed only for loggined player
476 // Note: buy back item already deleted from DB when player was saved
477 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
484 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
487 //all mailed items should be deleted, also all mail should be deallocated
488 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
491 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
492 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
494 delete PlayerTalkClass
;
498 m_transport
->RemovePassenger(this);
501 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
503 delete ItemSetEff
[x
];
505 // clean up player-instance binds, may unload some instance saves
506 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
507 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
508 itr
->second
.save
->RemovePlayer(this);
510 delete m_declinedname
;
514 void Player::CleanupsBeforeDelete()
516 if(m_uint32Values
) // only for fully created Object
519 DuelComplete(DUEL_INTERUPTED
);
521 Unit::CleanupsBeforeDelete();
524 bool Player::Create( uint32 guidlow
, const std::string
& name
, uint8 race
, uint8 class_
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
, uint8 outfitId
)
526 //FIXME: outfitId not used in player creating
528 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
532 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
535 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
539 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
545 SetMapId(info
->mapId
);
546 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
548 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
551 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
555 uint8 powertype
= cEntry
->powerType
;
557 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
558 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
563 SetDisplayId(info
->displayId_f
);
564 SetNativeDisplayId(info
->displayId_f
);
567 SetDisplayId(info
->displayId_m
);
568 SetNativeDisplayId(info
->displayId_m
);
571 sLog
.outError("Invalid gender %u for player",gender
);
576 setFactionForRace(m_race
);
578 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
580 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
581 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
582 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
583 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
584 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
585 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
587 // -1 is default value
588 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
590 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
591 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
592 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
594 SetUInt32Value( PLAYER_GUILDID
, 0 );
595 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
596 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
606 // set starting level
607 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
609 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
613 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
614 if(gm_level
> start_level
)
615 start_level
= gm_level
;
618 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
622 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
627 m_Last_tick
= time(NULL
);
628 m_Played_time
[0] = 0;
629 m_Played_time
[1] = 0;
631 // base stats and related field values
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProffesions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA
)
643 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
647 if(getPowerType() == POWER_RUNIC_POWER
)
649 SetPower(POWER_RUNE
, 8);
650 SetMaxPower(POWER_RUNE
, 8);
651 SetPower(POWER_RUNIC_POWER
, 0);
652 SetMaxPower(POWER_RUNIC_POWER
, 1000);
656 learnDefaultSpells();
658 // original action bar
659 std::list
<uint16
>::const_iterator action_itr
[4];
660 for(int i
=0; i
<4; ++i
)
661 action_itr
[i
] = info
->action
[i
].begin();
663 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
666 for(int i
=0; i
<4 ;++i
)
667 taction
[i
] = (*action_itr
[i
]);
669 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
671 for(int i
=0; i
<4 ;++i
)
676 CharStartOutfitEntry
const* oEntry
= NULL
;
677 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
679 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
681 if(entry
->RaceClassGender
== RaceClassGender
)
691 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
693 if(oEntry
->ItemId
[j
] <= 0)
696 uint32 item_id
= oEntry
->ItemId
[j
];
699 // Hack for not existed item id in dbc 3.0.3
703 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
706 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
713 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
715 switch(iProto
->Spells
[0].SpellCategory
)
718 if(iProto
->Stackable
> 4)
722 if(iProto
->Stackable
> 2)
728 StoreNewItemInBestSlots(item_id
, count
);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
733 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
740 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
745 if( msg
== EQUIP_ERR_OK
)
747 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
748 EquipItem( eDest
, pItem
, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
753 ItemPosCountVec sDest
;
754 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
755 if( msg
== EQUIP_ERR_OK
)
757 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
758 pItem
= StoreItem( sDest
, pItem
, true);
761 // if this is ammo then use it
762 msg
= CanUseAmmo( pItem
->GetEntry() );
763 if( msg
== EQUIP_ERR_OK
)
764 SetAmmo( pItem
->GetEntry() );
768 // all item positions resolved
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
775 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
777 // attempt equip by one
778 while(titem_amount
> 0)
781 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
782 if( msg
!= EQUIP_ERR_OK
)
785 EquipNewItem( eDest
, titem_id
, true);
786 AutoUnequipOffhandIfNeed();
790 if(titem_amount
== 0)
791 return true; // equipped
794 ItemPosCountVec sDest
;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
797 if( msg
== EQUIP_ERR_OK
)
799 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
800 return true; // stored
803 // item can't be added
804 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
808 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
810 if (MaxValue
== DISABLED_MIRROR_TIMER
)
812 if (CurrentValue
!=DISABLED_MIRROR_TIMER
)
813 StopMirrorTimer(Type
);
816 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
817 data
<< (uint32
)Type
;
818 data
<< CurrentValue
;
822 data
<< (uint32
)0; // spell id
823 GetSession()->SendPacket( &data
);
826 void Player::StopMirrorTimer(MirrorTimerType Type
)
828 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
829 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
830 data
<< (uint32
)Type
;
831 GetSession()->SendPacket( &data
);
834 void Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
836 if(!isAlive() || isGameMaster())
839 // Absorb, resist some environmental damage type
842 if (type
== DAMAGE_LAVA
)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
844 else if (type
== DAMAGE_SLIME
)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
847 damage
-=absorb
+resist
;
849 DealDamageMods(this,damage
,&absorb
);
851 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
852 data
<< uint64(GetGUID());
853 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
854 data
<< uint32(damage
);
855 data
<< uint32(absorb
);
856 data
<< uint32(resist
);
857 SendMessageToSet(&data
, true);
859 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
863 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
865 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
866 DurabilityLossAll(0.10f
,false);
867 // durability lost message
868 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
869 GetSession()->SendPacket(&data2
);
872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
876 int32
Player::getMaxTimer(MirrorTimerType timer
)
881 return MINUTE
*IN_MILISECONDS
;
884 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
885 return DISABLED_MIRROR_TIMER
;
886 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
887 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
888 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
889 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
890 return UnderWaterTime
;
895 return DISABLED_MIRROR_TIMER
;
896 return 1*IN_MILISECONDS
;
904 void Player::UpdateMirrorTimers()
906 // Desync flags for update on next HandleDrowning
907 if (m_MirrorTimerFlags
)
908 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
911 void Player::HandleDrowning(uint32 time_diff
)
913 if (!m_MirrorTimerFlags
)
917 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
919 // Breath timer not activated - activate it
920 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
922 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
923 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
925 else // If activated - do tick
927 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
928 // Timer limit - need deal damage
929 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
931 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
932 // Calculate and deal damage
933 // TODO: Check this formula
934 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
935 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
937 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
938 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
941 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
943 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
945 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
946 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
947 StopMirrorTimer(BREATH_TIMER
);
948 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
949 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
953 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
955 // Fatigue timer not activated - activate it
956 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
958 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
959 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
963 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
964 // Timer limit - need deal damage or teleport ghost to graveyard
965 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
967 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
968 if (isAlive()) // Calculate and deal damage
970 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
971 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
973 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
976 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
977 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
980 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
982 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
983 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
984 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
985 StopMirrorTimer(FATIGUE_TIMER
);
986 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
987 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
990 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
992 // Breath timer not activated - activate it
993 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
994 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
997 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
998 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
1000 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
1001 // Calculate and deal damage
1002 // TODO: Check this formula
1003 uint32 damage
= urand(600, 700);
1004 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1005 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1007 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1012 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1014 // Recheck timers flag
1015 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1016 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1017 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1019 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1022 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1025 ///The player sobers by 256 every 10 seconds
1026 void Player::HandleSobering()
1030 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1031 SetDrunkValue(drunk
);
1034 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1037 return DRUNKEN_SMASHED
;
1039 return DRUNKEN_DRUNK
;
1041 return DRUNKEN_TIPSY
;
1042 return DRUNKEN_SOBER
;
1045 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1047 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1049 m_drunk
= newDrunkenValue
;
1050 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1052 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1054 // special drunk invisibility detection
1055 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1056 m_detectInvisibilityMask
|= (1<<6);
1058 m_detectInvisibilityMask
&= ~(1<<6);
1060 if(newDrunkenState
== oldDrunkenState
)
1063 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1064 data
<< uint64(GetGUID());
1065 data
<< uint32(newDrunkenState
);
1066 data
<< uint32(itemId
);
1068 SendMessageToSet(&data
, true);
1071 void Player::Update( uint32 p_time
)
1077 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1082 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1083 m_nextMailDelivereTime
= 0;
1086 Unit::Update( p_time
);
1088 // update player only attacks
1089 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1091 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1094 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1096 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1099 time_t now
= time (NULL
);
1103 UpdateContestedPvP(p_time
);
1105 UpdateDuelFlag(now
);
1107 CheckDuelDistance(now
);
1109 UpdateAfkReport(now
);
1111 // Update items that have just a limited lifetime
1112 if (now
>m_Last_tick
)
1113 UpdateItemDuration(uint32(now
- m_Last_tick
));
1115 if (!m_timedquests
.empty())
1117 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1118 while (iter
!= m_timedquests
.end())
1120 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1121 if( q_status
.m_timer
<= p_time
)
1123 uint32 quest_id
= *iter
;
1124 ++iter
; // current iter will be removed in FailTimedQuest
1125 FailTimedQuest( quest_id
);
1129 q_status
.m_timer
-= p_time
;
1130 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1136 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1138 Unit
*pVictim
= getVictim();
1139 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1141 // default combat reach 10
1142 // TODO add weapon,skill check
1144 float pldistance
= ATTACK_DISTANCE
;
1146 if (isAttackReady(BASE_ATTACK
))
1148 if(!IsWithinDistInMap(pVictim
, pldistance
))
1150 setAttackTimer(BASE_ATTACK
,100);
1151 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1153 SendAttackSwingNotInRange();
1154 m_swingErrorMsg
= 1;
1157 //120 degrees of radiant range
1158 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1160 setAttackTimer(BASE_ATTACK
,100);
1161 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1163 SendAttackSwingBadFacingAttack();
1164 m_swingErrorMsg
= 2;
1169 m_swingErrorMsg
= 0; // reset swing error state
1171 // prevent base and off attack in same time, delay attack at 0.2 sec
1172 if(haveOffhandWeapon())
1174 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1175 if(off_att
< ATTACK_DISPLAY_DELAY
)
1176 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1178 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1179 resetAttackTimer(BASE_ATTACK
);
1183 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1185 if(!IsWithinDistInMap(pVictim
, pldistance
))
1187 setAttackTimer(OFF_ATTACK
,100);
1189 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1191 setAttackTimer(OFF_ATTACK
,100);
1195 // prevent base and off attack in same time, delay attack at 0.2 sec
1196 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1197 if(base_att
< ATTACK_DISPLAY_DELAY
)
1198 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1200 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1201 resetAttackTimer(OFF_ATTACK
);
1205 Unit
*owner
= pVictim
->GetOwner();
1206 Unit
*u
= owner
? owner
: pVictim
;
1207 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1215 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1217 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1219 int time_inn
= time(NULL
)-GetTimeInnEnter();
1220 if (time_inn
>= 10) //freeze update
1222 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1223 //speed collect rest bonus (section/in hour)
1224 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1225 UpdateInnerTime(time(NULL
));
1230 if(m_regenTimer
> 0)
1232 if(p_time
>= m_regenTimer
)
1235 m_regenTimer
-= p_time
;
1238 if (m_weaponChangeTimer
> 0)
1240 if(p_time
>= m_weaponChangeTimer
)
1241 m_weaponChangeTimer
= 0;
1243 m_weaponChangeTimer
-= p_time
;
1246 if (m_zoneUpdateTimer
> 0)
1248 if(p_time
>= m_zoneUpdateTimer
)
1250 uint32 newzone
, newarea
;
1251 GetZoneAndAreaId(newzone
,newarea
);
1253 if( m_zoneUpdateId
!= newzone
)
1254 UpdateZone(newzone
,newarea
); // also update area
1257 // use area updates as well
1258 // needed for free far all arenas for example
1259 if( m_areaUpdateId
!= newarea
)
1260 UpdateArea(newarea
);
1262 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1266 m_zoneUpdateTimer
-= p_time
;
1274 if (m_deathState
== JUST_DIED
)
1281 if(p_time
>= m_nextSave
)
1283 // m_nextSave reseted in SaveToDB call
1285 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1289 m_nextSave
-= p_time
;
1293 //Handle Water/drowning
1294 HandleDrowning(p_time
);
1296 //Handle detect stealth players
1297 if (m_DetectInvTimer
> 0)
1299 if (p_time
>= m_DetectInvTimer
)
1301 m_DetectInvTimer
= 3000;
1302 HandleStealthedUnitsDetection();
1305 m_DetectInvTimer
-= p_time
;
1309 if (now
> m_Last_tick
)
1311 uint32 elapsed
= uint32(now
- m_Last_tick
);
1312 m_Played_time
[0] += elapsed
; // Total played time
1313 m_Played_time
[1] += elapsed
; // Level played time
1319 m_drunkTimer
+= p_time
;
1321 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1325 // not auto-free ghost from body in instances
1326 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1328 if(p_time
>= m_deathTimer
)
1335 m_deathTimer
-= p_time
;
1338 UpdateEnchantTime(p_time
);
1339 UpdateHomebindTime(p_time
);
1342 SendUpdateToOutOfRangeGroupMembers();
1344 Pet
* pet
= GetPet();
1345 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1347 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1352 void Player::setDeathState(DeathState s
)
1354 uint32 ressSpellId
= 0;
1356 bool cur
= isAlive();
1358 if(s
== JUST_DIED
&& cur
)
1360 // drunken state is cleared on death
1362 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1365 clearResurrectRequestData();
1367 // remove form before other mods to prevent incorrect stats calculation
1368 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1370 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1371 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1373 // remove uncontrolled pets
1377 // save value before aura remove in Unit::setDeathState
1378 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1382 ressSpellId
= GetResurrectionSpellId();
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1384 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1385 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1387 Unit::setDeathState(s
);
1389 // restore resurrection spell id for player after aura remove
1390 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1391 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1393 if(isAlive() && !cur
)
1395 //clear aura case after resurrection by another way (spells will be applied before next death)
1396 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1398 // restore default warrior stance
1399 if(getClass()== CLASS_WARRIOR
)
1400 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1404 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1406 Field
*fields
= result
->Fetch();
1408 *p_data
<< uint64(GetGUID());
1411 *p_data
<< uint8(getRace());
1412 uint8 pClass
= getClass();
1413 *p_data
<< uint8(pClass
);
1414 *p_data
<< uint8(getGender());
1416 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1417 *p_data
<< uint8(bytes
);
1418 *p_data
<< uint8(bytes
>> 8);
1419 *p_data
<< uint8(bytes
>> 16);
1420 *p_data
<< uint8(bytes
>> 24);
1422 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1423 *p_data
<< uint8(bytes
);
1425 *p_data
<< uint8(getLevel()); // player level
1426 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1427 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1428 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1429 *p_data
<< uint32(zoneId
);
1430 *p_data
<< uint32(GetMapId());
1432 *p_data
<< GetPositionX();
1433 *p_data
<< GetPositionY();
1434 *p_data
<< GetPositionZ();
1437 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1439 uint32 char_flags
= 0;
1440 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1441 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1442 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1443 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1444 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1445 char_flags
|= CHARACTER_FLAG_GHOST
;
1446 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1447 char_flags
|= CHARACTER_FLAG_RENAME
;
1448 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1449 char_flags
|= CHARACTER_FLAG_DECLINED
;
1451 *p_data
<< uint32(char_flags
); // character flags
1452 // character customize (flags?)
1453 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1454 *p_data
<< uint8(1); // unknown
1458 uint32 petDisplayId
= 0;
1459 uint32 petLevel
= 0;
1460 uint32 petFamily
= 0;
1462 // show pet at selection character in character list only for non-ghost character
1463 if (result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
|| pClass
== CLASS_DEATH_KNIGHT
))
1465 uint32 entry
= fields
[10].GetUInt32();
1466 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1469 petDisplayId
= fields
[11].GetUInt32();
1470 petLevel
= fields
[12].GetUInt32();
1471 petFamily
= cInfo
->family
;
1475 *p_data
<< uint32(petDisplayId
);
1476 *p_data
<< uint32(petLevel
);
1477 *p_data
<< uint32(petFamily
);
1480 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1482 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1483 uint32 item_id
= GetUInt32Value(visualbase
);
1484 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1485 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1487 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1489 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1490 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1496 *p_data
<< uint32(proto
->DisplayInfoID
);
1497 *p_data
<< uint8(proto
->InventoryType
);
1498 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1502 *p_data
<< uint32(0);
1503 *p_data
<< uint8(0);
1504 *p_data
<< uint32(0); // enchant?
1507 *p_data
<< uint32(0); // first bag display id
1508 *p_data
<< uint8(0); // first bag inventory type
1509 *p_data
<< uint32(0); // enchant?
1512 bool Player::ToggleAFK()
1514 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1516 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1518 // afk player not allowed in battleground
1519 if(state
&& InBattleGround())
1520 LeaveBattleground();
1525 bool Player::ToggleDND()
1527 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1529 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1532 uint8
Player::chatTag() const
1549 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1551 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1553 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1557 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1558 Pet
* pet
= GetPet();
1560 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1562 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1563 // don't let gm level > 1 either
1564 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1567 // client without expansion support
1568 if(GetSession()->Expansion() < mEntry
->Expansion())
1570 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1573 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1575 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1577 return false; // normal client can't teleport to this map...
1581 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1584 // if we were on a transport, leave
1585 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1587 m_transport
->RemovePassenger(this);
1589 m_movementInfo
.t_x
= 0.0f
;
1590 m_movementInfo
.t_y
= 0.0f
;
1591 m_movementInfo
.t_z
= 0.0f
;
1592 m_movementInfo
.t_o
= 0.0f
;
1593 m_movementInfo
.t_time
= 0;
1596 // The player was ported to another map and looses the duel immediately.
1597 // We have to perform this check before the teleport, otherwise the
1598 // ObjectAccessor won't find the flag.
1599 if (duel
&& GetMapId()!=mapid
)
1601 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1603 DuelComplete(DUEL_FLED
);
1606 // reset movement flags at teleport, because player will continue move with these flags after teleport
1607 SetUnitMovementFlags(0);
1609 if ((GetMapId() == mapid
) && (!m_transport
))
1611 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1613 //same map, only remove pet if out of range for new position
1614 if(pet
&& pet
->GetDistance(x
,y
,z
) >= OWNER_MAX_DISTANCE
)
1615 UnsummonPetTemporaryIfAny();
1618 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1621 // this will be used instead of the current location in SaveToDB
1622 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1623 SetFallInformation(0, z
);
1625 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1626 // at client packet MSG_MOVE_TELEPORT_ACK
1627 SetSemaphoreTeleportNear(true);
1628 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1629 if(!GetSession()->PlayerLogout())
1632 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1633 GetSession()->SendPacket(&data
);
1638 // far teleport to another map
1639 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1640 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1642 // Check enter rights before map getting to avoid creating instance copy for player
1643 // this check not dependent from map instance copy and same for all instance copies of selected map
1644 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1647 // If the map is not created, assume it is possible to enter it.
1648 // It will be created in the WorldPortAck.
1649 Map
*map
= MapManager::Instance().FindMap(mapid
);
1650 if (!map
|| map
->CanEnter(this))
1656 ResetContestedPvP();
1658 // remove player from battleground on far teleport (when changing maps)
1659 if(BattleGround
const* bg
= GetBattleGround())
1661 // Note: at battleground join battleground id set before teleport
1662 // and we already will found "current" battleground
1663 // just need check that this is targeted map or leave
1664 if(bg
->GetMapId() != mapid
)
1665 LeaveBattleground(false); // don't teleport to entry point
1668 // remove pet on map change
1670 UnsummonPetTemporaryIfAny();
1672 // remove all dyn objects
1673 RemoveAllDynObjects();
1675 // stop spellcasting
1676 // not attempt interrupt teleportation spell at caster teleport
1677 if(!(options
& TELE_TO_SPELL
))
1678 if(IsNonMeleeSpellCasted(true))
1679 InterruptNonMeleeSpells(true);
1681 if(!GetSession()->PlayerLogout())
1683 // send transfer packets
1684 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1685 data
<< uint32(mapid
);
1688 data
<< m_transport
->GetEntry() << GetMapId();
1690 GetSession()->SendPacket(&data
);
1692 data
.Initialize(SMSG_NEW_WORLD
, (20));
1695 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1699 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1701 GetSession()->SendPacket( &data
);
1702 SendSavedInstances();
1704 // remove from old map now
1705 if(oldmap
) oldmap
->Remove(this, false);
1708 // new final coordinates
1712 float final_o
= orientation
;
1716 final_x
+= m_movementInfo
.t_x
;
1717 final_y
+= m_movementInfo
.t_y
;
1718 final_z
+= m_movementInfo
.t_z
;
1719 final_o
+= m_movementInfo
.t_o
;
1722 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1723 SetFallInformation(0, final_z
);
1724 // if the player is saved before worldportack (at logout for example)
1725 // this will be used instead of the current location in SaveToDB
1727 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1729 // move packet sent by client always after far teleport
1730 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1731 SetSemaphoreTeleportFar(true);
1739 void Player::AddToWorld()
1741 ///- Do not add/remove the player from the object storage
1742 ///- It will crash when updating the ObjectAccessor
1743 ///- The player should only be added when logging in
1746 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1749 m_items
[i
]->AddToWorld();
1753 void Player::RemoveFromWorld()
1758 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1760 UnsummonAllTotems();
1765 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1768 m_items
[i
]->RemoveFromWorld();
1771 ///- Do not add/remove the player from the object storage
1772 ///- It will crash when updating the ObjectAccessor
1773 ///- The player should only be removed when logging out
1774 Unit::RemoveFromWorld();
1777 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1781 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1785 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1787 // talent who gave more rage on attack
1788 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1792 addRage
= damage
/rageconversion
*2.5;
1794 // Berserker Rage effect
1795 if(HasAura(18499,0))
1799 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1801 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1804 void Player::RegenerateAll()
1806 if (m_regenTimer
!= 0)
1808 uint32 regenDelay
= 2000;
1810 // Not in combat or they have regeneration
1811 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1812 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1815 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1817 Regenerate(POWER_RAGE
);
1818 if(getClass() == CLASS_DEATH_KNIGHT
)
1819 Regenerate(POWER_RUNIC_POWER
);
1823 Regenerate( POWER_ENERGY
);
1825 Regenerate( POWER_MANA
);
1827 if(getClass() == CLASS_DEATH_KNIGHT
)
1828 Regenerate( POWER_RUNE
);
1830 m_regenTimer
= regenDelay
;
1833 void Player::Regenerate(Powers power
)
1835 uint32 curValue
= GetPower(power
);
1836 uint32 maxValue
= GetMaxPower(power
);
1838 float addvalue
= 0.0f
;
1844 bool recentCast
= IsUnderLastManaUseEffect();
1845 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1848 // Mangos Updates Mana in intervals of 2s, which is correct
1849 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1853 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1856 case POWER_RAGE
: // Regenerate rage
1858 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1859 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1861 case POWER_ENERGY
: // Regenerate energy (rogue)
1864 case POWER_RUNIC_POWER
:
1866 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1867 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1871 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1872 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1873 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1876 case POWER_HAPPINESS
:
1881 // Mana regen calculated in Player::UpdateManaRegen()
1882 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1883 if(power
!= POWER_MANA
)
1885 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1886 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1887 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1888 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1891 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1893 curValue
+= uint32(addvalue
);
1894 if (curValue
> maxValue
)
1895 curValue
= maxValue
;
1899 if(curValue
<= uint32(addvalue
))
1902 curValue
-= uint32(addvalue
);
1904 SetPower(power
, curValue
);
1907 void Player::RegenerateHealth()
1909 uint32 curValue
= GetHealth();
1910 uint32 maxValue
= GetMaxHealth();
1912 if (curValue
>= maxValue
) return;
1914 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1916 float addvalue
= 0.0f
;
1919 if ( IsPolymorphed() )
1920 addvalue
= GetMaxHealth()/3;
1921 // normal regen case (maybe partly in combat case)
1922 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1924 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1927 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1928 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1929 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1931 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1932 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1938 // always regeneration bonus (including combat)
1939 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1944 ModifyHealth(int32(addvalue
));
1947 bool Player::CanInteractWithNPCs(bool alive
) const
1949 if(alive
&& !isAlive())
1958 Player::GetNPCIfCanInteractWith(uint64 guid
, uint32 npcflagmask
)
1967 // exist (we need look pets also for some interaction (quest/etc)
1968 Creature
*unit
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
1973 if(!CanInteractWithNPCs(!unit
->isSpiritService()))
1976 // appropriate npc type
1977 if(npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
1980 // alive or spirit healer
1981 if(!unit
->isAlive() && (!unit
->isSpiritService() || isAlive() ))
1984 // not allow interaction under control, but allow with own pets
1985 if(unit
->GetCharmerGUID())
1989 if( unit
->IsHostileTo(this))
1993 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
1994 if(factionTemplate
->faction
)
1995 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
1996 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
2000 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2006 GameObject
* Player::GetGameObjectIfCanInteractWith(uint64 guid
, GameobjectTypes type
) const
2008 if(GameObject
*go
= GetMap()->GetGameObject(guid
))
2010 if(go
->GetGoType() == type
)
2015 // TODO: find out how the client calculates the maximal usage distance to spellless working
2016 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2017 case GAMEOBJECT_TYPE_GUILD_BANK
:
2018 case GAMEOBJECT_TYPE_MAILBOX
:
2021 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2022 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2025 maxdist
= INTERACTION_DISTANCE
;
2029 if (go
->IsWithinDistInMap(this, maxdist
))
2032 sLog
.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go
->GetGOInfo()->name
,
2033 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2039 bool Player::IsUnderWater() const
2041 return IsInWater() &&
2042 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2045 void Player::SetInWater(bool apply
)
2047 if(m_isInWater
==apply
)
2050 //define player in water by opcodes
2051 //move player's guid into HateOfflineList of those mobs
2052 //which can't swim and move guid back into ThreatList when
2054 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2055 m_isInWater
= apply
;
2057 // remove auras that need water/land
2058 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2060 getHostilRefManager().updateThreatTables();
2063 void Player::SetGameMaster(bool on
)
2067 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2069 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2071 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2072 ResetContestedPvP();
2074 getHostilRefManager().setOnlineOfflineState(false);
2077 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2082 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2083 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2085 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2086 setFactionForRace(getRace());
2087 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2089 // restore FFA PvP Server state
2090 if(sWorld
.IsFFAPvPRealm())
2091 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2093 // restore FFA PvP area state, remove not allowed for GM mounts
2094 UpdateArea(m_areaUpdateId
);
2096 getHostilRefManager().setOnlineOfflineState(true);
2099 ObjectAccessor::UpdateVisibilityForPlayer(this);
2102 void Player::SetGMVisible(bool on
)
2106 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2108 // Reapply stealth/invisibility if active or show if not any
2109 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2110 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2111 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2112 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2114 SetVisibility(VISIBILITY_ON
);
2118 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2120 SetAcceptWhispers(false);
2121 SetGameMaster(true);
2123 SetVisibility(VISIBILITY_OFF
);
2127 bool Player::IsGroupVisibleFor(Player
* p
) const
2129 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2131 default: return IsInSameGroupWith(p
);
2132 case 1: return IsInSameRaidWith(p
);
2133 case 2: return GetTeam()==p
->GetTeam();
2137 bool Player::IsInSameGroupWith(Player
const* p
) const
2139 return p
==this || GetGroup() != NULL
&&
2140 GetGroup() == p
->GetGroup() &&
2141 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2144 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2145 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2146 void Player::UninviteFromGroup()
2148 Group
* group
= GetGroupInvite();
2152 group
->RemoveInvite(this);
2154 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2156 if(group
->IsCreated())
2158 group
->Disband(true);
2159 objmgr
.RemoveGroup(group
);
2162 group
->RemoveAllInvites();
2168 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2172 if (group
->RemoveMember(guid
, 0) <= 1)
2174 // group->Disband(); already disbanded in RemoveMember
2175 objmgr
.RemoveGroup(group
);
2177 // removemember sets the player's group pointer to NULL
2182 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2184 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2185 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2186 data
<< uint32(GivenXP
+RestXP
); // given experience
2187 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2190 data
<< uint32(GivenXP
); // experience without rested bonus
2191 data
<< float(1); // 1 - none 0 - 100% group bonus output
2193 data
<< uint8(0); // new 2.4.0
2194 GetSession()->SendPacket(&data
);
2197 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2205 uint32 level
= getLevel();
2207 // XP to money conversion processed in Player::RewardQuest
2208 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2211 // handle SPELL_AURA_MOD_XP_PCT auras
2212 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2213 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2214 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2216 // XP resting bonus for kill
2217 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2219 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2221 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2222 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2223 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2225 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2229 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2230 GiveLevel(level
+ 1);
2233 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2236 SetUInt32Value(PLAYER_XP
, newXP
);
2239 // Update player to next level
2240 // Current player experience not update (must be update by caller)
2241 void Player::GiveLevel(uint32 level
)
2243 if ( level
== getLevel() )
2246 PlayerLevelInfo info
;
2247 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2249 PlayerClassLevelInfo classInfo
;
2250 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2252 // send levelup info to client
2253 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2254 data
<< uint32(level
);
2255 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2256 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2257 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2265 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2266 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2268 GetSession()->SendPacket(&data
);
2270 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2272 //update level, max level of skills
2273 if(getLevel()!= level
)
2274 m_Played_time
[1] = 0; // Level Played Time reset
2276 UpdateSkillsForLevel ();
2278 // save base values (bonuses already included in stored stats
2279 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2280 SetCreateStat(Stats(i
), info
.stats
[i
]);
2282 SetCreateHealth(classInfo
.basehealth
);
2283 SetCreateMana(classInfo
.basemana
);
2285 InitTalentForLevel();
2286 InitTaxiNodesForLevel();
2287 InitGlyphsForLevel();
2291 // set current level health and mana/energy to maximum after applying all mods.
2292 SetHealth(GetMaxHealth());
2293 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2294 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2295 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2296 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2297 SetPower(POWER_FOCUS
, 0);
2298 SetPower(POWER_HAPPINESS
, 0);
2300 // give level to summoned pet
2301 Pet
* pet
= GetPet();
2302 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2303 pet
->GivePetLevel(level
);
2304 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2307 void Player::InitTalentForLevel()
2309 uint32 level
= getLevel();
2310 // talents base at level diff ( talents = level - 9 but some can be used already)
2313 // Remove all talent points
2314 if(m_usedTalentCount
> 0) // Free any used talents
2317 SetFreeTalentPoints(0);
2322 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2324 // if used more that have then reset
2325 if(m_usedTalentCount
> talentPointsForLevel
)
2327 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2330 SetFreeTalentPoints(0);
2332 // else update amount of free points
2334 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2338 void Player::InitStatsForLevel(bool reapplyMods
)
2340 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2341 _RemoveAllStatBonuses();
2343 PlayerClassLevelInfo classInfo
;
2344 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2346 PlayerLevelInfo info
;
2347 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2349 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2350 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2352 UpdateSkillsForLevel ();
2354 // set default cast time multiplier
2355 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2357 // reset size before reapply auras
2358 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2360 // save base values (bonuses already included in stored stats
2361 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2362 SetCreateStat(Stats(i
), info
.stats
[i
]);
2364 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2365 SetStat(Stats(i
), info
.stats
[i
]);
2367 SetCreateHealth(classInfo
.basehealth
);
2370 SetCreateMana(classInfo
.basemana
);
2372 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2376 //reset rating fields values
2377 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2378 SetUInt32Value(index
, 0);
2380 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2381 for (int i
= 0; i
< 7; ++i
)
2383 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2384 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2385 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2388 //reset attack power, damage and attack speed fields
2389 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2390 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2391 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2393 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2394 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2395 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2396 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2397 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2398 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2400 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2401 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2402 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2403 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2404 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2405 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2407 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2408 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2409 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2410 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2412 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2413 for (uint8 i
= 0; i
< 7; ++i
)
2414 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2416 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2417 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2418 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2421 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2423 // set armor (resistance 0) to original value (create_agility*2)
2424 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2425 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2426 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2427 // set other resistance to original value (0)
2428 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2430 SetResistance(SpellSchools(i
), 0);
2431 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2432 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2435 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2436 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2437 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2439 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2440 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2442 // Reset no reagent cost field
2443 for(int i
= 0; i
< 3; ++i
)
2444 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2445 // Init data for form but skip reapply item mods for form
2446 InitDataForForm(reapplyMods
);
2449 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2450 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2452 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2454 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2455 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2457 // cleanup unit flags (will be re-applied if need at aura load).
2458 RemoveFlag( UNIT_FIELD_FLAGS
,
2459 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2460 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2461 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2462 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2463 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2464 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2466 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2468 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2469 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2471 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2472 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2474 // restore if need some important flags
2475 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2477 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2478 _ApplyAllStatBonuses();
2480 // set current level health and mana/energy to maximum after applying all mods.
2481 SetHealth(GetMaxHealth());
2482 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2483 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2484 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2485 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2486 SetPower(POWER_FOCUS
, 0);
2487 SetPower(POWER_HAPPINESS
, 0);
2488 SetPower(POWER_RUNIC_POWER
, 0);
2491 void Player::SendInitialSpells()
2493 time_t curTime
= time(NULL
);
2494 time_t infTime
= curTime
+ MONTH
/2;
2496 uint16 spellCount
= 0;
2498 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2501 size_t countPos
= data
.wpos();
2502 data
<< uint16(spellCount
); // spell count placeholder
2504 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2506 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2509 if(!itr
->second
->active
|| itr
->second
->disabled
)
2512 data
<< uint16(itr
->first
);
2513 data
<< uint16(0); // it's not slot id
2518 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2520 uint16 spellCooldowns
= m_spellCooldowns
.size();
2521 data
<< uint16(spellCooldowns
);
2522 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2524 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2528 // not send infinity cooldown
2529 if(itr
->second
.end
> infTime
)
2532 data
<< uint16(itr
->first
);
2534 time_t cooldown
= 0;
2535 if(itr
->second
.end
> curTime
)
2536 cooldown
= (itr
->second
.end
-curTime
)*IN_MILISECONDS
;
2538 data
<< uint16(itr
->second
.itemid
); // cast item id
2539 data
<< uint16(sEntry
->Category
); // spell category
2540 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2542 data
<< uint32(0); // cooldown
2543 data
<< uint32(cooldown
); // category cooldown
2547 data
<< uint32(cooldown
); // cooldown
2548 data
<< uint32(0); // category cooldown
2552 GetSession()->SendPacket(&data
);
2554 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2557 void Player::RemoveMail(uint32 id
)
2559 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2561 if ((*itr
)->messageID
== id
)
2563 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2570 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2572 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2573 data
<< (uint32
) mailId
;
2574 data
<< (uint32
) mailAction
;
2575 data
<< (uint32
) mailError
;
2576 if ( mailError
== MAIL_ERR_BAG_FULL
)
2577 data
<< (uint32
) equipError
;
2578 else if( mailAction
== MAIL_ITEM_TAKEN
)
2580 data
<< (uint32
) item_guid
; // item guid low?
2581 data
<< (uint32
) item_count
; // item count?
2583 GetSession()->SendPacket(&data
);
2586 void Player::SendNewMail()
2588 // deliver undelivered mail
2589 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2591 GetSession()->SendPacket(&data
);
2594 void Player::UpdateNextMailTimeAndUnreads()
2596 // calculate next delivery time (min. from non-delivered mails
2597 // and recalculate unReadMail
2598 time_t cTime
= time(NULL
);
2599 m_nextMailDelivereTime
= 0;
2601 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2603 if((*itr
)->deliver_time
> cTime
)
2605 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2606 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2608 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2613 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2615 if(deliver_time
<= time(NULL
)) // ready now
2620 else // not ready and no have ready mails
2622 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2623 m_nextMailDelivereTime
= deliver_time
;
2627 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2629 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2632 // do character spell book cleanup (all characters)
2633 if(!IsInWorld() && !learning
) // spell load case
2635 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2636 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2639 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2644 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2646 // do character spell book cleanup (all characters)
2647 if(!IsInWorld() && !learning
) // spell load case
2649 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2650 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2653 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2658 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2660 bool dependent_set
= false;
2661 bool disabled_case
= false;
2662 bool superceded_old
= false;
2664 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2665 if (itr
!= m_spells
.end())
2667 uint32 next_active_spell_id
= 0;
2668 // fix activate state for non-stackable low rank (and find next spell for !active case)
2669 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2671 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2672 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2674 if(HasSpell(next_itr
->second
))
2676 // high rank already known so this must !active
2678 next_active_spell_id
= next_itr
->second
;
2684 // not do anything if already known in expected state
2685 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2686 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2688 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2689 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2694 // dependent spell known as not dependent, overwrite state
2695 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2697 itr
->second
->dependent
= dependent
;
2698 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2699 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2700 dependent_set
= true;
2703 // update active state for known spell
2704 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2706 itr
->second
->active
= active
;
2708 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2709 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2710 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2711 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2715 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2716 CastSpell (this,spell_id
,true);
2718 else if(IsInWorld())
2720 if(next_active_spell_id
)
2722 // update spell ranks in spellbook and action bar
2723 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2724 data
<< uint16(spell_id
);
2725 data
<< uint16(next_active_spell_id
);
2726 GetSession()->SendPacket( &data
);
2730 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2731 data
<< uint16(spell_id
);
2732 GetSession()->SendPacket(&data
);
2736 return active
; // learn (show in spell book if active now)
2739 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2741 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2742 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2743 itr
->second
->disabled
= disabled
;
2748 disabled_case
= true;
2750 else switch(itr
->second
->state
)
2752 case PLAYERSPELL_UNCHANGED
: // known saved spell
2754 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2757 m_spells
.erase(itr
);
2758 state
= PLAYERSPELL_CHANGED
;
2759 break; // need re-add
2761 default: // known not saved yet spell (new or modified)
2763 // can be in case spell loading but learned at some previous spell loading
2764 if(!IsInWorld() && !learning
&& !dependent_set
)
2765 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2772 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2774 // talent: unlearn all other talent ranks (high and low)
2775 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2777 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2779 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
2781 // skip learning spell and no rank spell case
2782 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2783 if(!rankSpellId
|| rankSpellId
==spell_id
)
2786 removeSpell(rankSpellId
);
2790 // non talent spell: learn low ranks (recursive call)
2791 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2793 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2794 addSpell(prev_spell
,active
,true,true,disabled
);
2795 else // at normal learning
2796 learnSpell(prev_spell
,true);
2799 PlayerSpell
*newspell
= new PlayerSpell
;
2800 newspell
->state
= state
;
2801 newspell
->active
= active
;
2802 newspell
->dependent
= dependent
;
2803 newspell
->disabled
= disabled
;
2805 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2806 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2808 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
2810 if(itr2
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2811 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
2812 if(!i_spellInfo
) continue;
2814 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
2816 if(itr2
->second
->active
)
2818 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
2820 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2822 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2823 data
<< uint16(itr2
->first
);
2824 data
<< uint16(spell_id
);
2825 GetSession()->SendPacket( &data
);
2828 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2829 itr2
->second
->active
= false;
2830 if(itr2
->second
->state
!= PLAYERSPELL_NEW
)
2831 itr2
->second
->state
= PLAYERSPELL_CHANGED
;
2832 superceded_old
= true; // new spell replace old in action bars and spell book.
2834 else if(spellmgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
2836 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2838 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2839 data
<< uint16(spell_id
);
2840 data
<< uint16(itr2
->first
);
2841 GetSession()->SendPacket( &data
);
2844 // mark new spell as disable (not learned yet for client and will not learned)
2845 newspell
->active
= false;
2846 if(newspell
->state
!= PLAYERSPELL_NEW
)
2847 newspell
->state
= PLAYERSPELL_CHANGED
;
2854 m_spells
[spell_id
] = newspell
;
2856 // return false if spell disabled
2857 if (newspell
->disabled
)
2861 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2863 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2864 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2865 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2867 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2868 CastSpell(this, spell_id
, true);
2870 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2871 else if (IsPassiveSpell(spell_id
))
2873 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2874 CastSpell(this, spell_id
, true);
2876 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2878 CastSpell(this, spell_id
, true);
2882 // update used talent points count
2883 m_usedTalentCount
+= talentCost
;
2885 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2886 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2888 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2889 SetFreePrimaryProffesions(freeProfs
-1);
2892 // add dependent skills
2893 uint16 maxskill
= GetMaxSkillValueForLevel();
2895 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2897 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2898 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2902 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2903 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2905 if(skill_value
< spellLearnSkill
->value
)
2906 skill_value
= spellLearnSkill
->value
;
2908 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2910 if(skill_max_value
< new_skill_max_value
)
2911 skill_max_value
= new_skill_max_value
;
2913 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2917 // not ranked skills
2918 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2920 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2924 if(HasSkill(pSkill
->id
))
2927 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2928 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2929 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
2931 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2933 case SKILL_RANGE_LANGUAGE
:
2934 SetSkill(pSkill
->id
, 300, 300 );
2936 case SKILL_RANGE_LEVEL
:
2937 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2939 case SKILL_RANGE_MONO
:
2940 SetSkill(pSkill
->id
, 1, 1 );
2949 // learn dependent spells
2950 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2951 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2953 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2955 if(!itr2
->second
.autoLearned
)
2957 if(!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
2958 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
2959 else // at normal learning
2960 learnSpell(itr2
->second
.spell
,true);
2964 if(!GetSession()->PlayerLoading())
2966 // not ranked skills
2967 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2969 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
2970 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
2973 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
2976 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2977 return active
&& !disabled
&& !superceded_old
;
2980 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2982 bool need_cast
= false;
2984 switch(spellInfo
->Id
)
2986 // some spells not have stance data expacted cast at form change or present
2987 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2988 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2989 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2990 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2991 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2992 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2993 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2994 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2995 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2996 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2997 // another spells have proper stance data
2998 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
3001 //Check CasterAuraStates
3002 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3005 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3007 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3009 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
3010 bool active
= disabled
? itr
->second
->active
: true;
3012 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3014 // learn all disabled higher ranks (recursive)
3017 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3018 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3020 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3021 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
3022 learnSpell(i
->second
,false);
3026 // prevent duplicated entires in spell book, also not send if not in world (loading)
3027 if(!learning
|| !IsInWorld ())
3030 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3031 data
<< uint32(spell_id
);
3032 GetSession()->SendPacket(&data
);
3035 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
3037 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3038 if (itr
== m_spells
.end())
3041 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
3044 // unlearn non talent higher ranks (recursive)
3045 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3046 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3047 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3048 removeSpell(itr2
->second
,disabled
);
3050 bool cur_active
= itr
->second
->active
;
3051 bool cur_dependent
= itr
->second
->dependent
;
3055 itr
->second
->disabled
= disabled
;
3056 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3057 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3061 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3064 m_spells
.erase(itr
);
3067 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3070 RemoveAurasDueToSpell(spell_id
);
3073 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
3074 RemovePetAura(petSpell
);
3076 // free talent points
3077 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3080 if(talentCosts
< m_usedTalentCount
)
3081 m_usedTalentCount
-= talentCosts
;
3083 m_usedTalentCount
= 0;
3086 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3087 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3089 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
3090 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3091 SetFreePrimaryProffesions(freeProfs
);
3094 // remove dependent skill
3095 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3098 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3099 if(!prev_spell
) // first rank, remove skill
3100 SetSkill(spellLearnSkill
->skill
,0,0);
3103 // search prev. skill setting by spell ranks chain
3104 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3105 while(!prevSkill
&& prev_spell
)
3107 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3108 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3111 if(!prevSkill
) // not found prev skill setting, remove skill
3112 SetSkill(spellLearnSkill
->skill
,0,0);
3113 else // set to prev. skill setting values
3115 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3116 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3118 if(skill_value
> prevSkill
->value
)
3119 skill_value
= prevSkill
->value
;
3121 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3123 if(skill_max_value
> new_skill_max_value
)
3124 skill_max_value
= new_skill_max_value
;
3126 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3133 // not ranked skills
3134 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3135 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3137 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3139 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3143 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3144 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3145 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
3147 // not reset skills for professions and racial abilities
3148 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3149 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3152 SetSkill(pSkill
->id
, 0, 0 );
3157 // remove dependent spells
3158 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3159 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3161 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3162 removeSpell(itr2
->second
.spell
, disabled
);
3164 // activate lesser rank in spellbook/action bar, and cast it if need
3165 bool prev_activate
= false;
3167 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3169 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3171 // if talent then lesser rank also talent and need learn
3173 learnSpell (prev_id
,false);
3174 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3175 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3177 // need manually update dependence state (learn spell ignore like attempts)
3178 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3179 if (prev_itr
!= m_spells
.end())
3181 if(prev_itr
->second
->dependent
!= cur_dependent
)
3183 prev_itr
->second
->dependent
= cur_dependent
;
3184 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3185 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3188 // now re-learn if need re-activate
3189 if(cur_active
&& !prev_itr
->second
->active
)
3191 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3193 if(update_action_bar_for_low_rank
)
3195 // downgrade spell ranks in spellbook and action bar
3196 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3197 data
<< uint16(spell_id
);
3198 data
<< uint16(prev_id
);
3199 GetSession()->SendPacket( &data
);
3200 prev_activate
= true;
3208 // remove from spell book if not replaced by lesser rank
3211 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3212 data
<< uint16(spell_id
);
3213 GetSession()->SendPacket(&data
);
3217 void Player::RemoveArenaSpellCooldowns()
3219 // remove cooldowns on spells that has < 15 min CD
3220 SpellCooldowns::iterator itr
, next
;
3221 // iterate spell cooldowns
3222 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3226 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3227 // check if spellentry is present and if the cooldown is less than 15 mins
3229 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3230 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3233 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3234 data
<< uint32(itr
->first
);
3235 data
<< uint64(GetGUID());
3236 GetSession()->SendPacket(&data
);
3238 m_spellCooldowns
.erase(itr
);
3243 void Player::RemoveAllSpellCooldown()
3245 if(!m_spellCooldowns
.empty())
3247 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3249 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3250 data
<< uint32(itr
->first
);
3251 data
<< uint64(GetGUID());
3252 GetSession()->SendPacket(&data
);
3254 m_spellCooldowns
.clear();
3258 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3260 // some cooldowns can be already set at aura loading...
3262 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3266 time_t curTime
= time(NULL
);
3270 Field
*fields
= result
->Fetch();
3272 uint32 spell_id
= fields
[0].GetUInt32();
3273 uint32 item_id
= fields
[1].GetUInt32();
3274 time_t db_time
= (time_t)fields
[2].GetUInt64();
3276 if(!sSpellStore
.LookupEntry(spell_id
))
3278 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3282 // skip outdated cooldown
3283 if(db_time
<= curTime
)
3286 AddSpellCooldown(spell_id
, item_id
, db_time
);
3288 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3290 while( result
->NextRow() );
3296 void Player::_SaveSpellCooldowns()
3298 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3300 time_t curTime
= time(NULL
);
3301 time_t infTime
= curTime
+ MONTH
/2;
3303 // remove outdated and save active
3304 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3306 if(itr
->second
.end
<= curTime
)
3307 m_spellCooldowns
.erase(itr
++);
3308 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3310 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
));
3318 uint32
Player::resetTalentsCost() const
3320 // The first time reset costs 1 gold
3321 if(m_resetTalentsCost
< 1*GOLD
)
3324 else if(m_resetTalentsCost
< 5*GOLD
)
3326 // After that it increases in increments of 5 gold
3327 else if(m_resetTalentsCost
< 10*GOLD
)
3331 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3334 // This cost will be reduced by a rate of 5 gold per month
3335 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3336 // to a minimum of 10 gold.
3337 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3341 // After that it increases in increments of 5 gold
3342 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3343 // until it hits a cap of 50 gold.
3344 if(new_cost
> 50*GOLD
)
3351 bool Player::resetTalents(bool no_cost
)
3353 // not need after this call
3354 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3356 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3357 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3360 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3362 if (m_usedTalentCount
== 0)
3364 SetFreeTalentPoints(talentPointsForLevel
);
3372 cost
= resetTalentsCost();
3374 if (GetMoney() < cost
)
3376 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3381 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
3383 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3385 if (!talentInfo
) continue;
3387 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3392 // unlearn only talents for character class
3393 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3394 // to prevent unexpected lost normal learned spell skip another class talents
3395 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3398 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3400 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3402 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3408 // remove learned spells (all ranks)
3409 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3411 // unlearn if first rank is talent or learned by talent
3412 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3414 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3415 itr
= GetSpellMap().begin();
3424 SetFreeTalentPoints(talentPointsForLevel
);
3428 ModifyMoney(-(int32
)cost
);
3429 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3430 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3432 m_resetTalentsCost
= cost
;
3433 m_resetTalentsTime
= time(NULL
);
3436 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3437 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3441 m_canTitanGrip
= false;
3442 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3443 AutoUnequipOffhandIfNeed();
3449 Mail
* Player::GetMail(uint32 id
)
3451 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3453 if ((*itr
)->messageID
== id
)
3461 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3465 Object::_SetCreateBits(updateMask
, target
);
3469 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3471 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3472 updateMask
->SetBit(index
);
3477 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3481 Object::_SetUpdateBits(updateMask
, target
);
3485 Object::_SetUpdateBits(updateMask
, target
);
3486 *updateMask
&= updateVisualBits
;
3490 void Player::InitVisibleBits()
3492 updateVisualBits
.SetCount(PLAYER_END
);
3494 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3495 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3496 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3497 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3498 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3499 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3500 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3501 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3502 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3503 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3504 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3505 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3506 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3507 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3508 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3509 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3510 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3511 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3512 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3513 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3514 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3515 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3516 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3517 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3518 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3519 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3520 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3521 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3522 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3523 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3524 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3525 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3526 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3527 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3528 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3529 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3530 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3531 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3532 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3533 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3534 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3535 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3536 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3537 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3538 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3539 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3540 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3541 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3542 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3543 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3544 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3545 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3546 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3547 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3548 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3550 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3551 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3552 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3553 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3554 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3555 updateVisualBits
.SetBit(PLAYER_BYTES
);
3556 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3557 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3558 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3559 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3561 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3562 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3563 updateVisualBits
.SetBit(i
);
3565 // Players visible items are not inventory stuff
3566 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3568 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3571 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3572 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3575 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3577 // item enchantments
3578 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3579 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3581 // random properties
3582 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3583 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3584 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3587 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3590 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3592 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3594 if(m_items
[i
] == NULL
)
3597 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3602 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3604 if(m_items
[i
] == NULL
)
3607 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3609 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
3611 if(m_items
[i
] == NULL
)
3614 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3618 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3621 void Player::DestroyForPlayer( Player
*target
) const
3623 Unit::DestroyForPlayer( target
);
3625 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3627 if(m_items
[i
] == NULL
)
3630 m_items
[i
]->DestroyForPlayer( target
);
3635 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3637 if(m_items
[i
] == NULL
)
3640 m_items
[i
]->DestroyForPlayer( target
);
3642 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
3644 if(m_items
[i
] == NULL
)
3647 m_items
[i
]->DestroyForPlayer( target
);
3652 bool Player::HasSpell(uint32 spell
) const
3654 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3655 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3656 !itr
->second
->disabled
);
3659 bool Player::HasActiveSpell(uint32 spell
) const
3661 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3662 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3663 itr
->second
->active
&& !itr
->second
->disabled
);
3666 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3669 return TRAINER_SPELL_RED
;
3671 if (!trainer_spell
->learnedSpell
)
3672 return TRAINER_SPELL_RED
;
3675 if(HasSpell(trainer_spell
->learnedSpell
))
3676 return TRAINER_SPELL_GRAY
;
3678 // check race/class requirement
3679 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3680 return TRAINER_SPELL_RED
;
3682 // check level requirement
3683 if(getLevel() < trainer_spell
->reqLevel
)
3684 return TRAINER_SPELL_RED
;
3686 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3688 // check prev.rank requirement
3689 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3690 return TRAINER_SPELL_RED
;
3692 // check additional spell requirement
3693 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3694 return TRAINER_SPELL_RED
;
3697 // check skill requirement
3698 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3699 return TRAINER_SPELL_RED
;
3701 // exist, already checked at loading
3702 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3704 // secondary prof. or not prof. spell
3705 uint32 skill
= spell
->EffectMiscValue
[1];
3707 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3708 return TRAINER_SPELL_GREEN
;
3710 // check primary prof. limit
3711 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3712 return TRAINER_SPELL_GREEN_DISABLED
;
3714 return TRAINER_SPELL_GREEN
;
3717 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3719 uint32 guid
= GUID_LOPART(playerguid
);
3721 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3722 // bones will be deleted by corpse/bones deleting thread shortly
3723 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3725 // remove from guild
3726 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3729 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3731 guild
->DelMember(guid
);
3734 // remove from arena teams
3735 LeaveAllArenaTeams(playerguid
);
3737 // the player was uninvited already on logout so just remove from group
3738 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3741 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3743 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3746 RemoveFromGroup(group
, playerguid
);
3750 // remove signs from petitions (also remove petitions if owner);
3751 RemovePetitionsAndSigns(playerguid
, 10);
3753 // return back all mails with COD and Item 0 1 2 3 4 5 6
3754 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
);
3759 Field
*fields
= resultMail
->Fetch();
3761 uint32 mail_id
= fields
[0].GetUInt32();
3762 uint16 mailTemplateId
= fields
[1].GetUInt16();
3763 uint32 sender
= fields
[2].GetUInt32();
3764 std::string subject
= fields
[3].GetCppString();
3765 uint32 itemTextId
= fields
[4].GetUInt32();
3766 uint32 money
= fields
[5].GetUInt32();
3767 bool has_items
= fields
[6].GetBool();
3769 //we can return mail now
3770 //so firstly delete the old one
3771 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3776 // data needs to be at first place for Item::LoadFromDB
3777 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id
);
3782 Field
*fields2
= resultItems
->Fetch();
3784 uint32 item_guidlow
= fields2
[1].GetUInt32();
3785 uint32 item_template
= fields2
[2].GetUInt32();
3787 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3790 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3794 Item
*pItem
= NewItemOrBag(itemProto
);
3795 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3797 pItem
->FSetState(ITEM_REMOVED
);
3798 pItem
->SaveToDB(); // it also deletes item object !
3802 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3804 while (resultItems
->NextRow());
3810 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3812 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3814 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3816 while (resultMail
->NextRow());
3821 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3822 // Get guids of character's pets, will deleted in transaction
3823 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3825 // NOW we can finally clear other DB data related to character
3826 CharacterDatabase
.BeginTransaction();
3831 Field
*fields3
= resultPets
->Fetch();
3832 uint32 petguidlow
= fields3
[0].GetUInt32();
3833 Pet::DeleteFromDB(petguidlow
);
3834 } while (resultPets
->NextRow());
3838 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3839 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3840 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3841 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3842 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3843 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3844 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3845 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3846 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3847 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3848 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3849 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3850 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3851 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3852 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3853 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3854 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3855 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3856 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3857 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3858 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3859 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3860 CharacterDatabase
.CommitTransaction();
3862 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3863 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3866 void Player::SetMovement(PlayerMovementType pType
)
3871 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3872 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3873 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3874 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3876 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3879 data
.append(GetPackGUID());
3881 GetSession()->SendPacket( &data
);
3885 - a resurrectable corpse must not be loaded for the player (only bones)
3886 - the player must be in world
3888 void Player::BuildPlayerRepop()
3890 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3891 data
.append(GetPackGUID());
3892 GetSession()->SendPacket(&data
);
3894 if(getRace() == RACE_NIGHTELF
)
3895 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)
3896 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3898 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3899 // there must be SMSG.STOP_MIRROR_TIMER
3900 // there we must send 888 opcode
3902 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3905 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3909 // create a corpse and place it at the player's location
3911 Corpse
*corpse
= GetCorpse();
3914 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3917 GetMap()->Add(corpse
);
3919 // convert player body to ghost
3922 SetMovement(MOVE_WATER_WALK
);
3923 if(!GetSession()->isLogingOut())
3924 SetMovement(MOVE_UNROOT
);
3926 // BG - remove insignia related
3927 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3929 SendCorpseReclaimDelay();
3931 // to prevent cheating
3932 corpse
->ResetGhostTime();
3934 StopMirrorTimers(); //disable timers(bars)
3936 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3938 // set and clear other
3939 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3942 void Player::SendDelayResponse(const uint32 ml_seconds
)
3944 //FIXME: is this delay time arg really need? 50msec by default in code
3945 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3946 data
<< (uint32
)time(NULL
);
3948 GetSession()->SendPacket( &data
);
3951 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3953 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3958 GetSession()->SendPacket(&data
);
3960 // speed change, land walk
3962 // remove death flag + set aura
3963 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3964 if(getRace() == RACE_NIGHTELF
)
3965 RemoveAurasDueToSpell(20584); // speed bonuses
3966 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3968 setDeathState(ALIVE
);
3970 SetMovement(MOVE_LAND_WALK
);
3971 SetMovement(MOVE_UNROOT
);
3975 // set health/powers (0- will be set in caller)
3976 if(restore_percent
>0.0f
)
3978 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3979 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3980 SetPower(POWER_RAGE
, 0);
3981 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3984 // trigger update zone for alive state zone updates
3985 uint32 newzone
, newarea
;
3986 GetZoneAndAreaId(newzone
,newarea
);
3987 UpdateZone(newzone
,newarea
);
3989 // update visibility
3990 ObjectAccessor::UpdateVisibilityForPlayer(this);
3995 //Characters from level 1-10 are not affected by resurrection sickness.
3996 //Characters from level 11-19 will suffer from one minute of sickness
3997 //for each level they are above 10.
3998 //Characters level 20 and up suffer from ten minutes of sickness.
3999 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
4001 if(int32(getLevel()) >= startLevel
)
4003 // set resurrection sickness
4004 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4006 // not full duration
4007 if(int32(getLevel()) < startLevel
+9)
4009 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4011 for(int i
=0; i
< 3; ++i
)
4013 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
4015 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
4016 Aur
->SendAuraUpdate(false);
4023 void Player::KillPlayer()
4025 SetMovement(MOVE_ROOT
);
4027 StopMirrorTimers(); //disable timers(bars)
4029 setDeathState(CORPSE
);
4030 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4032 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4033 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4035 // 6 minutes until repop at graveyard
4036 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4038 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4040 // don't create corpse at this moment, player might be falling
4042 // update visibility
4043 ObjectAccessor::UpdateObjectVisibility(this);
4046 void Player::CreateCorpse()
4048 // prevent existence 2 corpse for player
4051 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4053 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4056 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4062 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4063 _pb
= GetUInt32Value(PLAYER_BYTES
);
4064 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4066 uint8 race
= (uint8
)(_uf
);
4067 uint8 skin
= (uint8
)(_pb
);
4068 uint8 face
= (uint8
)(_pb
>> 8);
4069 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4070 uint8 haircolor
= (uint8
)(_pb
>> 24);
4071 uint8 facialhair
= (uint8
)(_pb2
);
4073 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4074 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4076 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4077 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4079 uint32 flags
= CORPSE_FLAG_UNK2
;
4080 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4081 flags
|= CORPSE_FLAG_HIDE_HELM
;
4082 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4083 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4084 if(InBattleGround() && !InArena())
4085 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4086 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4088 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4090 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4093 uint16 iIventoryType
;
4095 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4099 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4100 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
4102 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
4103 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
4107 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4108 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4110 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4113 // register for player, but not show
4114 ObjectAccessor::Instance().AddCorpse(corpse
);
4117 void Player::SpawnCorpseBones()
4119 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4120 SaveToDB(); // prevent loading as ghost without corpse
4123 Corpse
* Player::GetCorpse() const
4125 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4128 void Player::DurabilityLossAll(double percent
, bool inventory
)
4130 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4131 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4132 DurabilityLoss(pItem
,percent
);
4136 // bags not have durability
4137 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4139 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4140 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4141 DurabilityLoss(pItem
,percent
);
4143 // keys not have durability
4144 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4146 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4147 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4148 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4149 if(Item
* pItem
= GetItemByPos( i
, j
))
4150 DurabilityLoss(pItem
,percent
);
4154 void Player::DurabilityLoss(Item
* item
, double percent
)
4159 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4164 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4166 if(pDurabilityLoss
< 1 )
4167 pDurabilityLoss
= 1;
4169 DurabilityPointsLoss(item
,pDurabilityLoss
);
4172 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4174 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4175 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4176 DurabilityPointsLoss(pItem
,points
);
4180 // bags not have durability
4181 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4183 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4184 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4185 DurabilityPointsLoss(pItem
,points
);
4187 // keys not have durability
4188 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4190 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4191 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4192 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4193 if(Item
* pItem
= GetItemByPos( i
, j
))
4194 DurabilityPointsLoss(pItem
,points
);
4198 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4200 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4201 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4202 int32 pNewDurability
= pOldDurability
- points
;
4204 if (pNewDurability
< 0)
4206 else if (pNewDurability
> pMaxDurability
)
4207 pNewDurability
= pMaxDurability
;
4209 if (pOldDurability
!= pNewDurability
)
4211 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4212 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4213 _ApplyItemMods(item
,item
->GetSlot(), false);
4215 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4217 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4218 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4219 _ApplyItemMods(item
,item
->GetSlot(), true);
4221 item
->SetState(ITEM_CHANGED
, this);
4225 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4227 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4228 DurabilityPointsLoss(pItem
,1);
4231 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4233 uint32 TotalCost
= 0;
4234 // equipped, backpack, bags itself
4235 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4236 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4238 // bank, buyback and keys not repaired
4240 // items in inventory bags
4241 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4242 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4243 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4247 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4249 Item
* item
= GetItemByPos(pos
);
4251 uint32 TotalCost
= 0;
4255 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4259 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4263 uint32 LostDurability
= maxDurability
- curDurability
;
4264 if(LostDurability
>0)
4266 ItemPrototype
const *ditemProto
= item
->GetProto();
4268 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4271 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4275 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4276 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4277 if(!dQualitymodEntry
)
4279 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4283 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4284 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4286 costs
= uint32(costs
* discountMod
);
4288 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4293 if (GetGuildId()==0)
4295 DEBUG_LOG("You are not member of a guild");
4299 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4303 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4305 DEBUG_LOG("You do not have rights to withdraw for repairs");
4309 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4311 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4315 if (pGuild
->GetGuildBankMoney() < costs
)
4317 DEBUG_LOG("There is not enough money in bank");
4321 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4324 else if (GetMoney() < costs
)
4326 DEBUG_LOG("You do not have enough money");
4330 ModifyMoney( -int32(costs
) );
4334 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4335 item
->SetState(ITEM_CHANGED
, this);
4337 // reapply mods for total broken and repaired item if equipped
4338 if(IsEquipmentPos(pos
) && !curDurability
)
4339 _ApplyItemMods(item
,pos
& 255, true);
4343 void Player::RepopAtGraveyard()
4345 // note: this can be called also when the player is alive
4346 // for example from WorldSession::HandleMovementOpcodes
4348 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4350 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4351 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4353 ResurrectPlayer(0.5f
);
4357 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4359 // Special handle for battleground maps
4360 if( BattleGround
*bg
= GetBattleGround() )
4361 ClosestGrave
= bg
->GetClosestGraveYard(this);
4363 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4365 // stop countdown until repop
4368 // if no grave found, stay at the current location
4369 // and don't show spirit healer location
4372 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4373 if(isDead()) // not send if alive, because it used in TeleportTo()
4375 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4376 data
<< ClosestGrave
->map_id
;
4377 data
<< ClosestGrave
->x
;
4378 data
<< ClosestGrave
->y
;
4379 data
<< ClosestGrave
->z
;
4380 GetSession()->SendPacket(&data
);
4385 void Player::JoinedChannel(Channel
*c
)
4387 m_channels
.push_back(c
);
4390 void Player::LeftChannel(Channel
*c
)
4392 m_channels
.remove(c
);
4395 void Player::CleanupChannels()
4397 while(!m_channels
.empty())
4399 Channel
* ch
= *m_channels
.begin();
4400 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4401 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4402 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4403 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4406 sLog
.outDebug("Player: channels cleaned up!");
4409 void Player::UpdateLocalChannels(uint32 newZone
)
4411 if(m_channels
.empty())
4414 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4418 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4422 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4424 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4428 // skip non built-in channels
4429 if(!(*i
)->IsConstant())
4432 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4436 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4440 char new_channel_name_buf
[100];
4441 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4442 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4444 if((*i
)!=new_channel
)
4446 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4448 // leave old channel
4449 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4450 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4451 LeftChannel(*i
); // remove from player's channel list
4452 cMgr
->LeftChannel(name
); // delete if empty
4455 sLog
.outDebug("Player: channels cleaned up!");
4458 void Player::LeaveLFGChannel()
4460 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4464 (*i
)->Leave(GetGUID());
4470 void Player::UpdateDefense()
4472 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4474 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4476 // update dependent from defense skill part
4477 UpdateDefenseBonusesMod();
4481 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4483 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4485 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4494 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4497 if(amount
<= -100.0f
)
4500 val
= (100.0f
+ amount
) / 100.0f
;
4501 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4505 if(!CanModifyStats())
4510 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4511 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4512 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4513 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4518 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4520 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4522 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4526 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4529 return m_auraBaseMod
[modGroup
][modType
];
4532 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4534 if(modGroup
>= BASEMOD_END
)
4536 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4540 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4543 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4546 uint32
Player::GetShieldBlockValue() const
4548 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4550 value
= (value
< 0) ? 0 : value
;
4552 return uint32(value
);
4555 float Player::GetMeleeCritFromAgility()
4557 uint32 level
= getLevel();
4558 uint32 pclass
= getClass();
4560 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4562 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4563 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4564 if (critBase
==NULL
|| critRatio
==NULL
)
4567 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4571 float Player::GetDodgeFromAgility()
4573 // Table for base dodge values
4574 float dodge_base
[MAX_CLASSES
] = {
4576 0.00652f
, // Paladin
4583 0.02011f
, // Warlock
4587 // Crit/agility to dodge/agility coefficient multipliers
4588 float crit_to_dodge
[MAX_CLASSES
] = {
4602 uint32 level
= getLevel();
4603 uint32 pclass
= getClass();
4605 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4607 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4608 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4609 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4612 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4613 return dodge
*100.0f
;
4616 float Player::GetSpellCritFromIntellect()
4618 uint32 level
= getLevel();
4619 uint32 pclass
= getClass();
4621 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4623 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4624 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4625 if (critBase
==NULL
|| critRatio
==NULL
)
4628 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4632 float Player::GetRatingCoefficient(CombatRating cr
) const
4634 uint32 level
= getLevel();
4636 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4638 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4640 return 1.0f
; // By default use minimum coefficient (not must be called)
4642 return Rating
->ratio
;
4645 float Player::GetRatingBonusValue(CombatRating cr
) const
4647 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4650 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4652 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.2f
;
4653 if (melee
>33.0f
) melee
= 33.0f
;
4654 return uint32 (melee
* damage
/100.0f
);
4657 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4659 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.2f
;
4660 if (ranged
>33.0f
) ranged
=33.0f
;
4661 return uint32 (ranged
* damage
/100.0f
);
4664 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4666 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.2f
;
4667 // In wow script resilience limited to 33%
4670 return uint32 (spell
* damage
/ 100.0f
);
4673 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4675 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4676 // Dot resilience not limited (limit it by 100%)
4677 if (spellDot
> 100.0f
)
4679 return uint32 (spellDot
* damage
/ 100.0f
);
4682 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4687 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4689 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4696 float Player::OCTRegenHPPerSpirit()
4698 uint32 level
= getLevel();
4699 uint32 pclass
= getClass();
4701 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4703 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4704 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4705 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4708 // Formula from PaperDollFrame script
4709 float spirit
= GetStat(STAT_SPIRIT
);
4710 float baseSpirit
= spirit
;
4711 if (baseSpirit
>50) baseSpirit
= 50;
4712 float moreSpirit
= spirit
- baseSpirit
;
4713 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4717 float Player::OCTRegenMPPerSpirit()
4719 uint32 level
= getLevel();
4720 uint32 pclass
= getClass();
4722 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4724 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4725 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4726 if (moreRatio
==NULL
)
4729 // Formula get from PaperDollFrame script
4730 float spirit
= GetStat(STAT_SPIRIT
);
4731 float regen
= spirit
* moreRatio
->ratio
;
4735 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4737 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4739 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4740 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4741 // stat used stored in miscValueB for this aura
4742 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4743 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4744 if ((*i
)->GetMiscValue() & (1<<cr
))
4745 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4748 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4750 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4751 float RatingChange
= 0.0f
;
4753 bool affectStats
= CanModifyStats();
4757 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4758 case CR_DEFENSE_SKILL
:
4759 UpdateDefenseBonusesMod();
4762 UpdateDodgePercentage();
4765 UpdateParryPercentage();
4768 UpdateBlockPercentage();
4771 UpdateMeleeHitChances();
4774 UpdateRangedHitChances();
4777 UpdateSpellHitChances();
4782 UpdateCritPercentage(BASE_ATTACK
);
4783 UpdateCritPercentage(OFF_ATTACK
);
4786 case CR_CRIT_RANGED
:
4788 UpdateCritPercentage(RANGED_ATTACK
);
4792 UpdateAllSpellCritChances();
4794 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4795 case CR_HIT_TAKEN_RANGED
:
4797 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4799 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4800 case CR_CRIT_TAKEN_RANGED
:
4802 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4804 case CR_HASTE_MELEE
:
4805 RatingChange
= value
/ RatingCoeffecient
;
4806 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4807 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4809 case CR_HASTE_RANGED
:
4810 RatingChange
= value
/ RatingCoeffecient
;
4811 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4813 case CR_HASTE_SPELL
:
4814 RatingChange
= value
/ RatingCoeffecient
;
4815 ApplyCastTimePercentMod(RatingChange
,apply
);
4817 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4818 case CR_WEAPON_SKILL_OFFHAND
:
4819 case CR_WEAPON_SKILL_RANGED
:
4824 UpdateExpertise(BASE_ATTACK
);
4825 UpdateExpertise(OFF_ATTACK
);
4828 case CR_ARMOR_PENETRATION
:
4833 void Player::SetRegularAttackTime()
4835 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4837 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4838 if(tmpitem
&& !tmpitem
->IsBroken())
4840 ItemPrototype
const *proto
= tmpitem
->GetProto();
4842 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4844 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4849 //skill+step, checking for max value
4850 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4856 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
4857 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4860 if(i
>=PLAYER_MAX_SKILLS
)
4863 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4864 uint32 value
= SKILL_VALUE(data
);
4865 uint32 max
= SKILL_MAX(data
);
4867 if ((!max
) || (!value
) || (value
>= max
))
4870 if (value
*512 < max
*urand(0,512))
4872 uint32 new_value
= value
+step
;
4876 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4877 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
4884 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4886 if ( SkillValue
>= GrayLevel
)
4887 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4888 if ( SkillValue
>= GreenLevel
)
4889 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4890 if ( SkillValue
>= YellowLevel
)
4891 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4892 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4895 bool Player::UpdateCraftSkill(uint32 spellid
)
4897 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4899 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4900 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4902 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4904 if(_spell_idx
->second
->skillId
)
4906 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4908 // Alchemy Discoveries here
4909 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4910 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4912 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4913 learnSpell(discoveredSpell
,false);
4916 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4918 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4919 _spell_idx
->second
->max_value
,
4920 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4921 _spell_idx
->second
->min_value
),
4928 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4930 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4932 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4934 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4937 case SKILL_HERBALISM
:
4938 case SKILL_LOCKPICKING
:
4939 case SKILL_JEWELCRAFTING
:
4940 case SKILL_INSCRIPTION
:
4941 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4942 case SKILL_SKINNING
:
4943 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4944 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4946 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4948 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4949 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4951 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4956 bool Player::UpdateFishingSkill()
4958 sLog
.outDebug("UpdateFishingSkill");
4960 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4962 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4964 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4966 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4969 // levels sync. with spell requirement for skill levels to learn
4970 // bonus abilities in sSkillLineAbilityStore
4971 // Used only to avoid scan DBC at each skill grow
4972 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4974 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4976 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4980 if(Chance
<= 0) // speedup in 0 chance case
4982 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4987 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
4988 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4989 if ( i
>= PLAYER_MAX_SKILLS
)
4992 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4993 uint16 SkillValue
= SKILL_VALUE(data
);
4994 uint16 MaxValue
= SKILL_MAX(data
);
4996 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4999 int32 Roll
= irand(1,1000);
5001 if ( Roll
<= Chance
)
5003 uint32 new_value
= SkillValue
+step
;
5004 if(new_value
> MaxValue
)
5005 new_value
= MaxValue
;
5007 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
5008 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5010 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5012 learnSkillRewardedSpells( SkillId
, new_value
);
5016 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5017 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5021 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5025 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5027 // no skill gain in pvp
5028 Unit
*pVictim
= getVictim();
5029 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
5033 return; // always maximized SKILL_FERAL_COMBAT in fact
5035 if(m_form
== FORM_TREE
)
5036 return; // use weapon but not skill up
5038 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5044 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5047 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5048 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5049 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5055 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5057 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5061 UpdateAllCritPercentages();
5064 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5066 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5067 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5068 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5069 if(moblevel
< greylevel
)
5072 if (moblevel
> plevel
+ 5)
5073 moblevel
= plevel
+ 5;
5075 uint32 lvldif
= moblevel
- greylevel
;
5079 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5083 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5086 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5087 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5090 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5092 if(roll_chance_f(chance
))
5097 UpdateWeaponSkill(attType
);
5103 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5105 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5106 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5108 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5109 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5110 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5112 if(talent
) // permanent bonus stored in high part
5113 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5114 else // temporary/item bonus stored in low part
5115 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5120 void Player::UpdateSkillsForLevel()
5122 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5123 uint32 maxSkill
= GetMaxSkillValueForLevel();
5125 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5127 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5128 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5130 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5132 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5136 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5139 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5140 uint32 max
= SKILL_MAX(data
);
5141 uint32 val
= SKILL_VALUE(data
);
5143 /// update only level dependent max skill values
5146 /// miximize skill always
5148 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5149 /// update max skill value if current max skill not maximized
5150 else if(max
!= maxconfskill
)
5151 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5156 void Player::UpdateSkillsToMaxSkillsForLevel()
5158 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5159 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5161 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5162 if( IsProfessionOrRidingSkill(pskill
))
5164 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5166 uint32 max
= SKILL_MAX(data
);
5169 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5171 if(pskill
== SKILL_DEFENSE
)
5172 UpdateDefenseBonusesMod();
5176 // This functions sets a skill line value (and adds if doesn't exist yet)
5177 // To "remove" a skill line, set it's values to zero
5178 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5184 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
5185 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5187 if(i
<PLAYER_MAX_SKILLS
) //has skill
5191 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5192 learnSkillRewardedSpells(id
, currVal
);
5193 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5194 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5198 // clear skill fields
5199 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5200 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5201 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5203 // remove all spells that related to this skill
5204 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5205 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5206 if (pAbility
->skillId
==id
)
5207 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5210 else if(currVal
) //add
5212 for (i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5213 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5215 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5218 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5221 // enable unlearn button for primary professions only
5222 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5223 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5225 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5226 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5227 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5228 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5230 // apply skill bonuses
5231 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5233 // temporary bonuses
5234 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5235 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5236 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5237 (*j
)->ApplyModifier(true);
5239 // permanent bonuses
5240 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5241 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5242 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5243 (*j
)->ApplyModifier(true);
5245 // Learn all spells for skill
5246 learnSkillRewardedSpells(id
, currVal
);
5252 bool Player::HasSkill(uint32 skill
) const
5254 if(!skill
)return false;
5255 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5257 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5265 uint16
Player::GetSkillValue(uint32 skill
) const
5270 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5272 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5274 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5276 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5277 result
+= SKILL_TEMP_BONUS(bonus
);
5278 result
+= SKILL_PERM_BONUS(bonus
);
5279 return result
< 0 ? 0 : result
;
5285 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5288 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5290 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5292 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5294 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5295 result
+= SKILL_TEMP_BONUS(bonus
);
5296 result
+= SKILL_PERM_BONUS(bonus
);
5297 return result
< 0 ? 0 : result
;
5303 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5306 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5308 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5310 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5316 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5319 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5321 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5323 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5324 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5325 return result
< 0 ? 0 : result
;
5331 uint16
Player::GetPureSkillValue(uint32 skill
) const
5334 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5336 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5338 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5344 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5349 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5351 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5353 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5360 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5365 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5367 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5369 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5376 void Player::SendInitialActionButtons() const
5378 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5380 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5381 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5383 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5384 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5386 data
<< uint16(itr
->second
.action
);
5387 data
<< uint8(itr
->second
.misc
);
5388 data
<< uint8(itr
->second
.type
);
5396 GetSession()->SendPacket( &data
);
5397 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5400 bool Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5402 if(button
>= MAX_ACTION_BUTTONS
)
5404 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5408 // check cheating with adding non-known spells to action bar
5409 if(type
==ACTION_BUTTON_SPELL
)
5411 if(!sSpellStore
.LookupEntry(action
))
5413 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5417 if(!HasSpell(action
))
5419 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5424 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5426 if (buttonItr
==m_actionButtons
.end())
5427 { // just add new button
5428 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5431 { // change state of current button
5432 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5433 buttonItr
->second
= ActionButton(action
,type
,misc
);
5434 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5437 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5441 void Player::removeActionButton(uint8 button
)
5443 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5444 if (buttonItr
==m_actionButtons
.end())
5447 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5448 m_actionButtons
.erase(buttonItr
); // new and not saved
5450 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5452 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5455 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5457 // prevent crash when a bad coord is sent by the client
5458 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5460 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5466 const float old_x
= GetPositionX();
5467 const float old_y
= GetPositionY();
5468 const float old_z
= GetPositionZ();
5469 const float old_r
= GetOrientation();
5471 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5473 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5474 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5476 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5478 // move and update visible state if need
5479 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5481 // reread after Map::Relocation
5488 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5489 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5492 // code block for underwater state update
5493 UpdateUnderwaterState(m
, x
, y
, z
);
5495 CheckExploreSystem();
5500 void Player::SaveRecallPosition()
5502 m_recallMap
= GetMapId();
5503 m_recallX
= GetPositionX();
5504 m_recallY
= GetPositionY();
5505 m_recallZ
= GetPositionZ();
5506 m_recallO
= GetOrientation();
5509 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5511 GetMap()->MessageBroadcast(this, data
, self
);
5514 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5516 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5519 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5521 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5524 void Player::SendDirectMessage(WorldPacket
*data
)
5526 GetSession()->SendPacket(data
);
5529 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5531 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5532 data
<< uint32(CinematicSequenceId
);
5533 SendDirectMessage(&data
);
5536 void Player::SendMovieStart(uint32 MovieId
)
5538 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5539 data
<< uint32(MovieId
);
5540 SendDirectMessage(&data
);
5543 void Player::CheckExploreSystem()
5551 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5552 if(areaFlag
==0xffff)
5554 int offset
= areaFlag
/ 32;
5558 sLog
.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5562 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5563 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5565 if( !(currFields
& val
) )
5567 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5569 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5571 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5574 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5576 else if(p
->area_level
> 0)
5578 uint32 area
= p
->ID
;
5579 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5581 SendExplorationExperience(area
,0);
5585 int32 diff
= int32(getLevel()) - p
->area_level
;
5589 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5593 int32 exploration_percent
= (100-((diff
-5)*5));
5594 if (exploration_percent
> 100)
5595 exploration_percent
= 100;
5596 else if (exploration_percent
< 0)
5597 exploration_percent
= 0;
5599 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5603 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5607 SendExplorationExperience(area
,XP
);
5609 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5614 uint32
Player::TeamForRace(uint8 race
)
5616 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5619 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5623 switch(rEntry
->TeamID
)
5625 case 7: return ALLIANCE
;
5626 case 1: return HORDE
;
5629 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5633 uint32
Player::getFactionForRace(uint8 race
)
5635 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5638 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5642 return rEntry
->FactionID
;
5645 void Player::setFactionForRace(uint8 race
)
5647 m_team
= TeamForRace(race
);
5648 setFaction( getFactionForRace(race
) );
5651 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5653 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5654 return GetReputationMgr().GetRank(factionEntry
);
5657 //Calculate total reputation percent player gain with quest/creature level
5658 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5660 float percent
= 100.0f
;
5662 float rate
= for_quest
? sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_KILL
);
5664 if(rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
5667 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5669 percent
+= rep
> 0 ? repMod
: -repMod
;
5674 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5677 //Calculates how many reputation points player gains in victim's enemy factions
5678 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5680 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5683 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5688 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5690 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5691 donerep1
= int32(donerep1
*rate
);
5692 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5693 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
5694 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5695 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
5697 // Wiki: Team factions value divided by 2
5698 if (factionEntry1
&& Rep
->is_teamaward1
)
5700 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5701 if(team1_factionEntry
)
5702 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
5706 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5708 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5709 donerep2
= int32(donerep2
*rate
);
5710 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5711 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
5712 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5713 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
5715 // Wiki: Team factions value divided by 2
5716 if (factionEntry2
&& Rep
->is_teamaward2
)
5718 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5719 if(team2_factionEntry
)
5720 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
5725 //Calculate how many reputation points player gain with the quest
5726 void Player::RewardReputation(Quest
const *pQuest
)
5728 // quest reputation reward/loss
5729 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5731 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5733 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
),pQuest
->RewRepValue
[i
],true);
5734 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5736 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
5740 // TODO: implement reputation spillover
5743 void Player::UpdateArenaFields(void)
5745 /* arena calcs go here */
5748 void Player::UpdateHonorFields()
5750 /// called when rewarding honor and at each save
5751 uint64 now
= time(NULL
);
5752 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5754 if(m_lastHonorUpdateTime
< today
)
5756 uint64 yesterday
= today
- DAY
;
5758 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5760 // update yesterday's contribution
5761 if(m_lastHonorUpdateTime
>= yesterday
)
5763 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5765 // this is the first update today, reset today's contribution
5766 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5767 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5771 // no honor/kills yesterday or today, reset
5772 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5773 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5777 m_lastHonorUpdateTime
= now
;
5780 ///Calculate the amount of honor gained based on the victim
5781 ///and the size of the group for which the honor is divided
5782 ///An exact honor value can also be given (overriding the calcs)
5783 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5785 // do not reward honor in arenas, but enable onkill spellproc
5788 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5791 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5797 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5798 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5801 uint64 victim_guid
= 0;
5802 uint32 victim_rank
= 0;
5804 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5805 UpdateHonorFields();
5809 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5812 victim_guid
= uVictim
->GetGUID();
5814 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5816 Player
*pVictim
= (Player
*)uVictim
;
5818 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5821 float f
= 1; //need for total kills (?? need more info)
5823 uint32 k_level
= getLevel();
5824 uint32 v_level
= pVictim
->getLevel();
5827 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5829 // [1..14] Alliance honor titles and player name
5830 // [15..28] Horde honor titles and player name
5831 // [29..38] Other title and player name
5833 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5834 // Get Killer titles, CharTitlesEntry::bit_index
5836 // title[1..14] -> rank[5..18]
5837 // title[15..28] -> rank[5..18]
5838 // title[other] -> 0
5839 if (victim_title
== 0)
5840 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5841 else if (victim_title
< 15)
5842 victim_rank
= victim_title
+ 4;
5843 else if (victim_title
< 29)
5844 victim_rank
= victim_title
- 14 + 4;
5846 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5849 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
5854 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5856 int32 v_rank
=1; //need more info
5858 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5859 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5861 // count the number of playerkills in one day
5862 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5863 // and those in a lifetime
5864 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5865 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
5866 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS
, pVictim
->getClass());
5867 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE
, pVictim
->getRace());
5871 Creature
*cVictim
= (Creature
*)uVictim
;
5873 if (!cVictim
->isRacialLeader())
5876 honor
= 100; // ??? need more info
5877 victim_rank
= 19; // HK: Leader
5881 if (uVictim
!= NULL
)
5883 honor
*= sWorld
.getRate(RATE_HONOR
);
5888 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5891 // honor - for show honor points in log
5892 // victim_guid - for show victim name in log
5893 // victim_rank [1..4] HK: <dishonored rank>
5894 // victim_rank [5..19] HK: <alliance\horde rank>
5895 // victim_rank [0,20+] HK: <>
5896 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5897 data
<< (uint32
) honor
;
5898 data
<< (uint64
) victim_guid
;
5899 data
<< (uint32
) victim_rank
;
5901 GetSession()->SendPacket(&data
);
5904 ModifyHonorPoints(int32(honor
));
5906 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5910 void Player::ModifyHonorPoints( int32 value
)
5914 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5915 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5917 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5920 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5923 void Player::ModifyArenaPoints( int32 value
)
5927 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
5928 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
5930 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
5933 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
5936 uint32
Player::GetGuildIdFromDB(uint64 guid
)
5938 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
5942 uint32 id
= result
->Fetch()[0].GetUInt32();
5947 uint32
Player::GetRankFromDB(uint64 guid
)
5949 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
5952 uint32 v
= result
->Fetch()[0].GetUInt32();
5960 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
5962 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
);
5966 uint32 id
= (*result
)[0].GetUInt32();
5971 uint32
Player::GetZoneIdFromDB(uint64 guid
)
5973 uint32 guidLow
= GUID_LOPART(guid
);
5974 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
5977 Field
* fields
= result
->Fetch();
5978 uint32 zone
= fields
[0].GetUInt32();
5983 // stored zone is zero, use generic and slow zone detection
5984 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
5987 fields
= result
->Fetch();
5988 uint32 map
= fields
[0].GetUInt32();
5989 float posx
= fields
[1].GetFloat();
5990 float posy
= fields
[2].GetFloat();
5991 float posz
= fields
[3].GetFloat();
5994 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
5996 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6002 void Player::UpdateArea(uint32 newArea
)
6004 // FFA_PVP flags are area and not zone id dependent
6005 // so apply them accordingly
6006 m_areaUpdateId
= newArea
;
6008 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6010 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6013 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6017 // remove ffa flag only if not ffapvp realm
6018 // removal in sanctuaries and capitals is handled in zone update
6019 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6020 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6023 UpdateAreaDependentAuras(newArea
);
6026 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6028 if(m_zoneUpdateId
!= newZone
)
6029 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6031 m_zoneUpdateId
= newZone
;
6032 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6034 // zone changed, so area changed as well, update it
6035 UpdateArea(newArea
);
6037 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6041 if (sWorld
.getConfig(CONFIG_WEATHER
))
6043 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6046 wth
->SendWeatherUpdateToPlayer(this);
6050 if(!sWorld
.AddWeather(zone
->ID
))
6052 // send fine weather packet to remove old zone's weather
6053 Weather::SendFineWeatherUpdateToPlayer(this);
6058 // in PvP, any not controlled zone (except zone->team == 6, default case)
6059 // in PvE, only opposition team capital
6063 pvpInfo
.inHostileArea
= GetTeam() != ALLIANCE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6065 case AREATEAM_HORDE
:
6066 pvpInfo
.inHostileArea
= GetTeam() != HORDE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6069 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6070 pvpInfo
.inHostileArea
= sWorld
.IsPvPRealm() || InBattleGround();
6072 default: // 6 in fact
6073 pvpInfo
.inHostileArea
= false;
6077 if(pvpInfo
.inHostileArea
) // in hostile area
6079 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6080 UpdatePvP(true, true);
6082 else // in friendly area
6084 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6085 pvpInfo
.endTimer
= time(0); // start toggle-off
6088 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6090 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6091 if(sWorld
.IsFFAPvPRealm())
6092 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6096 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6099 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6101 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6102 SetRestType(REST_TYPE_IN_CITY
);
6103 InnEnter(time(0),GetMapId(),0,0,0);
6105 if(sWorld
.IsFFAPvPRealm())
6106 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6108 else // anywhere else
6110 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6112 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6114 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6116 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6117 SetRestType(REST_TYPE_NO
);
6119 if(sWorld
.IsFFAPvPRealm())
6120 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6123 else // not in tavern (leave city then)
6125 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6126 SetRestType(REST_TYPE_NO
);
6128 // Set player to FFA PVP when not in rested environment.
6129 if(sWorld
.IsFFAPvPRealm())
6130 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6135 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6136 // if player resurrected at teleport this will be applied in resurrect code
6138 DestroyZoneLimitedItem( true, newZone
);
6140 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6141 AutoUnequipOffhandIfNeed();
6143 // recent client version not send leave/join channel packets for built-in local channels
6144 UpdateLocalChannels( newZone
);
6148 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6150 UpdateZoneDependentAuras(newZone
);
6153 //If players are too far way of duel flag... then player loose the duel
6154 void Player::CheckDuelDistance(time_t currTime
)
6159 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6160 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6164 if(duel
->outOfBound
== 0)
6166 if(!IsWithinDistInMap(obj
, 50))
6168 duel
->outOfBound
= currTime
;
6170 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6171 GetSession()->SendPacket(&data
);
6176 if(IsWithinDistInMap(obj
, 40))
6178 duel
->outOfBound
= 0;
6180 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6181 GetSession()->SendPacket(&data
);
6183 else if(currTime
>= (duel
->outOfBound
+10))
6185 DuelComplete(DUEL_FLED
);
6190 void Player::DuelComplete(DuelCompleteType type
)
6192 // duel not requested
6196 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6197 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6198 GetSession()->SendPacket(&data
);
6199 duel
->opponent
->GetSession()->SendPacket(&data
);
6201 if(type
!= DUEL_INTERUPTED
)
6203 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6204 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6205 data
<< duel
->opponent
->GetName();
6207 SendMessageToSet(&data
,true);
6210 if (type
== DUEL_WON
)
6212 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL
, 1);
6214 duel
->opponent
->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL
, 1);
6217 // cool-down duel spell
6218 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6225 GetSession()->SendPacket(&data);
6226 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6227 data<<duel->opponent->GetGUID();
6231 duel->opponent->GetSession()->SendPacket(&data);*/
6233 //Remove Duel Flag object
6234 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6236 duel
->initiator
->RemoveGameObject(obj
,true);
6239 std::vector
<uint32
> auras2remove
;
6240 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6241 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6243 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6244 auras2remove
.push_back(i
->second
->GetId());
6247 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6248 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6250 auras2remove
.clear();
6251 AuraMap
const& auras
= GetAuras();
6252 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6254 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6255 auras2remove
.push_back(i
->second
->GetId());
6257 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6258 RemoveAurasDueToSpell(auras2remove
[i
]);
6260 // cleanup combo points
6261 if(GetComboTarget()==duel
->opponent
->GetGUID())
6263 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6266 if(duel
->opponent
->GetComboTarget()==GetGUID())
6267 duel
->opponent
->ClearComboPoints();
6268 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6269 duel
->opponent
->ClearComboPoints();
6272 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6273 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6274 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6275 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6277 delete duel
->opponent
->duel
;
6278 duel
->opponent
->duel
= NULL
;
6283 //---------------------------------------------------------//
6285 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6287 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6290 // not apply/remove mods for broken item
6291 if(item
->IsBroken())
6294 ItemPrototype
const *proto
= item
->GetProto();
6299 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6301 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6302 if(attacktype
< MAX_ATTACK
)
6303 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6305 _ApplyItemBonuses(proto
,slot
,apply
);
6307 if( slot
==EQUIPMENT_SLOT_RANGED
)
6308 _ApplyAmmoBonuses();
6310 ApplyItemEquipSpell(item
,apply
);
6311 ApplyEnchantment(item
, apply
);
6313 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6314 CorrectMetaGemEnchants(slot
, apply
);
6316 sLog
.outDebug("_ApplyItemMods complete.");
6319 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6321 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6324 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6326 uint32 statType
= 0;
6329 if(proto
->ScalingStatDistribution
)
6331 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6333 statType
= ssd
->StatMod
[i
];
6335 if(uint32 modifier
= ssd
->Modifier
[i
])
6337 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6338 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6340 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6341 val
= (multiplier
* modifier
) / 10000;
6348 statType
= proto
->ItemStat
[i
].ItemStatType
;
6349 val
= proto
->ItemStat
[i
].ItemStatValue
;
6358 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6360 case ITEM_MOD_HEALTH
: // modify HP
6361 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6363 case ITEM_MOD_AGILITY
: // modify agility
6364 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6365 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6367 case ITEM_MOD_STRENGTH
: //modify strength
6368 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6369 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6371 case ITEM_MOD_INTELLECT
: //modify intellect
6372 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6373 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6375 case ITEM_MOD_SPIRIT
: //modify spirit
6376 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6377 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6379 case ITEM_MOD_STAMINA
: //modify stamina
6380 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6381 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6383 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6384 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6386 case ITEM_MOD_DODGE_RATING
:
6387 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6389 case ITEM_MOD_PARRY_RATING
:
6390 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6392 case ITEM_MOD_BLOCK_RATING
:
6393 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6395 case ITEM_MOD_HIT_MELEE_RATING
:
6396 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6398 case ITEM_MOD_HIT_RANGED_RATING
:
6399 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6401 case ITEM_MOD_HIT_SPELL_RATING
:
6402 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6404 case ITEM_MOD_CRIT_MELEE_RATING
:
6405 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6407 case ITEM_MOD_CRIT_RANGED_RATING
:
6408 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6410 case ITEM_MOD_CRIT_SPELL_RATING
:
6411 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6413 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6414 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6416 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6417 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6419 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6420 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6422 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6423 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6425 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6426 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6428 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6429 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6431 case ITEM_MOD_HASTE_MELEE_RATING
:
6432 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6434 case ITEM_MOD_HASTE_RANGED_RATING
:
6435 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6437 case ITEM_MOD_HASTE_SPELL_RATING
:
6438 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6440 case ITEM_MOD_HIT_RATING
:
6441 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6442 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6443 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6445 case ITEM_MOD_CRIT_RATING
:
6446 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6447 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6448 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6450 case ITEM_MOD_HIT_TAKEN_RATING
:
6451 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6452 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6453 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6455 case ITEM_MOD_CRIT_TAKEN_RATING
:
6456 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6457 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6458 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6460 case ITEM_MOD_RESILIENCE_RATING
:
6461 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6462 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6463 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6465 case ITEM_MOD_HASTE_RATING
:
6466 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6467 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6468 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6470 case ITEM_MOD_EXPERTISE_RATING
:
6471 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6473 case ITEM_MOD_ATTACK_POWER
:
6474 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6475 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6477 case ITEM_MOD_RANGED_ATTACK_POWER
:
6478 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6480 case ITEM_MOD_FERAL_ATTACK_POWER
:
6481 ApplyFeralAPBonus(int32(val
), apply
);
6483 case ITEM_MOD_SPELL_HEALING_DONE
:
6484 ApplySpellHealingBonus(int32(val
), apply
);
6486 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6487 ApplySpellDamageBonus(int32(val
), apply
);
6489 case ITEM_MOD_MANA_REGENERATION
:
6490 ApplyManaRegenBonus(int32(val
), apply
);
6492 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6493 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6495 case ITEM_MOD_SPELL_POWER
:
6496 ApplySpellHealingBonus(int32(val
), apply
);
6497 ApplySpellDamageBonus(int32(val
), apply
);
6503 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6506 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6509 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6512 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6514 if (proto
->NatureRes
)
6515 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6517 if (proto
->FrostRes
)
6518 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6520 if (proto
->ShadowRes
)
6521 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6523 if (proto
->ArcaneRes
)
6524 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6526 WeaponAttackType attType
= BASE_ATTACK
;
6527 float damage
= 0.0f
;
6529 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6530 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6531 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6533 attType
= RANGED_ATTACK
;
6535 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6537 attType
= OFF_ATTACK
;
6540 if (proto
->Damage
[0].DamageMin
> 0 )
6542 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6543 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6544 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6547 if (proto
->Damage
[0].DamageMax
> 0 )
6549 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6550 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6553 // Druids get feral AP bonus from weapon dps
6554 if(getClass() == CLASS_DRUID
)
6556 int32 feral_bonus
= proto
->getFeralBonus();
6557 if (feral_bonus
> 0)
6558 ApplyFeralAPBonus(feral_bonus
, apply
);
6561 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6566 if(slot
== EQUIPMENT_SLOT_RANGED
)
6567 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6568 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6569 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6570 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6571 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6574 if(CanModifyStats() && (damage
|| proto
->Delay
))
6575 UpdateDamagePhysical(attType
);
6578 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6580 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6581 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6582 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6584 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6585 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6586 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6588 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6589 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6590 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6593 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6595 // generic not weapon specific case processes in aura code
6596 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6599 BaseModGroup mod
= BASEMOD_END
;
6602 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6603 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6604 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6608 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6610 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6614 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6616 // ignore spell mods for not wands
6617 Modifier
const* modifier
= aura
->GetModifier();
6618 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6621 // generic not weapon specific case processes in aura code
6622 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6625 UnitMods unitMod
= UNIT_MOD_END
;
6628 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6629 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6630 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6634 UnitModifierType unitModType
= TOTAL_VALUE
;
6635 switch(modifier
->m_auraname
)
6637 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6638 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6642 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6644 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6648 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6653 ItemPrototype
const *proto
= item
->GetProto();
6657 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6659 _Spell
const& spellData
= proto
->Spells
[i
];
6662 if(!spellData
.SpellId
)
6665 // wrong triggering type
6666 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6669 // check if it is valid spell
6670 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6674 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6678 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6682 // Cannot be used in this stance/form
6683 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
6686 if(form_change
) // check aura active state from other form
6689 for (int k
=0; k
< 3; ++k
)
6691 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6692 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6694 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6704 if(found
) // and skip re-cast already active aura at form change
6708 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6710 CastSpell(this,spellInfo
,true,item
);
6714 if(form_change
) // check aura compatibility
6716 // Cannot be used in this stance/form
6717 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
6718 return; // and remove only not compatible at form change
6722 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6724 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6728 void Player::UpdateEquipSpellsAtFormChange()
6730 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6732 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6734 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6735 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6739 // item set bonuses not dependent from item broken state
6740 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6742 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6746 for(uint32 y
=0;y
<8; ++y
)
6748 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6752 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6753 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6758 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6760 if(!item
|| item
->IsBroken())
6763 ItemPrototype
const *proto
= item
->GetProto();
6767 if (!Target
|| Target
== this )
6770 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6772 _Spell
const& spellData
= proto
->Spells
[i
];
6775 if(!spellData
.SpellId
)
6778 // wrong triggering type
6779 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6782 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6785 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6789 // not allow proc extra attack spell at extra attack
6790 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6793 float chance
= spellInfo
->procChance
;
6795 if(spellData
.SpellPPMRate
)
6797 uint32 WeaponSpeed
= GetAttackTime(attType
);
6798 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6800 else if(chance
> 100.0f
)
6802 chance
= GetWeaponProcChance();
6805 if (roll_chance_f(chance
))
6806 CastSpell(Target
, spellInfo
->Id
, true, item
);
6809 // item combat enchantments
6810 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6812 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6813 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6814 if(!pEnchant
) continue;
6815 for (int s
=0;s
<3;s
++)
6817 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6820 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6823 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6827 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6828 if (roll_chance_f(chance
))
6830 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6831 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6833 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6839 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
6841 ItemPrototype
const* proto
= item
->GetProto();
6842 // special learning case
6843 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
6845 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
6846 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
6848 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
6851 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
6852 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
6856 Spell
*spell
= new Spell(this, spellInfo
, false);
6857 spell
->m_CastItem
= item
;
6858 spell
->m_cast_count
= cast_count
; //set count of casts
6859 spell
->m_currentBasePoints
[0] = learning_spell_id
;
6860 spell
->prepare(&targets
);
6864 // use triggered flag only for items with many spell casts and for not first cast
6867 // item spells casted at use
6868 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6870 _Spell
const& spellData
= proto
->Spells
[i
];
6873 if(!spellData
.SpellId
)
6876 // wrong triggering type
6877 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
6880 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6883 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
6887 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6888 spell
->m_CastItem
= item
;
6889 spell
->m_cast_count
= cast_count
; // set count of casts
6890 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6891 spell
->prepare(&targets
);
6896 // Item enchantments spells casted at use
6897 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6899 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6900 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6901 if(!pEnchant
) continue;
6902 for (int s
=0;s
<3;s
++)
6904 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
6907 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6910 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6914 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6915 spell
->m_CastItem
= item
;
6916 spell
->m_cast_count
= cast_count
; // set count of casts
6917 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6918 spell
->prepare(&targets
);
6925 void Player::_RemoveAllItemMods()
6927 sLog
.outDebug("_RemoveAllItemMods start.");
6929 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6933 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6937 // item set bonuses not dependent from item broken state
6939 RemoveItemsSetItem(this,proto
);
6941 if(m_items
[i
]->IsBroken())
6944 ApplyItemEquipSpell(m_items
[i
],false);
6945 ApplyEnchantment(m_items
[i
], false);
6949 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6953 if(m_items
[i
]->IsBroken())
6955 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6959 uint32 attacktype
= Player::GetAttackBySlot(i
);
6960 if(attacktype
< MAX_ATTACK
)
6961 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6963 _ApplyItemBonuses(proto
,i
, false);
6965 if( i
== EQUIPMENT_SLOT_RANGED
)
6966 _ApplyAmmoBonuses();
6970 sLog
.outDebug("_RemoveAllItemMods complete.");
6973 void Player::_ApplyAllItemMods()
6975 sLog
.outDebug("_ApplyAllItemMods start.");
6977 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6981 if(m_items
[i
]->IsBroken())
6984 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6988 uint32 attacktype
= Player::GetAttackBySlot(i
);
6989 if(attacktype
< MAX_ATTACK
)
6990 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6992 _ApplyItemBonuses(proto
,i
, true);
6994 if( i
== EQUIPMENT_SLOT_RANGED
)
6995 _ApplyAmmoBonuses();
6999 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7003 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7007 // item set bonuses not dependent from item broken state
7009 AddItemsSetItem(this,m_items
[i
]);
7011 if(m_items
[i
]->IsBroken())
7014 ApplyItemEquipSpell(m_items
[i
],true);
7015 ApplyEnchantment(m_items
[i
], true);
7019 sLog
.outDebug("_ApplyAllItemMods complete.");
7022 void Player::_ApplyAmmoBonuses()
7025 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7029 float currentAmmoDPS
;
7031 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7032 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7033 currentAmmoDPS
= 0.0f
;
7035 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7037 if(currentAmmoDPS
== GetAmmoDPS())
7040 m_ammoDPS
= currentAmmoDPS
;
7042 if(CanModifyStats())
7043 UpdateDamagePhysical(RANGED_ATTACK
);
7046 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7051 // check ranged weapon
7052 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7053 if(!weapon
|| weapon
->IsBroken() )
7056 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7057 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7060 // check ammo ws. weapon compatibility
7061 switch(weapon_proto
->SubClass
)
7063 case ITEM_SUBCLASS_WEAPON_BOW
:
7064 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7065 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7068 case ITEM_SUBCLASS_WEAPON_GUN
:
7069 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7079 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7080 Called by remove insignia spell effect */
7081 void Player::RemovedInsignia(Player
* looterPlr
)
7083 if (!GetBattleGroundId())
7086 // If not released spirit, do it !
7087 if(m_deathTimer
> 0)
7094 Corpse
*corpse
= GetCorpse();
7098 // We have to convert player corpse to bones, not to be able to resurrect there
7099 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7100 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7104 // Now we must make bones lootable, and send player loot
7105 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7107 // We store the level of our player in the gold field
7108 // We retrieve this information at Player::SendLoot()
7109 bones
->loot
.gold
= getLevel();
7110 bones
->lootRecipient
= looterPlr
;
7111 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7114 void Player::SendLootRelease( uint64 guid
)
7116 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7117 data
<< uint64(guid
) << uint8(1);
7118 SendDirectMessage( &data
);
7121 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7123 if (uint64 lguid
= GetLootGUID())
7124 m_session
->DoLootRelease(lguid
);
7127 PermissionTypes permission
= ALL_PERMISSION
;
7129 sLog
.outDebug("Player::SendLoot");
7130 if (IS_GAMEOBJECT_GUID(guid
))
7132 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7133 GameObject
*go
= GetMap()->GetGameObject(guid
);
7135 // not check distance for GO in case owned GO (fishing bobber case, for example)
7136 // And permit out of range GO with no owner in case fishing hole
7137 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7139 SendLootRelease(guid
);
7145 if (go
->getLootState() == GO_READY
)
7147 uint32 lootid
= go
->GetLootId();
7151 sLog
.outDebug(" if(lootid)");
7153 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7156 if (loot_type
== LOOT_FISHING
)
7157 go
->getFishLoot(loot
,this);
7159 go
->SetLootState(GO_ACTIVATED
);
7162 else if (IS_ITEM_GUID(guid
))
7164 Item
*item
= GetItemByGuid( guid
);
7168 SendLootRelease(guid
);
7174 if (!item
->m_lootGenerated
)
7176 item
->m_lootGenerated
= true;
7181 case LOOT_DISENCHANTING
:
7182 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7184 case LOOT_PROSPECTING
:
7185 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7188 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7191 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7192 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7197 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7199 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7201 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7203 SendLootRelease(guid
);
7207 loot
= &bones
->loot
;
7209 if (!bones
->lootForBody
)
7211 bones
->lootForBody
= true;
7212 uint32 pLevel
= bones
->loot
.gold
;
7213 bones
->loot
.clear();
7214 // It may need a better formula
7215 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7216 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7219 if (bones
->lootRecipient
!= this)
7220 permission
= NONE_PERMISSION
;
7224 Creature
*creature
= GetMap()->GetCreature(guid
);
7226 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7227 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7229 SendLootRelease(guid
);
7233 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7235 SendLootRelease(guid
);
7239 loot
= &creature
->loot
;
7241 if (loot_type
== LOOT_PICKPOCKETING
)
7243 if (!creature
->lootForPickPocketed
)
7245 creature
->lootForPickPocketed
= true;
7248 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7249 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7251 // Generate extra money for pick pocket loot
7252 const uint32 a
= urand(0, creature
->getLevel()/2);
7253 const uint32 b
= urand(0, getLevel()/2);
7254 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7259 // the player whose group may loot the corpse
7260 Player
*recipient
= creature
->GetLootRecipient();
7263 creature
->SetLootRecipient(this);
7267 if (creature
->lootForPickPocketed
)
7269 creature
->lootForPickPocketed
= false;
7273 if (!creature
->lootForBody
)
7275 creature
->lootForBody
= true;
7278 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7279 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7281 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7283 if (Group
* group
= recipient
->GetGroup())
7285 group
->UpdateLooterGuid(creature
,true);
7287 switch (group
->GetLootMethod())
7290 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7291 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7293 case NEED_BEFORE_GREED
:
7294 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7297 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7305 // possible only if creature->lootForBody && loot->empty() at spell cast check
7306 if (loot_type
== LOOT_SKINNING
)
7309 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7311 // set group rights only for loot_type != LOOT_SKINNING
7314 if(Group
* group
= GetGroup())
7316 if (group
== recipient
->GetGroup())
7318 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7319 permission
= ALL_PERMISSION
;
7320 else if (group
->GetLooterGuid() == GetGUID())
7322 if (group
->GetLootMethod() == MASTER_LOOT
)
7323 permission
= MASTER_PERMISSION
;
7325 permission
= ALL_PERMISSION
;
7328 permission
= GROUP_PERMISSION
;
7331 permission
= NONE_PERMISSION
;
7333 else if (recipient
== this)
7334 permission
= ALL_PERMISSION
;
7336 permission
= NONE_PERMISSION
;
7343 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7346 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7347 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7351 // need know merged fishing/corpse loot type for achievements
7352 loot
->loot_type
= loot_type
;
7354 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7356 data
<< uint64(guid
);
7357 data
<< uint8(loot_type
);
7358 data
<< LootView(*loot
, this, permission
);
7360 SendDirectMessage(&data
);
7362 // add 'this' player as one of the players that are looting 'loot'
7363 if (permission
!= NONE_PERMISSION
)
7364 loot
->AddLooter(GetGUID());
7366 if (loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
))
7367 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7370 void Player::SendNotifyLootMoneyRemoved()
7372 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7373 GetSession()->SendPacket( &data
);
7376 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7378 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7379 data
<< uint8(lootSlot
);
7380 GetSession()->SendPacket( &data
);
7383 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7385 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7388 GetSession()->SendPacket(&data
);
7391 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7393 // data depends on zoneid/mapid...
7394 BattleGround
* bg
= GetBattleGround();
7395 uint16 NumberOfFields
= 0;
7396 uint32 mapid
= GetMapId();
7398 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7400 // may be exist better way to do this...
7423 NumberOfFields
= 41;
7426 NumberOfFields
= 15;
7429 NumberOfFields
= 83;
7432 NumberOfFields
= 16;
7436 NumberOfFields
= 40;
7439 NumberOfFields
= 27;
7442 NumberOfFields
= 39;
7445 NumberOfFields
= 38;
7448 NumberOfFields
= 37;
7453 NumberOfFields
= 11;
7456 NumberOfFields
= 11;
7459 NumberOfFields
= 12;
7463 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7464 data
<< uint32(mapid
); // mapid
7465 data
<< uint32(zoneid
); // zone id
7466 data
<< uint32(areaid
); // area id, new 2.1.0
7467 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7468 data
<< uint32(0x8d8) << uint32(0x0); // 1
7469 data
<< uint32(0x8d7) << uint32(0x0); // 2
7470 data
<< uint32(0x8d6) << uint32(0x0); // 3
7471 data
<< uint32(0x8d5) << uint32(0x0); // 4
7472 data
<< uint32(0x8d4) << uint32(0x0); // 5
7473 data
<< uint32(0x8d3) << uint32(0x0); // 6
7474 // 7 1 - Arena season in progress, 0 - end of season
7475 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7476 // 8 Arena season id
7477 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7478 if(mapid
== 530) // Outland
7480 data
<< uint32(0x9bf) << uint32(0x0); // 7
7481 data
<< uint32(0x9bd) << uint32(0xF); // 8
7482 data
<< uint32(0x9bb) << uint32(0xF); // 9
7497 data
<< uint32(0x7ae) << uint32(0x1); // 7
7498 data
<< uint32(0x532) << uint32(0x1); // 8
7499 data
<< uint32(0x531) << uint32(0x0); // 9
7500 data
<< uint32(0x52e) << uint32(0x0); // 10
7501 data
<< uint32(0x571) << uint32(0x0); // 11
7502 data
<< uint32(0x570) << uint32(0x0); // 12
7503 data
<< uint32(0x567) << uint32(0x1); // 13
7504 data
<< uint32(0x566) << uint32(0x1); // 14
7505 data
<< uint32(0x550) << uint32(0x1); // 15
7506 data
<< uint32(0x544) << uint32(0x0); // 16
7507 data
<< uint32(0x536) << uint32(0x0); // 17
7508 data
<< uint32(0x535) << uint32(0x1); // 18
7509 data
<< uint32(0x518) << uint32(0x0); // 19
7510 data
<< uint32(0x517) << uint32(0x0); // 20
7511 data
<< uint32(0x574) << uint32(0x0); // 21
7512 data
<< uint32(0x573) << uint32(0x0); // 22
7513 data
<< uint32(0x572) << uint32(0x0); // 23
7514 data
<< uint32(0x56f) << uint32(0x0); // 24
7515 data
<< uint32(0x56e) << uint32(0x0); // 25
7516 data
<< uint32(0x56d) << uint32(0x0); // 26
7517 data
<< uint32(0x56c) << uint32(0x0); // 27
7518 data
<< uint32(0x56b) << uint32(0x0); // 28
7519 data
<< uint32(0x56a) << uint32(0x1); // 29
7520 data
<< uint32(0x569) << uint32(0x1); // 30
7521 data
<< uint32(0x568) << uint32(0x1); // 13
7522 data
<< uint32(0x565) << uint32(0x0); // 32
7523 data
<< uint32(0x564) << uint32(0x0); // 33
7524 data
<< uint32(0x563) << uint32(0x0); // 34
7525 data
<< uint32(0x562) << uint32(0x0); // 35
7526 data
<< uint32(0x561) << uint32(0x0); // 36
7527 data
<< uint32(0x560) << uint32(0x0); // 37
7528 data
<< uint32(0x55f) << uint32(0x0); // 38
7529 data
<< uint32(0x55e) << uint32(0x0); // 39
7530 data
<< uint32(0x55d) << uint32(0x0); // 40
7531 data
<< uint32(0x3c6) << uint32(0x4); // 41
7532 data
<< uint32(0x3c4) << uint32(0x6); // 42
7533 data
<< uint32(0x3c2) << uint32(0x4); // 43
7534 data
<< uint32(0x516) << uint32(0x1); // 44
7535 data
<< uint32(0x515) << uint32(0x0); // 45
7536 data
<< uint32(0x3b6) << uint32(0x6); // 46
7537 data
<< uint32(0x55c) << uint32(0x0); // 47
7538 data
<< uint32(0x55b) << uint32(0x0); // 48
7539 data
<< uint32(0x55a) << uint32(0x0); // 49
7540 data
<< uint32(0x559) << uint32(0x0); // 50
7541 data
<< uint32(0x558) << uint32(0x0); // 51
7542 data
<< uint32(0x557) << uint32(0x0); // 52
7543 data
<< uint32(0x556) << uint32(0x0); // 53
7544 data
<< uint32(0x555) << uint32(0x0); // 54
7545 data
<< uint32(0x554) << uint32(0x1); // 55
7546 data
<< uint32(0x553) << uint32(0x1); // 56
7547 data
<< uint32(0x552) << uint32(0x1); // 57
7548 data
<< uint32(0x551) << uint32(0x1); // 58
7549 data
<< uint32(0x54f) << uint32(0x0); // 59
7550 data
<< uint32(0x54e) << uint32(0x0); // 60
7551 data
<< uint32(0x54d) << uint32(0x1); // 61
7552 data
<< uint32(0x54c) << uint32(0x0); // 62
7553 data
<< uint32(0x54b) << uint32(0x0); // 63
7554 data
<< uint32(0x545) << uint32(0x0); // 64
7555 data
<< uint32(0x543) << uint32(0x1); // 65
7556 data
<< uint32(0x542) << uint32(0x0); // 66
7557 data
<< uint32(0x540) << uint32(0x0); // 67
7558 data
<< uint32(0x53f) << uint32(0x0); // 68
7559 data
<< uint32(0x53e) << uint32(0x0); // 69
7560 data
<< uint32(0x53d) << uint32(0x0); // 70
7561 data
<< uint32(0x53c) << uint32(0x0); // 71
7562 data
<< uint32(0x53b) << uint32(0x0); // 72
7563 data
<< uint32(0x53a) << uint32(0x1); // 73
7564 data
<< uint32(0x539) << uint32(0x0); // 74
7565 data
<< uint32(0x538) << uint32(0x0); // 75
7566 data
<< uint32(0x537) << uint32(0x0); // 76
7567 data
<< uint32(0x534) << uint32(0x0); // 77
7568 data
<< uint32(0x533) << uint32(0x0); // 78
7569 data
<< uint32(0x530) << uint32(0x0); // 79
7570 data
<< uint32(0x52f) << uint32(0x0); // 80
7571 data
<< uint32(0x52d) << uint32(0x1); // 81
7574 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7575 bg
->FillInitialWorldStates(data
);
7578 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7579 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7580 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7581 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7582 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7583 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7584 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7585 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7589 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7590 bg
->FillInitialWorldStates(data
);
7593 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7594 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7595 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7596 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7597 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7598 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7599 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7600 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7601 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7602 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7603 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7604 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7605 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7606 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7607 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7608 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7609 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7610 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7611 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7612 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7613 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7614 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7615 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7616 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7617 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7618 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7619 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7620 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7621 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7622 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7623 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7624 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7628 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7629 bg
->FillInitialWorldStates(data
);
7632 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7633 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7634 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7635 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7636 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7637 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7638 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7639 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7640 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7641 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7642 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7643 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7644 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7645 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7646 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7647 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7648 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7649 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7650 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7651 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7652 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7653 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7654 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7655 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7656 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7657 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7658 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7659 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7660 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7661 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7662 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7663 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7664 // and some more ... unknown
7667 case 3483: // Hellfire Peninsula
7668 data
<< uint32(0x9ba) << uint32(0x1); // 10
7669 data
<< uint32(0x9b9) << uint32(0x1); // 11
7670 data
<< uint32(0x9b5) << uint32(0x0); // 12
7671 data
<< uint32(0x9b4) << uint32(0x1); // 13
7672 data
<< uint32(0x9b3) << uint32(0x0); // 14
7673 data
<< uint32(0x9b2) << uint32(0x0); // 15
7674 data
<< uint32(0x9b1) << uint32(0x1); // 16
7675 data
<< uint32(0x9b0) << uint32(0x0); // 17
7676 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7677 data
<< uint32(0x9ac) << uint32(0x0); // 19
7678 data
<< uint32(0x9a8) << uint32(0x0); // 20
7679 data
<< uint32(0x9a7) << uint32(0x0); // 21
7680 data
<< uint32(0x9a6) << uint32(0x1); // 22
7682 case 3519: // Terokkar Forest
7683 data
<< uint32(0xa41) << uint32(0x0); // 10
7684 data
<< uint32(0xa40) << uint32(0x14); // 11
7685 data
<< uint32(0xa3f) << uint32(0x0); // 12
7686 data
<< uint32(0xa3e) << uint32(0x0); // 13
7687 data
<< uint32(0xa3d) << uint32(0x5); // 14
7688 data
<< uint32(0xa3c) << uint32(0x0); // 15
7689 data
<< uint32(0xa87) << uint32(0x0); // 16
7690 data
<< uint32(0xa86) << uint32(0x0); // 17
7691 data
<< uint32(0xa85) << uint32(0x0); // 18
7692 data
<< uint32(0xa84) << uint32(0x0); // 19
7693 data
<< uint32(0xa83) << uint32(0x0); // 20
7694 data
<< uint32(0xa82) << uint32(0x0); // 21
7695 data
<< uint32(0xa81) << uint32(0x0); // 22
7696 data
<< uint32(0xa80) << uint32(0x0); // 23
7697 data
<< uint32(0xa7e) << uint32(0x0); // 24
7698 data
<< uint32(0xa7d) << uint32(0x0); // 25
7699 data
<< uint32(0xa7c) << uint32(0x0); // 26
7700 data
<< uint32(0xa7b) << uint32(0x0); // 27
7701 data
<< uint32(0xa7a) << uint32(0x0); // 28
7702 data
<< uint32(0xa79) << uint32(0x0); // 29
7703 data
<< uint32(0x9d0) << uint32(0x5); // 30
7704 data
<< uint32(0x9ce) << uint32(0x0); // 31
7705 data
<< uint32(0x9cd) << uint32(0x0); // 32
7706 data
<< uint32(0x9cc) << uint32(0x0); // 33
7707 data
<< uint32(0xa88) << uint32(0x0); // 34
7708 data
<< uint32(0xad0) << uint32(0x0); // 35
7709 data
<< uint32(0xacf) << uint32(0x1); // 36
7711 case 3521: // Zangarmarsh
7712 data
<< uint32(0x9e1) << uint32(0x0); // 10
7713 data
<< uint32(0x9e0) << uint32(0x0); // 11
7714 data
<< uint32(0x9df) << uint32(0x0); // 12
7715 data
<< uint32(0xa5d) << uint32(0x1); // 13
7716 data
<< uint32(0xa5c) << uint32(0x0); // 14
7717 data
<< uint32(0xa5b) << uint32(0x1); // 15
7718 data
<< uint32(0xa5a) << uint32(0x0); // 16
7719 data
<< uint32(0xa59) << uint32(0x1); // 17
7720 data
<< uint32(0xa58) << uint32(0x0); // 18
7721 data
<< uint32(0xa57) << uint32(0x0); // 19
7722 data
<< uint32(0xa56) << uint32(0x0); // 20
7723 data
<< uint32(0xa55) << uint32(0x1); // 21
7724 data
<< uint32(0xa54) << uint32(0x0); // 22
7725 data
<< uint32(0x9e7) << uint32(0x0); // 23
7726 data
<< uint32(0x9e6) << uint32(0x0); // 24
7727 data
<< uint32(0x9e5) << uint32(0x0); // 25
7728 data
<< uint32(0xa00) << uint32(0x0); // 26
7729 data
<< uint32(0x9ff) << uint32(0x1); // 27
7730 data
<< uint32(0x9fe) << uint32(0x0); // 28
7731 data
<< uint32(0x9fd) << uint32(0x0); // 29
7732 data
<< uint32(0x9fc) << uint32(0x1); // 30
7733 data
<< uint32(0x9fb) << uint32(0x0); // 31
7734 data
<< uint32(0xa62) << uint32(0x0); // 32
7735 data
<< uint32(0xa61) << uint32(0x1); // 33
7736 data
<< uint32(0xa60) << uint32(0x1); // 34
7737 data
<< uint32(0xa5f) << uint32(0x0); // 35
7739 case 3698: // Nagrand Arena
7740 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
7741 bg
->FillInitialWorldStates(data
);
7744 data
<< uint32(0xa0f) << uint32(0x0); // 7
7745 data
<< uint32(0xa10) << uint32(0x0); // 8
7746 data
<< uint32(0xa11) << uint32(0x0); // 9 show
7749 case 3702: // Blade's Edge Arena
7750 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
7751 bg
->FillInitialWorldStates(data
);
7754 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
7755 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
7756 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
7759 case 3968: // Ruins of Lordaeron
7760 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
7761 bg
->FillInitialWorldStates(data
);
7764 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
7765 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
7766 data
<< uint32(0xbba) << uint32(0x0); // 9 show
7769 case 3703: // Shattrath City
7772 data
<< uint32(0x914) << uint32(0x0); // 7
7773 data
<< uint32(0x913) << uint32(0x0); // 8
7774 data
<< uint32(0x912) << uint32(0x0); // 9
7775 data
<< uint32(0x915) << uint32(0x0); // 10
7778 GetSession()->SendPacket(&data
);
7781 uint32
Player::GetXPRestBonus(uint32 xp
)
7783 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7785 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7788 SetRestBonus( GetRestBonus() - rested_bonus
);
7790 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7791 return rested_bonus
;
7794 void Player::SetBindPoint(uint64 guid
)
7796 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7797 data
<< uint64(guid
);
7798 GetSession()->SendPacket( &data
);
7801 void Player::SendTalentWipeConfirm(uint64 guid
)
7803 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7804 data
<< uint64(guid
);
7805 data
<< uint32(resetTalentsCost());
7806 GetSession()->SendPacket( &data
);
7809 void Player::SendPetSkillWipeConfirm()
7811 Pet
* pet
= GetPet();
7814 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7815 data
<< pet
->GetGUID();
7816 data
<< uint32(pet
->resetTalentsCost());
7817 GetSession()->SendPacket( &data
);
7820 /*********************************************************/
7821 /*** STORAGE SYSTEM ***/
7822 /*********************************************************/
7824 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7829 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7831 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7835 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7836 else if(charges
<= 1)
7838 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7839 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7844 void Player::SetSheath( uint32 sheathed
)
7848 case SHEATH_STATE_UNARMED
: // no prepared weapon
7849 SetVirtualItemSlot(0,NULL
);
7850 SetVirtualItemSlot(1,NULL
);
7851 SetVirtualItemSlot(2,NULL
);
7853 case SHEATH_STATE_MELEE
: // prepared melee weapon
7855 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7856 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7857 SetVirtualItemSlot(2,NULL
);
7859 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7860 SetVirtualItemSlot(0,NULL
);
7861 SetVirtualItemSlot(1,NULL
);
7862 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7865 SetVirtualItemSlot(0,NULL
);
7866 SetVirtualItemSlot(1,NULL
);
7867 SetVirtualItemSlot(2,NULL
);
7870 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7873 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7875 uint8 pClass
= getClass();
7878 slots
[0] = NULL_SLOT
;
7879 slots
[1] = NULL_SLOT
;
7880 slots
[2] = NULL_SLOT
;
7881 slots
[3] = NULL_SLOT
;
7882 switch( proto
->InventoryType
)
7885 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7888 slots
[0] = EQUIPMENT_SLOT_NECK
;
7890 case INVTYPE_SHOULDERS
:
7891 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7894 slots
[0] = EQUIPMENT_SLOT_BODY
;
7897 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7900 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7903 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7906 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7909 slots
[0] = EQUIPMENT_SLOT_FEET
;
7911 case INVTYPE_WRISTS
:
7912 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7915 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7917 case INVTYPE_FINGER
:
7918 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7919 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7921 case INVTYPE_TRINKET
:
7922 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7923 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7926 slots
[0] = EQUIPMENT_SLOT_BACK
;
7928 case INVTYPE_WEAPON
:
7930 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7932 // suggest offhand slot only if know dual wielding
7933 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7935 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7938 case INVTYPE_SHIELD
:
7939 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7941 case INVTYPE_RANGED
:
7942 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7944 case INVTYPE_2HWEAPON
:
7945 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7946 if (CanDualWield() && CanTitanGrip())
7947 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7949 case INVTYPE_TABARD
:
7950 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7952 case INVTYPE_WEAPONMAINHAND
:
7953 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7955 case INVTYPE_WEAPONOFFHAND
:
7956 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7958 case INVTYPE_HOLDABLE
:
7959 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7961 case INVTYPE_THROWN
:
7962 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7964 case INVTYPE_RANGEDRIGHT
:
7965 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7968 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
7969 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
7970 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
7971 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
7975 switch(proto
->SubClass
)
7977 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7978 if (pClass
== CLASS_PALADIN
)
7979 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7981 case ITEM_SUBCLASS_ARMOR_IDOL
:
7982 if (pClass
== CLASS_DRUID
)
7983 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7985 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7986 if (pClass
== CLASS_SHAMAN
)
7987 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7989 case ITEM_SUBCLASS_ARMOR_MISC
:
7990 if (pClass
== CLASS_WARLOCK
)
7991 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7993 case ITEM_SUBCLASS_ARMOR_SIGIL
:
7994 if (pClass
== CLASS_DEATH_KNIGHT
)
7995 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8004 if( slot
!= NULL_SLOT
)
8006 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8008 for (int i
= 0; i
< 4; ++i
)
8010 if ( slots
[i
] == slot
)
8017 // search free slot at first
8018 for (int i
= 0; i
< 4; ++i
)
8020 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8022 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8023 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8028 // if not found free and can swap return first appropriate from used
8029 for (int i
= 0; i
< 4; ++i
)
8031 if ( slots
[i
] != NULL_SLOT
&& swap
)
8040 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8043 uint32 tempcount
= 0;
8045 uint8 res
= EQUIP_ERR_OK
;
8047 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8049 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8050 if( pItem
&& pItem
->GetEntry() == item
)
8052 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8053 if(ires
==EQUIP_ERR_OK
)
8055 tempcount
+= pItem
->GetCount();
8056 if( tempcount
>= count
)
8057 return EQUIP_ERR_OK
;
8063 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8065 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8066 if( pItem
&& pItem
->GetEntry() == item
)
8068 tempcount
+= pItem
->GetCount();
8069 if( tempcount
>= count
)
8070 return EQUIP_ERR_OK
;
8073 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8075 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8076 if( pItem
&& pItem
->GetEntry() == item
)
8078 tempcount
+= pItem
->GetCount();
8079 if( tempcount
>= count
)
8080 return EQUIP_ERR_OK
;
8084 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8086 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8089 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8091 pItem
= GetItemByPos( i
, j
);
8092 if( pItem
&& pItem
->GetEntry() == item
)
8094 tempcount
+= pItem
->GetCount();
8095 if( tempcount
>= count
)
8096 return EQUIP_ERR_OK
;
8102 // not found req. item count and have unequippable items
8106 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8109 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8111 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8112 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8113 count
+= pItem
->GetCount();
8115 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8117 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8118 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8119 count
+= pItem
->GetCount();
8121 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8123 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8125 count
+= pBag
->GetItemCount(item
,skipItem
);
8128 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8130 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8132 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8133 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8134 count
+= pItem
->GetGemCountWithID(item
);
8140 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8142 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8143 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8144 count
+= pItem
->GetCount();
8146 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8148 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8150 count
+= pBag
->GetItemCount(item
,skipItem
);
8153 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8155 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8157 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8158 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8159 count
+= pItem
->GetGemCountWithID(item
);
8167 Item
* Player::GetItemByGuid( uint64 guid
) const
8169 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8171 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8172 if( pItem
&& pItem
->GetGUID() == guid
)
8175 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8177 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8178 if( pItem
&& pItem
->GetGUID() == guid
)
8182 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8184 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8187 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8189 Item
* pItem
= pBag
->GetItemByPos( j
);
8190 if( pItem
&& pItem
->GetGUID() == guid
)
8195 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8197 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8200 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8202 Item
* pItem
= pBag
->GetItemByPos( j
);
8203 if( pItem
&& pItem
->GetGUID() == guid
)
8212 Item
* Player::GetItemByPos( uint16 pos
) const
8214 uint8 bag
= pos
>> 8;
8215 uint8 slot
= pos
& 255;
8216 return GetItemByPos( bag
, slot
);
8219 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8221 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8222 return m_items
[slot
];
8223 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8224 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8226 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8228 return pBag
->GetItemByPos(slot
);
8233 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8238 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8239 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8240 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8241 default: return NULL
;
8244 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8245 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8251 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8257 Item
* Player::GetShield(bool useable
) const
8259 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8260 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8266 if( item
->IsBroken())
8272 uint32
Player::GetAttackBySlot( uint8 slot
)
8276 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8277 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8278 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8279 default: return MAX_ATTACK
;
8283 bool Player::HasBankBagSlot( uint8 slot
) const
8285 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8286 if( slot
< maxslot
)
8291 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8293 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8295 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8297 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8299 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8304 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8306 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8308 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8313 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8315 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8317 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8319 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8324 bool Player::IsBagPos( uint16 pos
)
8326 uint8 bag
= pos
>> 8;
8327 uint8 slot
= pos
& 255;
8328 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8330 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8335 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8341 if (bag
== INVENTORY_SLOT_BAG_0
)
8343 // any post selected
8344 if (slot
== NULL_SLOT
)
8348 if (slot
< EQUIPMENT_SLOT_END
)
8352 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8356 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8360 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8364 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8368 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8374 // bag content slots
8375 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8377 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8381 // any post selected
8382 if (slot
== NULL_SLOT
)
8385 return slot
< pBag
->GetBagSize();
8388 // bank bag content slots
8389 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8391 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8395 // any post selected
8396 if (slot
== NULL_SLOT
)
8399 return slot
< pBag
->GetBagSize();
8407 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8409 uint32 tempcount
= 0;
8410 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8412 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8413 if( pItem
&& pItem
->GetEntry() == item
)
8415 tempcount
+= pItem
->GetCount();
8416 if( tempcount
>= count
)
8420 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8422 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8423 if( pItem
&& pItem
->GetEntry() == item
)
8425 tempcount
+= pItem
->GetCount();
8426 if( tempcount
>= count
)
8430 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8432 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8434 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8436 Item
* pItem
= GetItemByPos( i
, j
);
8437 if( pItem
&& pItem
->GetEntry() == item
)
8439 tempcount
+= pItem
->GetCount();
8440 if( tempcount
>= count
)
8449 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8451 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8452 if( pItem
&& pItem
->GetEntry() == item
)
8454 tempcount
+= pItem
->GetCount();
8455 if( tempcount
>= count
)
8459 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8461 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8463 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8465 Item
* pItem
= GetItemByPos( i
, j
);
8466 if( pItem
&& pItem
->GetEntry() == item
)
8468 tempcount
+= pItem
->GetCount();
8469 if( tempcount
>= count
)
8480 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8482 uint32 tempcount
= 0;
8483 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8485 if(i
==int(except_slot
))
8488 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8489 if( pItem
&& pItem
->GetEntry() == item
)
8491 tempcount
+= pItem
->GetCount();
8492 if( tempcount
>= count
)
8497 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8498 if (pProto
&& pProto
->GemProperties
)
8500 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8502 if(i
==int(except_slot
))
8505 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8506 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8508 tempcount
+= pItem
->GetGemCountWithID(item
);
8509 if( tempcount
>= count
)
8518 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8520 uint32 tempcount
= 0;
8521 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8523 if(i
==int(except_slot
))
8526 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8530 ItemPrototype
const *pProto
= pItem
->GetProto();
8534 if (pProto
->ItemLimitCategory
== limitCategory
)
8536 tempcount
+= pItem
->GetCount();
8537 if( tempcount
>= count
)
8541 if( pProto
->Socket
[0].Color
)
8543 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8544 if( tempcount
>= count
)
8552 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8554 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8558 *no_space_count
= count
;
8559 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8563 if(pProto
->MaxCount
<= 0)
8564 return EQUIP_ERR_OK
;
8566 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8568 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8571 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8572 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8575 return EQUIP_ERR_OK
;
8578 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8581 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8583 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8584 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8587 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8589 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8590 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8593 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8595 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8597 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8599 pItem
= GetItemByPos( i
, j
);
8600 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8608 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8610 Item
* pItem2
= GetItemByPos( bag
, slot
);
8612 // ignore move item (this slot will be empty at move)
8613 if(pItem2
==pSrcItem
)
8618 // empty specific slot - check item fit to slot
8619 if( !pItem2
|| swap
)
8621 if( bag
== INVENTORY_SLOT_BAG_0
)
8624 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8625 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8627 // vanitypet case (not use, vanity pets stored as spells)
8628 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8629 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8631 // currencytoken case (disabled until proper implement)
8632 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8633 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8635 // guestbag case (not use)
8636 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
)
8637 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8640 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8641 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8645 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8647 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8649 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8651 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8653 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8654 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8657 // non empty stack with space
8658 need_space
= pProto
->GetMaxStackSize();
8660 // non empty slot, check item type
8664 if(pItem2
->GetEntry() != pProto
->ItemId
)
8665 return EQUIP_ERR_ITEM_CANT_STACK
;
8668 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8669 return EQUIP_ERR_ITEM_CANT_STACK
;
8671 // free stack space or infinity
8672 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8675 if(need_space
> count
)
8678 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8679 if(!newPosition
.isContainedIn(dest
))
8681 dest
.push_back(newPosition
);
8682 count
-= need_space
;
8684 return EQUIP_ERR_OK
;
8687 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
8689 // skip specific bag already processed in first called _CanStoreItem_InBag
8691 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8693 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8695 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8697 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8699 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8701 // specialized bag mode or non-specilized
8702 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8703 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8705 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8706 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8708 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8710 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8714 Item
* pItem2
= GetItemByPos( bag
, j
);
8716 // ignore move item (this slot will be empty at move)
8717 if(pItem2
==pSrcItem
)
8720 // if merge skip empty, if !merge skip non-empty
8721 if((pItem2
!=NULL
)!=merge
)
8726 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8728 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8729 if(need_space
> count
)
8732 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8733 if(!newPosition
.isContainedIn(dest
))
8735 dest
.push_back(newPosition
);
8736 count
-= need_space
;
8739 return EQUIP_ERR_OK
;
8745 uint32 need_space
= pProto
->GetMaxStackSize();
8746 if(need_space
> count
)
8749 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8750 if(!newPosition
.isContainedIn(dest
))
8752 dest
.push_back(newPosition
);
8753 count
-= need_space
;
8756 return EQUIP_ERR_OK
;
8760 return EQUIP_ERR_OK
;
8763 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
8765 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
8767 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8768 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8771 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8773 // ignore move item (this slot will be empty at move)
8774 if(pItem2
==pSrcItem
)
8777 // if merge skip empty, if !merge skip non-empty
8778 if((pItem2
!=NULL
)!=merge
)
8783 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8785 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8786 if(need_space
> count
)
8788 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8789 if(!newPosition
.isContainedIn(dest
))
8791 dest
.push_back(newPosition
);
8792 count
-= need_space
;
8795 return EQUIP_ERR_OK
;
8801 uint32 need_space
= pProto
->GetMaxStackSize();
8802 if(need_space
> count
)
8805 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8806 if(!newPosition
.isContainedIn(dest
))
8808 dest
.push_back(newPosition
);
8809 count
-= need_space
;
8812 return EQUIP_ERR_OK
;
8816 return EQUIP_ERR_OK
;
8819 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8821 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8823 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8827 *no_space_count
= count
;
8828 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8831 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8834 *no_space_count
= count
;
8835 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8838 // check count of items (skip for auto move for same player from bank)
8839 uint32 no_similar_count
= 0; // can't store this amount similar items
8840 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8841 if(res
!=EQUIP_ERR_OK
)
8843 if(count
==no_similar_count
)
8846 *no_space_count
= no_similar_count
;
8849 count
-= no_similar_count
;
8853 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8855 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8856 if(res
!=EQUIP_ERR_OK
)
8859 *no_space_count
= count
+ no_similar_count
;
8865 if(no_similar_count
==0)
8866 return EQUIP_ERR_OK
;
8869 *no_space_count
= count
+ no_similar_count
;
8870 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8874 // not specific slot or have space for partly store only in specific slot
8877 if( bag
!= NULL_BAG
)
8879 // search stack in bag for merge to
8880 if( pProto
->Stackable
!= 1 )
8882 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8884 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8885 if(res
!=EQUIP_ERR_OK
)
8888 *no_space_count
= count
+ no_similar_count
;
8894 if(no_similar_count
==0)
8895 return EQUIP_ERR_OK
;
8898 *no_space_count
= count
+ no_similar_count
;
8899 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8902 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8903 if(res
!=EQUIP_ERR_OK
)
8906 *no_space_count
= count
+ no_similar_count
;
8912 if(no_similar_count
==0)
8913 return EQUIP_ERR_OK
;
8916 *no_space_count
= count
+ no_similar_count
;
8917 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8920 else // equipped bag
8922 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8923 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8924 if(res
!=EQUIP_ERR_OK
)
8925 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8927 if(res
!=EQUIP_ERR_OK
)
8930 *no_space_count
= count
+ no_similar_count
;
8936 if(no_similar_count
==0)
8937 return EQUIP_ERR_OK
;
8940 *no_space_count
= count
+ no_similar_count
;
8941 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8946 // search free slot in bag for place to
8947 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8949 // search free slot - keyring case
8950 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8952 uint32 keyringSize
= GetMaxKeyringSize();
8953 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8954 if(res
!=EQUIP_ERR_OK
)
8957 *no_space_count
= count
+ no_similar_count
;
8963 if(no_similar_count
==0)
8964 return EQUIP_ERR_OK
;
8967 *no_space_count
= count
+ no_similar_count
;
8968 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8971 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8972 if(res
!=EQUIP_ERR_OK
)
8975 *no_space_count
= count
+ no_similar_count
;
8981 if(no_similar_count
==0)
8982 return EQUIP_ERR_OK
;
8985 *no_space_count
= count
+ no_similar_count
;
8986 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8989 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
8991 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8992 if(res
!=EQUIP_ERR_OK
)
8995 *no_space_count
= count
+ no_similar_count
;
9001 if(no_similar_count
==0)
9002 return EQUIP_ERR_OK
;
9005 *no_space_count
= count
+ no_similar_count
;
9006 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9010 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9011 if(res
!=EQUIP_ERR_OK
)
9014 *no_space_count
= count
+ no_similar_count
;
9020 if(no_similar_count
==0)
9021 return EQUIP_ERR_OK
;
9024 *no_space_count
= count
+ no_similar_count
;
9025 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9028 else // equipped bag
9030 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9031 if(res
!=EQUIP_ERR_OK
)
9032 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9034 if(res
!=EQUIP_ERR_OK
)
9037 *no_space_count
= count
+ no_similar_count
;
9043 if(no_similar_count
==0)
9044 return EQUIP_ERR_OK
;
9047 *no_space_count
= count
+ no_similar_count
;
9048 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9053 // not specific bag or have space for partly store only in specific bag
9055 // search stack for merge to
9056 if( pProto
->Stackable
!= 1 )
9058 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9059 if(res
!=EQUIP_ERR_OK
)
9062 *no_space_count
= count
+ no_similar_count
;
9068 if(no_similar_count
==0)
9069 return EQUIP_ERR_OK
;
9072 *no_space_count
= count
+ no_similar_count
;
9073 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9076 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9077 if(res
!=EQUIP_ERR_OK
)
9080 *no_space_count
= count
+ no_similar_count
;
9086 if(no_similar_count
==0)
9087 return EQUIP_ERR_OK
;
9090 *no_space_count
= count
+ no_similar_count
;
9091 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9094 if( pProto
->BagFamily
)
9096 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9098 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9099 if(res
!=EQUIP_ERR_OK
)
9104 if(no_similar_count
==0)
9105 return EQUIP_ERR_OK
;
9108 *no_space_count
= count
+ no_similar_count
;
9109 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9114 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9116 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9117 if(res
!=EQUIP_ERR_OK
)
9122 if(no_similar_count
==0)
9123 return EQUIP_ERR_OK
;
9126 *no_space_count
= count
+ no_similar_count
;
9127 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9132 // search free slot - special bag case
9133 if( pProto
->BagFamily
)
9135 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9137 uint32 keyringSize
= GetMaxKeyringSize();
9138 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9139 if(res
!=EQUIP_ERR_OK
)
9142 *no_space_count
= count
+ no_similar_count
;
9148 if(no_similar_count
==0)
9149 return EQUIP_ERR_OK
;
9152 *no_space_count
= count
+ no_similar_count
;
9153 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9156 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9158 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9159 if(res
!=EQUIP_ERR_OK
)
9162 *no_space_count
= count
+ no_similar_count
;
9168 if(no_similar_count
==0)
9169 return EQUIP_ERR_OK
;
9172 *no_space_count
= count
+ no_similar_count
;
9173 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9177 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9179 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9180 if(res
!=EQUIP_ERR_OK
)
9185 if(no_similar_count
==0)
9186 return EQUIP_ERR_OK
;
9189 *no_space_count
= count
+ no_similar_count
;
9190 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9196 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9197 if(res
!=EQUIP_ERR_OK
)
9200 *no_space_count
= count
+ no_similar_count
;
9206 if(no_similar_count
==0)
9207 return EQUIP_ERR_OK
;
9210 *no_space_count
= count
+ no_similar_count
;
9211 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9214 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9216 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9217 if(res
!=EQUIP_ERR_OK
)
9222 if(no_similar_count
==0)
9223 return EQUIP_ERR_OK
;
9226 *no_space_count
= count
+ no_similar_count
;
9227 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9232 *no_space_count
= count
+ no_similar_count
;
9234 return EQUIP_ERR_INVENTORY_FULL
;
9237 //////////////////////////////////////////////////////////////////////////
9238 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9243 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9244 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9245 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9246 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9248 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9249 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9250 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9251 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9253 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9255 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9257 if (pItem2
&& !pItem2
->IsInTrade())
9259 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9263 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9265 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9267 if (pItem2
&& !pItem2
->IsInTrade())
9269 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9273 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9275 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9277 if (pItem2
&& !pItem2
->IsInTrade())
9279 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9283 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9285 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9287 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9289 pItem2
= GetItemByPos( i
, j
);
9290 if (pItem2
&& !pItem2
->IsInTrade())
9292 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9298 // check free space for all items
9299 for (int k
=0;k
<count
;k
++)
9301 Item
*pItem
= pItems
[k
];
9304 if (!pItem
) continue;
9306 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9307 ItemPrototype
const *pProto
= pItem
->GetProto();
9311 return EQUIP_ERR_ITEM_NOT_FOUND
;
9314 if(pItem
->IsBindedNotWith(GetGUID()))
9315 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9318 ItemPrototype
const *pBagProto
;
9320 // item is 'one item only'
9321 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9322 if(res
!= EQUIP_ERR_OK
)
9325 // search stack for merge to
9326 if( pProto
->Stackable
!= 1 )
9328 bool b_found
= false;
9330 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9332 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9333 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9335 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9340 if (b_found
) continue;
9342 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9344 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9345 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9347 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9352 if (b_found
) continue;
9354 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9356 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9357 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9359 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9364 if (b_found
) continue;
9366 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9368 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9371 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9373 pItem2
= GetItemByPos( t
, j
);
9374 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9376 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9383 if (b_found
) continue;
9387 if( pProto
->BagFamily
)
9389 bool b_found
= false;
9390 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9392 uint32 keyringSize
= GetMaxKeyringSize();
9393 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9395 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9397 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9404 if (b_found
) continue;
9406 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9408 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9410 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9412 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9419 if (b_found
) continue;
9421 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9423 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9426 pBagProto
= pBag
->GetProto();
9428 // not plain container check
9429 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9430 ItemCanGoIntoBag(pProto
,pBagProto
) )
9432 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9434 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9436 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9444 if (b_found
) continue;
9448 bool b_found
= false;
9449 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9451 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9453 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9458 if (b_found
) continue;
9460 // search free slot in bags
9461 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9463 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9466 pBagProto
= pBag
->GetProto();
9468 // special bag already checked
9469 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9472 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9474 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9476 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9484 // no free slot found?
9486 return EQUIP_ERR_INVENTORY_FULL
;
9489 return EQUIP_ERR_OK
;
9492 //////////////////////////////////////////////////////////////////////////
9493 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9496 Item
*pItem
= Item::CreateItem( item
, 1, this );
9499 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9504 return EQUIP_ERR_ITEM_NOT_FOUND
;
9507 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9512 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9513 ItemPrototype
const *pProto
= pItem
->GetProto();
9516 if(pItem
->IsBindedNotWith(GetGUID()))
9517 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9519 // check count of items (skip for auto move for same player from bank)
9520 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9521 if(res
!= EQUIP_ERR_OK
)
9524 // check this only in game
9527 // May be here should be more stronger checks; STUNNED checked
9528 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9529 if (hasUnitState(UNIT_STAT_STUNNED
))
9530 return EQUIP_ERR_YOU_ARE_STUNNED
;
9532 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9534 // - in-progress arenas
9535 if( !pProto
->CanChangeEquipStateInCombat() )
9538 return EQUIP_ERR_NOT_IN_COMBAT
;
9540 if(BattleGround
* bg
= GetBattleGround())
9541 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9542 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9545 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9546 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9548 if(IsNonMeleeSpellCasted(false))
9549 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9552 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9553 if( eslot
== NULL_SLOT
)
9554 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9556 uint8 msg
= CanUseItem( pItem
, not_loading
);
9557 if( msg
!= EQUIP_ERR_OK
)
9559 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9560 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9562 // if swap ignore item (equipped also)
9563 if(uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9566 // check unique-equipped special item classes
9567 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9569 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9571 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9575 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9577 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
9579 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9580 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9582 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9590 uint32 type
= pProto
->InventoryType
;
9592 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9594 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9597 return EQUIP_ERR_CANT_DUAL_WIELD
;
9599 else if (type
== INVTYPE_2HWEAPON
)
9601 if(!CanDualWield() || !CanTitanGrip())
9602 return EQUIP_ERR_CANT_DUAL_WIELD
;
9606 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9609 // equip two-hand weapon case (with possible unequip 2 items)
9610 if( type
== INVTYPE_2HWEAPON
)
9612 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9614 if (!CanTitanGrip())
9615 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9617 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9618 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9620 if (!CanTitanGrip())
9622 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9623 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9624 ItemPosCountVec off_dest
;
9625 if( offItem
&& (!not_loading
||
9626 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9627 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9628 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9631 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9632 return EQUIP_ERR_OK
;
9636 return EQUIP_ERR_ITEM_NOT_FOUND
;
9638 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9641 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9643 // Applied only to equipped items and bank bags
9644 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9645 return EQUIP_ERR_OK
;
9647 Item
* pItem
= GetItemByPos(pos
);
9649 // Applied only to existed equipped item
9651 return EQUIP_ERR_OK
;
9653 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9655 ItemPrototype
const *pProto
= pItem
->GetProto();
9657 return EQUIP_ERR_ITEM_NOT_FOUND
;
9659 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9661 // - in-progress arenas
9662 if( !pProto
->CanChangeEquipStateInCombat() )
9665 return EQUIP_ERR_NOT_IN_COMBAT
;
9667 if(BattleGround
* bg
= GetBattleGround())
9668 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9669 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9672 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9673 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9675 return EQUIP_ERR_OK
;
9678 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9681 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9683 uint32 count
= pItem
->GetCount();
9685 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9686 ItemPrototype
const *pProto
= pItem
->GetProto();
9688 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9690 if( pItem
->IsBindedNotWith(GetGUID()) )
9691 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9693 // check count of items (skip for auto move for same player from bank)
9694 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9695 if(res
!= EQUIP_ERR_OK
)
9699 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9701 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9703 if (!pItem
->IsBag())
9704 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9706 if( !HasBankBagSlot( slot
) )
9707 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9709 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9713 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9714 if(res
!=EQUIP_ERR_OK
)
9718 return EQUIP_ERR_OK
;
9721 // not specific slot or have space for partly store only in specific slot
9724 if( bag
!= NULL_BAG
)
9726 if( pProto
->InventoryType
== INVTYPE_BAG
)
9728 Bag
*pBag
= (Bag
*)pItem
;
9729 if( pBag
&& !pBag
->IsEmpty() )
9730 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9733 // search stack in bag for merge to
9734 if( pProto
->Stackable
!= 1 )
9736 if( bag
== INVENTORY_SLOT_BAG_0
)
9738 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9739 if(res
!=EQUIP_ERR_OK
)
9743 return EQUIP_ERR_OK
;
9747 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9748 if(res
!=EQUIP_ERR_OK
)
9749 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9751 if(res
!=EQUIP_ERR_OK
)
9755 return EQUIP_ERR_OK
;
9759 // search free slot in bag
9760 if( bag
== INVENTORY_SLOT_BAG_0
)
9762 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9763 if(res
!=EQUIP_ERR_OK
)
9767 return EQUIP_ERR_OK
;
9771 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9772 if(res
!=EQUIP_ERR_OK
)
9773 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9775 if(res
!=EQUIP_ERR_OK
)
9779 return EQUIP_ERR_OK
;
9783 // not specific bag or have space for partly store only in specific bag
9785 // search stack for merge to
9786 if( pProto
->Stackable
!= 1 )
9789 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9790 if(res
!=EQUIP_ERR_OK
)
9794 return EQUIP_ERR_OK
;
9797 if( pProto
->BagFamily
)
9799 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9801 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9802 if(res
!=EQUIP_ERR_OK
)
9806 return EQUIP_ERR_OK
;
9810 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9812 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9813 if(res
!=EQUIP_ERR_OK
)
9817 return EQUIP_ERR_OK
;
9821 // search free place in special bag
9822 if( pProto
->BagFamily
)
9824 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9826 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9827 if(res
!=EQUIP_ERR_OK
)
9831 return EQUIP_ERR_OK
;
9835 // search free space
9836 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9837 if(res
!=EQUIP_ERR_OK
)
9841 return EQUIP_ERR_OK
;
9843 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9845 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9846 if(res
!=EQUIP_ERR_OK
)
9850 return EQUIP_ERR_OK
;
9852 return EQUIP_ERR_BANK_FULL
;
9855 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9859 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9860 if( !isAlive() && not_loading
)
9861 return EQUIP_ERR_YOU_ARE_DEAD
;
9863 // return EQUIP_ERR_YOU_ARE_STUNNED;
9864 ItemPrototype
const *pProto
= pItem
->GetProto();
9867 if( pItem
->IsBindedNotWith(GetGUID()) )
9868 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9869 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9870 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9871 if( pItem
->GetSkill() != 0 )
9873 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9874 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9876 if( pProto
->RequiredSkill
!= 0 )
9878 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9879 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9880 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9881 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9883 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9884 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9885 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9886 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9887 if( getLevel() < pProto
->RequiredLevel
)
9888 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9889 return EQUIP_ERR_OK
;
9892 return EQUIP_ERR_ITEM_NOT_FOUND
;
9895 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9897 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9901 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9903 if( pProto
->RequiredSkill
!= 0 )
9905 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9907 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9910 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9912 if( getLevel() < pProto
->RequiredLevel
)
9919 uint8
Player::CanUseAmmo( uint32 item
) const
9921 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9923 return EQUIP_ERR_YOU_ARE_DEAD
;
9925 // return EQUIP_ERR_YOU_ARE_STUNNED;
9926 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9929 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9930 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9931 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9932 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9933 if( pProto
->RequiredSkill
!= 0 )
9935 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9936 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9937 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9938 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9940 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9941 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9942 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9943 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9945 if( getLevel() < pProto
->RequiredLevel
)
9946 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9949 if(GetDummyAura(46699))
9950 return EQUIP_ERR_BAG_FULL6
;
9952 return EQUIP_ERR_OK
;
9954 return EQUIP_ERR_ITEM_NOT_FOUND
;
9957 void Player::SetAmmo( uint32 item
)
9963 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9969 uint8 msg
= CanUseAmmo( item
);
9970 if( msg
!= EQUIP_ERR_OK
)
9972 SendEquipError( msg
, NULL
, NULL
);
9977 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9979 _ApplyAmmoBonuses();
9982 void Player::RemoveAmmo()
9984 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9988 if(CanModifyStats())
9989 UpdateDamagePhysical(RANGED_ATTACK
);
9992 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9993 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9996 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9997 count
+= itr
->count
;
9999 Item
*pItem
= Item::CreateItem( item
, count
, this );
10002 ItemAddedQuestCheck( item
, count
);
10003 if(randomPropertyId
)
10004 pItem
->SetItemRandomProperties(randomPropertyId
);
10005 pItem
= StoreItem( dest
, pItem
, update
);
10010 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10015 Item
* lastItem
= pItem
;
10016 uint32 entry
= pItem
->GetEntry();
10017 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10019 uint16 pos
= itr
->pos
;
10020 uint32 count
= itr
->count
;
10024 if(itr
== dest
.end())
10026 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10030 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10032 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10036 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10037 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10042 uint8 bag
= pos
>> 8;
10043 uint8 slot
= pos
& 255;
10045 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10047 Item
*pItem2
= GetItemByPos( bag
, slot
);
10052 pItem
= pItem
->CloneItem(count
,this);
10054 pItem
->SetCount(count
);
10059 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10060 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10061 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10062 pItem
->SetBinding( true );
10064 if (bag
== INVENTORY_SLOT_BAG_0
)
10066 m_items
[slot
] = pItem
;
10067 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10068 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10069 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10071 pItem
->SetSlot( slot
);
10072 pItem
->SetContainer( NULL
);
10074 // need update known currency
10075 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10076 UpdateKnownCurrencies(pItem
->GetEntry(),true);
10078 if (IsInWorld() && update
)
10080 pItem
->AddToWorld();
10081 pItem
->SendUpdateToPlayer( this );
10084 pItem
->SetState(ITEM_CHANGED
, this);
10086 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10088 pBag
->StoreItem( slot
, pItem
, update
);
10089 if( IsInWorld() && update
)
10091 pItem
->AddToWorld();
10092 pItem
->SendUpdateToPlayer( this );
10094 pItem
->SetState(ITEM_CHANGED
, this);
10095 pBag
->SetState(ITEM_CHANGED
, this);
10098 AddEnchantmentDurations(pItem
);
10099 AddItemDurations(pItem
);
10105 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10106 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10107 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10108 pItem2
->SetBinding( true );
10110 pItem2
->SetCount( pItem2
->GetCount() + count
);
10111 if (IsInWorld() && update
)
10112 pItem2
->SendUpdateToPlayer( this );
10116 // delete item (it not in any slot currently)
10117 if (IsInWorld() && update
)
10119 pItem
->RemoveFromWorld();
10120 pItem
->DestroyForPlayer( this );
10123 RemoveEnchantmentDurations(pItem
);
10124 RemoveItemDurations(pItem
);
10126 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10127 pItem
->SetState(ITEM_REMOVED
, this);
10130 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10131 AddEnchantmentDurations(pItem2
);
10133 pItem2
->SetState(ITEM_CHANGED
, this);
10139 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10141 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10143 ItemAddedQuestCheck( item
, 1 );
10144 return EquipItem( pos
, pItem
, update
);
10150 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10153 AddEnchantmentDurations(pItem
);
10154 AddItemDurations(pItem
);
10156 uint8 bag
= pos
>> 8;
10157 uint8 slot
= pos
& 255;
10159 Item
*pItem2
= GetItemByPos( bag
, slot
);
10163 VisualizeItem( slot
, pItem
);
10167 ItemPrototype
const *pProto
= pItem
->GetProto();
10169 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10170 if(pProto
&& pProto
->ItemSet
)
10171 AddItemsSetItem(this,pItem
);
10173 _ApplyItemMods(pItem
, slot
, true);
10175 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10177 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10179 if (getClass() == CLASS_ROGUE
)
10180 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10182 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10185 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10188 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10190 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10191 data
<< uint64(GetGUID());
10193 data
<< uint32(cooldownSpell
);
10195 GetSession()->SendPacket(&data
);
10200 if( IsInWorld() && update
)
10202 pItem
->AddToWorld();
10203 pItem
->SendUpdateToPlayer( this );
10206 ApplyEquipCooldown(pItem
);
10208 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10209 UpdateExpertise(BASE_ATTACK
);
10210 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10211 UpdateExpertise(OFF_ATTACK
);
10215 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10216 if( IsInWorld() && update
)
10217 pItem2
->SendUpdateToPlayer( this );
10219 // delete item (it not in any slot currently)
10220 //pItem->DeleteFromDB();
10221 if( IsInWorld() && update
)
10223 pItem
->RemoveFromWorld();
10224 pItem
->DestroyForPlayer( this );
10227 RemoveEnchantmentDurations(pItem
);
10228 RemoveItemDurations(pItem
);
10230 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10231 pItem
->SetState(ITEM_REMOVED
, this);
10232 pItem2
->SetState(ITEM_CHANGED
, this);
10234 ApplyEquipCooldown(pItem2
);
10239 // only for full equip instead adding to stack
10240 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10245 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10249 AddEnchantmentDurations(pItem
);
10250 AddItemDurations(pItem
);
10252 uint8 slot
= pos
& 255;
10253 VisualizeItem( slot
, pItem
);
10257 pItem
->AddToWorld();
10258 pItem
->SendUpdateToPlayer( this );
10263 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10265 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10266 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10267 // entry // Size: 1
10268 // inspected enchantments // Size: 6
10270 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10271 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10276 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10278 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10279 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10281 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10282 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10284 // Use SetInt16Value to prevent set high part to FFFF for negative value
10285 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10286 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10290 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10292 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10293 SetUInt32Value(VisibleBase
+ 0, 0);
10295 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10296 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10298 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10299 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10303 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10308 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10309 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10310 pItem
->SetBinding( true );
10312 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10314 m_items
[slot
] = pItem
;
10315 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10316 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10317 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10318 pItem
->SetSlot( slot
);
10319 pItem
->SetContainer( NULL
);
10321 if( slot
< EQUIPMENT_SLOT_END
)
10322 SetVisibleItemSlot(slot
,pItem
);
10324 pItem
->SetState(ITEM_CHANGED
, this);
10327 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10329 // note: removeitem does not actually change the item
10330 // it only takes the item out of storage temporarily
10331 // note2: if removeitem is to be used for delinking
10332 // the item must be removed from the player's updatequeue
10334 Item
*pItem
= GetItemByPos( bag
, slot
);
10337 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10339 RemoveEnchantmentDurations(pItem
);
10340 RemoveItemDurations(pItem
);
10342 if( bag
== INVENTORY_SLOT_BAG_0
)
10344 if ( slot
< INVENTORY_SLOT_BAG_END
)
10346 ItemPrototype
const *pProto
= pItem
->GetProto();
10347 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10349 if(pProto
&& pProto
->ItemSet
)
10350 RemoveItemsSetItem(this,pProto
);
10352 _ApplyItemMods(pItem
, slot
, false);
10354 // remove item dependent auras and casts (only weapon and armor slots)
10355 if(slot
< EQUIPMENT_SLOT_END
)
10357 RemoveItemDependentAurasAndCasts(pItem
);
10359 // remove held enchantments, update expertise
10360 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10362 if (pItem
->GetItemSuffixFactor())
10364 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10365 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10369 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10370 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10373 UpdateExpertise(BASE_ATTACK
);
10375 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10376 UpdateExpertise(OFF_ATTACK
);
10379 // need update known currency
10380 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10381 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10383 m_items
[slot
] = NULL
;
10384 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10386 if ( slot
< EQUIPMENT_SLOT_END
)
10387 SetVisibleItemSlot(slot
,NULL
);
10391 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10393 pBag
->RemoveItem(slot
, update
);
10395 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10396 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10397 pItem
->SetSlot( NULL_SLOT
);
10398 if( IsInWorld() && update
)
10399 pItem
->SendUpdateToPlayer( this );
10403 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10404 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10406 if(Item
* it
= GetItemByPos(bag
,slot
))
10408 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10409 RemoveItem( bag
,slot
,update
);
10410 it
->RemoveFromUpdateQueueOf(this);
10411 if(it
->IsInWorld())
10413 it
->RemoveFromWorld();
10414 it
->DestroyForPlayer( this );
10419 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10420 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10422 // update quest counters
10423 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10426 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10428 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10429 if(pLastItem
==pItem
)
10431 // update owner for last item (this can be original item with wrong owner
10432 if(pLastItem
->GetOwnerGUID() != GetGUID())
10433 pLastItem
->SetOwnerGUID(GetGUID());
10435 // if this original item then it need create record in inventory
10436 // in case trade we already have item in other player inventory
10437 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10441 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10443 Item
*pItem
= GetItemByPos( bag
, slot
);
10446 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10448 // start from destroy contained items (only equipped bag can have its)
10449 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10451 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
10452 DestroyItem(slot
,i
,update
);
10455 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10456 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10458 RemoveEnchantmentDurations(pItem
);
10459 RemoveItemDurations(pItem
);
10461 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10463 if( bag
== INVENTORY_SLOT_BAG_0
)
10465 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10467 // equipment and equipped bags can have applied bonuses
10468 if ( slot
< INVENTORY_SLOT_BAG_END
)
10470 ItemPrototype
const *pProto
= pItem
->GetProto();
10472 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10473 if(pProto
&& pProto
->ItemSet
)
10474 RemoveItemsSetItem(this,pProto
);
10476 _ApplyItemMods(pItem
, slot
, false);
10479 if ( slot
< EQUIPMENT_SLOT_END
)
10481 // remove item dependent auras and casts (only weapon and armor slots)
10482 RemoveItemDependentAurasAndCasts(pItem
);
10484 // update expertise
10485 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10486 UpdateExpertise(BASE_ATTACK
);
10487 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10488 UpdateExpertise(OFF_ATTACK
);
10490 // equipment visual show
10491 SetVisibleItemSlot(slot
,NULL
);
10493 // need update known currency
10494 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10495 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10497 m_items
[slot
] = NULL
;
10499 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10500 pBag
->RemoveItem(slot
, update
);
10502 if( IsInWorld() && update
)
10504 pItem
->RemoveFromWorld();
10505 pItem
->DestroyForPlayer(this);
10508 //pItem->SetOwnerGUID(0);
10509 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10510 pItem
->SetSlot( NULL_SLOT
);
10511 pItem
->SetState(ITEM_REMOVED
, this);
10515 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10517 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10518 uint32 remcount
= 0;
10521 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10523 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10525 if (pItem
->GetEntry() == item
)
10527 if (pItem
->GetCount() + remcount
<= count
)
10529 // all items in inventory can unequipped
10530 remcount
+= pItem
->GetCount();
10531 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10533 if (remcount
>=count
)
10538 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10539 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10540 if (IsInWorld() & update
)
10541 pItem
->SendUpdateToPlayer( this );
10542 pItem
->SetState(ITEM_CHANGED
, this);
10549 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
10551 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10553 if (pItem
->GetEntry() == item
)
10555 if (pItem
->GetCount() + remcount
<= count
)
10557 // all keys can be unequipped
10558 remcount
+= pItem
->GetCount();
10559 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10561 if (remcount
>=count
)
10566 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10567 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10568 if (IsInWorld() & update
)
10569 pItem
->SendUpdateToPlayer( this );
10570 pItem
->SetState(ITEM_CHANGED
, this);
10577 // in inventory bags
10578 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10580 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10582 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10584 if(Item
* pItem
= pBag
->GetItemByPos(j
))
10586 if (pItem
->GetEntry() == item
)
10588 // all items in bags can be unequipped
10589 if (pItem
->GetCount() + remcount
<= count
)
10591 remcount
+= pItem
->GetCount();
10592 DestroyItem( i
, j
, update
);
10594 if (remcount
>=count
)
10599 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10600 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10601 if (IsInWorld() && update
)
10602 pItem
->SendUpdateToPlayer( this );
10603 pItem
->SetState(ITEM_CHANGED
, this);
10612 // in equipment and bag list
10613 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10615 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10617 if (pItem
&& pItem
->GetEntry() == item
)
10619 if (pItem
->GetCount() + remcount
<= count
)
10621 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10623 remcount
+= pItem
->GetCount();
10624 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10626 if (remcount
>=count
)
10632 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10633 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10634 if (IsInWorld() & update
)
10635 pItem
->SendUpdateToPlayer( this );
10636 pItem
->SetState(ITEM_CHANGED
, this);
10644 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10646 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10649 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10650 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10651 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10652 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10654 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
10655 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10656 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10657 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10659 // in inventory bags
10660 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10661 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10662 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10663 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10664 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10665 DestroyItem( i
, j
, update
);
10667 // in equipment and bag list
10668 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10669 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10670 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10671 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10674 void Player::DestroyConjuredItems( bool update
)
10676 // used when entering arena
10677 // destroys all conjured items
10678 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10681 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10682 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10683 if (pItem
->IsConjuredConsumable())
10684 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10686 // in inventory bags
10687 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10688 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10689 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10690 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10691 if (pItem
->IsConjuredConsumable())
10692 DestroyItem( i
, j
, update
);
10694 // in equipment and bag list
10695 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10696 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10697 if (pItem
->IsConjuredConsumable())
10698 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10701 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10706 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10708 if( pItem
->GetCount() <= count
)
10710 count
-= pItem
->GetCount();
10712 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10716 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10717 pItem
->SetCount( pItem
->GetCount() - count
);
10719 if( IsInWorld() & update
)
10720 pItem
->SendUpdateToPlayer( this );
10721 pItem
->SetState(ITEM_CHANGED
, this);
10725 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10727 uint8 srcbag
= src
>> 8;
10728 uint8 srcslot
= src
& 255;
10730 uint8 dstbag
= dst
>> 8;
10731 uint8 dstslot
= dst
& 255;
10733 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10736 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10740 // not let split all items (can be only at cheating)
10741 if(pSrcItem
->GetCount() == count
)
10743 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10747 // not let split more existed items (can be only at cheating)
10748 if(pSrcItem
->GetCount() < count
)
10750 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10754 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10756 //best error message found for attempting to split while looting
10757 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10761 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10762 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10765 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10769 if( IsInventoryPos( dst
) )
10771 // change item amount before check (for unique max count check)
10772 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10774 ItemPosCountVec dest
;
10775 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10776 if( msg
!= EQUIP_ERR_OK
)
10779 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10780 SendEquipError( msg
, pSrcItem
, NULL
);
10785 pSrcItem
->SendUpdateToPlayer( this );
10786 pSrcItem
->SetState(ITEM_CHANGED
, this);
10787 StoreItem( dest
, pNewItem
, true);
10789 else if( IsBankPos ( dst
) )
10791 // change item amount before check (for unique max count check)
10792 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10794 ItemPosCountVec dest
;
10795 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10796 if( msg
!= EQUIP_ERR_OK
)
10799 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10800 SendEquipError( msg
, pSrcItem
, NULL
);
10805 pSrcItem
->SendUpdateToPlayer( this );
10806 pSrcItem
->SetState(ITEM_CHANGED
, this);
10807 BankItem( dest
, pNewItem
, true);
10809 else if( IsEquipmentPos ( dst
) )
10811 // change item amount before check (for unique max count check), provide space for splitted items
10812 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10815 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10816 if( msg
!= EQUIP_ERR_OK
)
10819 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10820 SendEquipError( msg
, pSrcItem
, NULL
);
10825 pSrcItem
->SendUpdateToPlayer( this );
10826 pSrcItem
->SetState(ITEM_CHANGED
, this);
10827 EquipItem( dest
, pNewItem
, true);
10828 AutoUnequipOffhandIfNeed();
10832 void Player::SwapItem( uint16 src
, uint16 dst
)
10834 uint8 srcbag
= src
>> 8;
10835 uint8 srcslot
= src
& 255;
10837 uint8 dstbag
= dst
>> 8;
10838 uint8 dstslot
= dst
& 255;
10840 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10841 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10846 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10850 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10856 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10858 //best error message found for attempting to swap while looting
10859 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10863 // check unequip potability for equipped items and bank bags
10864 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10866 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10867 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
10868 if(msg
!= EQUIP_ERR_OK
)
10870 SendEquipError( msg
, pSrcItem
, pDstItem
);
10875 // prevent put equipped/bank bag in self
10876 if( IsBagPos ( src
) && srcslot
== dstbag
)
10878 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10886 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10888 //best error message found for attempting to swap while looting
10889 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10893 // check unequip potability for equipped items and bank bags
10894 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10896 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10897 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
10898 if(msg
!= EQUIP_ERR_OK
)
10900 SendEquipError( msg
, pSrcItem
, pDstItem
);
10906 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10907 // or swap empty bag with another empty or not empty bag (with items exchange)
10912 if( IsInventoryPos( dst
) )
10914 ItemPosCountVec dest
;
10915 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10916 if( msg
!= EQUIP_ERR_OK
)
10918 SendEquipError( msg
, pSrcItem
, NULL
);
10922 RemoveItem(srcbag
, srcslot
, true);
10923 StoreItem( dest
, pSrcItem
, true);
10925 else if( IsBankPos ( dst
) )
10927 ItemPosCountVec dest
;
10928 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10929 if( msg
!= EQUIP_ERR_OK
)
10931 SendEquipError( msg
, pSrcItem
, NULL
);
10935 RemoveItem(srcbag
, srcslot
, true);
10936 BankItem( dest
, pSrcItem
, true);
10938 else if( IsEquipmentPos ( dst
) )
10941 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10942 if( msg
!= EQUIP_ERR_OK
)
10944 SendEquipError( msg
, pSrcItem
, NULL
);
10948 RemoveItem(srcbag
, srcslot
, true);
10949 EquipItem( dest
, pSrcItem
, true);
10950 AutoUnequipOffhandIfNeed();
10956 // attempt merge to / fill target item
10957 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
10960 ItemPosCountVec sDest
;
10962 if( IsInventoryPos( dst
) )
10963 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10964 else if( IsBankPos ( dst
) )
10965 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10966 else if( IsEquipmentPos ( dst
) )
10967 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10971 // can be merge/fill
10972 if(msg
== EQUIP_ERR_OK
)
10974 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
10976 RemoveItem(srcbag
, srcslot
, true);
10978 if( IsInventoryPos( dst
) )
10979 StoreItem( sDest
, pSrcItem
, true);
10980 else if( IsBankPos ( dst
) )
10981 BankItem( sDest
, pSrcItem
, true);
10982 else if( IsEquipmentPos ( dst
) )
10984 EquipItem( eDest
, pSrcItem
, true);
10985 AutoUnequipOffhandIfNeed();
10990 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
10991 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
10992 pSrcItem
->SetState(ITEM_CHANGED
, this);
10993 pDstItem
->SetState(ITEM_CHANGED
, this);
10996 pSrcItem
->SendUpdateToPlayer( this );
10997 pDstItem
->SendUpdateToPlayer( this );
11004 // impossible merge/fill, do real swap
11007 // check src->dest move possibility
11008 ItemPosCountVec sDest
;
11010 if( IsInventoryPos( dst
) )
11011 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11012 else if( IsBankPos( dst
) )
11013 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11014 else if( IsEquipmentPos( dst
) )
11016 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11017 if( msg
== EQUIP_ERR_OK
)
11018 msg
= CanUnequipItem( eDest
, true );
11021 if( msg
!= EQUIP_ERR_OK
)
11023 SendEquipError( msg
, pSrcItem
, pDstItem
);
11027 // check dest->src move possibility
11028 ItemPosCountVec sDest2
;
11030 if( IsInventoryPos( src
) )
11031 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11032 else if( IsBankPos( src
) )
11033 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11034 else if( IsEquipmentPos( src
) )
11036 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11037 if( msg
== EQUIP_ERR_OK
)
11038 msg
= CanUnequipItem( eDest2
, true);
11041 if( msg
!= EQUIP_ERR_OK
)
11043 SendEquipError( msg
, pDstItem
, pSrcItem
);
11047 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11048 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11050 Bag
* emptyBag
= NULL
;
11051 Bag
* fullBag
= NULL
;
11052 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11054 emptyBag
= (Bag
*)pSrcItem
;
11055 fullBag
= (Bag
*)pDstItem
;
11057 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11059 emptyBag
= (Bag
*)pDstItem
;
11060 fullBag
= (Bag
*)pSrcItem
;
11063 // bag swap (with items exchange) case
11064 if(emptyBag
&& fullBag
)
11066 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11070 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11072 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11076 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11077 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11079 // one from items not go to empry target bag
11080 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11088 if (count
> emptyBag
->GetBagSize())
11090 // too small targeted bag
11091 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11096 count
= 0; // will pos in new bag
11097 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11099 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11103 fullBag
->RemoveItem(i
, true);
11104 emptyBag
->StoreItem(count
, bagItem
, true);
11105 bagItem
->SetState(ITEM_CHANGED
, this);
11112 // now do moves, remove...
11113 RemoveItem(dstbag
, dstslot
, false);
11114 RemoveItem(srcbag
, srcslot
, false);
11117 if( IsInventoryPos( dst
) )
11118 StoreItem(sDest
, pSrcItem
, true);
11119 else if( IsBankPos( dst
) )
11120 BankItem(sDest
, pSrcItem
, true);
11121 else if( IsEquipmentPos( dst
) )
11122 EquipItem(eDest
, pSrcItem
, true);
11125 if( IsInventoryPos( src
) )
11126 StoreItem(sDest2
, pDstItem
, true);
11127 else if( IsBankPos( src
) )
11128 BankItem(sDest2
, pDstItem
, true);
11129 else if( IsEquipmentPos( src
) )
11130 EquipItem(eDest2
, pDstItem
, true);
11132 AutoUnequipOffhandIfNeed();
11135 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11139 uint32 slot
= m_currentBuybackSlot
;
11140 // if current back slot non-empty search oldest or free
11143 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11144 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11146 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11155 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11157 if(oldest_time
> i_time
)
11159 oldest_time
= i_time
;
11165 slot
= oldest_slot
;
11168 RemoveItemFromBuyBackSlot( slot
, true );
11169 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11171 m_items
[slot
] = pItem
;
11172 time_t base
= time(NULL
);
11173 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11174 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11176 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11177 ItemPrototype
const *pProto
= pItem
->GetProto();
11179 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11181 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11182 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11184 // move to next (for non filled list is move most optimized choice)
11185 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11186 ++m_currentBuybackSlot
;
11190 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11192 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11193 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11194 return m_items
[slot
];
11198 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11200 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11201 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11203 Item
*pItem
= m_items
[slot
];
11206 pItem
->RemoveFromWorld();
11207 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11210 m_items
[slot
] = NULL
;
11212 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11213 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11214 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11215 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11217 // if current backslot is filled set to now free slot
11218 if(m_items
[m_currentBuybackSlot
])
11219 m_currentBuybackSlot
= slot
;
11223 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11225 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11226 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11227 data
<< uint8(msg
);
11231 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11232 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11233 data
<< uint8(0); // not 0 there...
11235 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11240 if(ItemPrototype
const* proto
= pItem
->GetProto())
11241 level
= proto
->RequiredLevel
;
11243 data
<< uint32(level
); // new 2.4.0
11246 GetSession()->SendPacket(&data
);
11249 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11251 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11252 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11253 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11254 data
<< uint32(item
);
11256 data
<< uint32(param
);
11257 data
<< uint8(msg
);
11258 GetSession()->SendPacket(&data
);
11261 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11263 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11264 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11265 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11266 data
<< uint64(guid
);
11268 data
<< uint32(param
);
11269 data
<< uint8(msg
);
11270 GetSession()->SendPacket(&data
);
11273 void Player::ClearTrade()
11276 acceptTrade
= false;
11277 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11278 tradeItems
[i
] = NULL_SLOT
;
11281 void Player::TradeCancel(bool sendback
)
11285 // send yellow "Trade canceled" message to both traders
11289 ws
->SendCancelTrade();
11290 ws
= pTrader
->GetSession();
11291 if(!ws
->PlayerLogout())
11292 ws
->SendCancelTrade();
11296 pTrader
->ClearTrade();
11297 // prevent loss of reference
11298 pTrader
->pTrader
= NULL
;
11303 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11305 if(m_itemDuration
.empty())
11308 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11310 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11313 ++itr
; // current element can be erased in UpdateDuration
11315 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11316 item
->UpdateDuration(this,time
);
11320 void Player::UpdateEnchantTime(uint32 time
)
11322 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11326 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11328 next
= m_enchantDuration
.erase(itr
);
11330 else if(itr
->leftduration
<= time
)
11332 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11333 itr
->item
->ClearEnchantment(itr
->slot
);
11334 next
= m_enchantDuration
.erase(itr
);
11336 else if(itr
->leftduration
> time
)
11338 itr
->leftduration
-= time
;
11344 void Player::AddEnchantmentDurations(Item
*item
)
11346 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11348 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11351 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11353 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11357 void Player::RemoveEnchantmentDurations(Item
*item
)
11359 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11361 if(itr
->item
== item
)
11363 // save duration in item
11364 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11365 itr
= m_enchantDuration
.erase(itr
);
11372 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11374 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11375 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11378 if(itr
->slot
==slot
)
11380 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11382 // remove from stats
11383 ApplyEnchantment(itr
->item
,slot
,false,false);
11385 itr
->item
->ClearEnchantment(slot
);
11387 // remove from update list
11388 next
= m_enchantDuration
.erase(itr
);
11394 // remove enchants from inventory items
11395 // NOTE: no need to remove these from stats, since these aren't equipped
11397 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11399 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11400 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11401 pItem
->ClearEnchantment(slot
);
11404 // in inventory bags
11405 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11407 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11410 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11412 Item
* pItem
= pBag
->GetItemByPos(j
);
11413 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11414 pItem
->ClearEnchantment(slot
);
11420 // duration == 0 will remove item enchant
11421 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11426 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11429 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11431 if(itr
->item
== item
&& itr
->slot
== slot
)
11433 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11434 m_enchantDuration
.erase(itr
);
11438 if(item
&& duration
> 0 )
11440 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11441 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11445 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11447 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11448 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11451 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11456 if(!item
->IsEquipped())
11459 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11462 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11466 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11470 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11473 if (!item
->IsBroken())
11475 for (int s
=0; s
<3; s
++)
11477 uint32 enchant_display_type
= pEnchant
->type
[s
];
11478 uint32 enchant_amount
= pEnchant
->amount
[s
];
11479 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11481 switch(enchant_display_type
)
11483 case ITEM_ENCHANTMENT_TYPE_NONE
:
11485 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11486 // processed in Player::CastItemCombatSpell
11488 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11489 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11490 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11491 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11492 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11493 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11494 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11496 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11497 if(enchant_spell_id
)
11501 int32 basepoints
= 0;
11502 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11503 if (item
->GetItemRandomPropertyId())
11505 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11508 // Search enchant_amount
11509 for (int k
=0; k
<3; k
++)
11511 if(item_rand
->enchant_id
[k
] == enchant_id
)
11513 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11519 // Cast custom spell vs all equal basepoints getted from enchant_amount
11521 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11523 CastSpell(this,enchant_spell_id
,true,item
);
11526 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11529 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11530 if (!enchant_amount
)
11532 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11535 for (int k
=0; k
<3; k
++)
11537 if(item_rand
->enchant_id
[k
] == enchant_id
)
11539 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11546 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11548 case ITEM_ENCHANTMENT_TYPE_STAT
:
11550 if (!enchant_amount
)
11552 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11553 if(item_rand_suffix
)
11555 for (int k
=0; k
<3; k
++)
11557 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11559 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11566 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11567 switch (enchant_spell_id
)
11569 case ITEM_MOD_AGILITY
:
11570 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11571 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11572 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11574 case ITEM_MOD_STRENGTH
:
11575 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11576 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11577 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11579 case ITEM_MOD_INTELLECT
:
11580 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11581 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11582 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11584 case ITEM_MOD_SPIRIT
:
11585 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11586 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11587 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11589 case ITEM_MOD_STAMINA
:
11590 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11591 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11592 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11594 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11595 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11596 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11598 case ITEM_MOD_DODGE_RATING
:
11599 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11600 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11602 case ITEM_MOD_PARRY_RATING
:
11603 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11604 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11606 case ITEM_MOD_BLOCK_RATING
:
11607 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11608 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11610 case ITEM_MOD_HIT_MELEE_RATING
:
11611 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11612 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11614 case ITEM_MOD_HIT_RANGED_RATING
:
11615 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11616 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11618 case ITEM_MOD_HIT_SPELL_RATING
:
11619 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11620 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11622 case ITEM_MOD_CRIT_MELEE_RATING
:
11623 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11624 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11626 case ITEM_MOD_CRIT_RANGED_RATING
:
11627 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11628 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11630 case ITEM_MOD_CRIT_SPELL_RATING
:
11631 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11632 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11634 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11636 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11637 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11639 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11640 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11642 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11643 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11645 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11646 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11648 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11649 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11651 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11652 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11654 // case ITEM_MOD_HASTE_MELEE_RATING:
11655 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11657 // case ITEM_MOD_HASTE_RANGED_RATING:
11658 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11660 case ITEM_MOD_HASTE_SPELL_RATING
:
11661 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11663 case ITEM_MOD_HIT_RATING
:
11664 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11665 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11666 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11667 sLog
.outDebug("+ %u HIT", enchant_amount
);
11669 case ITEM_MOD_CRIT_RATING
:
11670 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11671 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11672 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11673 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11675 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11676 // case ITEM_MOD_HIT_TAKEN_RATING:
11677 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11678 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11679 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11681 // case ITEM_MOD_CRIT_TAKEN_RATING:
11682 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11683 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11684 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11686 case ITEM_MOD_RESILIENCE_RATING
:
11687 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11688 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11689 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11690 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11692 case ITEM_MOD_HASTE_RATING
:
11693 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11694 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11695 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11696 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11698 case ITEM_MOD_EXPERTISE_RATING
:
11699 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11700 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11702 case ITEM_MOD_ATTACK_POWER
:
11703 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11704 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11705 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11707 case ITEM_MOD_RANGED_ATTACK_POWER
:
11708 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11709 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11711 case ITEM_MOD_FERAL_ATTACK_POWER
:
11712 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11713 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
11715 case ITEM_MOD_SPELL_HEALING_DONE
:
11716 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11717 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
11719 case ITEM_MOD_SPELL_DAMAGE_DONE
:
11720 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11721 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
11723 case ITEM_MOD_MANA_REGENERATION
:
11724 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
11725 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
11727 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11728 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11729 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11731 case ITEM_MOD_SPELL_POWER
:
11732 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11733 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11734 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
11741 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11743 if(getClass() == CLASS_SHAMAN
)
11745 float addValue
= 0.0f
;
11746 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11748 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11749 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11751 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11753 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11754 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11759 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
11760 // processed in Player::CastItemUseSpell
11762 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
11766 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
11768 } /*switch(enchant_display_type)*/
11772 // visualize enchantment at player and equipped items
11773 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11775 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11776 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11784 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11786 AddEnchantmentDuration(item
,slot
,duration
);
11790 // duration == 0 will remove EnchantDuration
11791 AddEnchantmentDuration(item
,slot
,0);
11796 void Player::SendEnchantmentDurations()
11798 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11800 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11804 void Player::SendItemDurations()
11806 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11808 (*itr
)->SendTimeUpdate(this);
11812 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11814 if(!item
) // prevent crash
11817 // last check 2.0.10
11818 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11819 data
<< GetGUID(); // player GUID
11820 data
<< uint32(received
); // 0=looted, 1=from npc
11821 data
<< uint32(created
); // 0=received, 1=created
11822 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11823 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11824 // item slot, but when added to stack: 0xFFFFFFFF
11825 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11826 data
<< uint32(item
->GetEntry()); // item id
11827 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11828 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11829 data
<< uint32(count
); // count of items
11830 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11832 if (broadcast
&& GetGroup())
11833 GetGroup()->BroadcastPacket(&data
, true);
11835 GetSession()->SendPacket(&data
);
11838 /*********************************************************/
11839 /*** QUEST SYSTEM ***/
11840 /*********************************************************/
11842 void Player::PrepareQuestMenu( uint64 guid
)
11845 QuestRelations
* pObjectQR
;
11846 QuestRelations
* pObjectQIR
;
11848 // pets also can have quests
11849 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
11852 pObject
= (Object
*)pCreature
;
11853 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11854 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11858 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
11861 pObject
= (Object
*)pGameObject
;
11862 pObjectQR
= &objmgr
.mGOQuestRelations
;
11863 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11869 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11872 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11874 uint32 quest_id
= i
->second
;
11875 QuestStatus status
= GetQuestStatus( quest_id
);
11876 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11877 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11878 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11879 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11880 else if (status
== QUEST_STATUS_AVAILABLE
)
11881 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11884 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11886 uint32 quest_id
= i
->second
;
11887 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11888 if(!pQuest
) continue;
11890 QuestStatus status
= GetQuestStatus( quest_id
);
11892 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11893 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11894 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11895 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11899 void Player::SendPreparedQuest( uint64 guid
)
11901 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11902 if( questMenu
.Empty() )
11905 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11907 uint32 status
= qmi0
.m_qIcon
;
11909 // single element case
11910 if ( questMenu
.MenuItemCount() == 1 )
11912 // Auto open -- maybe also should verify there is no greeting
11913 uint32 quest_id
= qmi0
.m_qId
;
11914 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11917 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11918 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11919 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11920 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11921 // Send completable on repeatable quest if player don't have quest
11922 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
11923 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11925 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11928 // multiply entries
11934 std::string title
= "";
11936 // need pet case for some quests
11937 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
11940 uint32 textid
= pCreature
->GetNpcTextId();
11941 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
11944 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11945 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11950 qe
= gossiptext
->Options
[0].Emotes
[0];
11952 if(!gossiptext
->Options
[0].Text_0
.empty())
11954 title
= gossiptext
->Options
[0].Text_0
;
11956 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11959 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11962 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11963 title
= nl
->Text_0
[0][loc_idx
];
11969 title
= gossiptext
->Options
[0].Text_1
;
11971 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11974 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11977 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11978 title
= nl
->Text_1
[0][loc_idx
];
11984 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11988 bool Player::IsActiveQuest( uint32 quest_id
) const
11990 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11992 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11995 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11998 QuestRelations
* pObjectQR
;
11999 QuestRelations
* pObjectQIR
;
12001 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
12004 pObject
= (Object
*)pCreature
;
12005 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12006 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12010 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
12013 pObject
= (Object
*)pGameObject
;
12014 pObjectQR
= &objmgr
.mGOQuestRelations
;
12015 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12021 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12022 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12024 if (itr
->second
== nextQuestID
)
12025 return objmgr
.GetQuestTemplate(nextQuestID
);
12031 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12033 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12034 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12035 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12036 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12038 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12044 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12046 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12047 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12048 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12049 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12050 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12051 && SatisfyQuestDay( pQuest
, msg
);
12054 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12056 if( !SatisfyQuestLog( msg
) )
12059 uint32 srcitem
= pQuest
->GetSrcItemId();
12062 uint32 count
= pQuest
->GetSrcItemCount();
12063 ItemPosCountVec dest
;
12064 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12066 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12067 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12069 else if( msg2
!= EQUIP_ERR_OK
)
12071 SendEquipError( msg2
, NULL
, NULL
);
12078 bool Player::CanCompleteQuest( uint32 quest_id
)
12082 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12083 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12084 return false; // not allow re-complete quest
12086 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12091 // auto complete quest
12092 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12095 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12098 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12100 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12102 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12107 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12109 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12111 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12114 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12119 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12122 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12125 if ( qInfo
->GetRewOrReqMoney() < 0 )
12127 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12131 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12132 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12141 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12143 // Solve problem that player don't have the quest and try complete it.
12144 // if repeatable she must be able to complete event if player don't have it.
12145 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12146 if( !CanTakeQuest(pQuest
, false) )
12149 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12150 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12151 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12154 if( !CanRewardQuest(pQuest
, false) )
12160 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12162 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12163 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12166 // daily quest can't be rewarded (25 daily quest already completed)
12167 if(!SatisfyQuestDay(pQuest
,true))
12170 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12171 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12174 // prevent receive reward with quest items in bank
12175 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12177 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12179 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12180 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12183 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12189 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12190 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12196 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12198 // prevent receive reward with quest items in bank or for not completed quest
12199 if(!CanRewardQuest(pQuest
,msg
))
12202 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12204 if( pQuest
->RewChoiceItemId
[reward
] )
12206 ItemPosCountVec dest
;
12207 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12208 if( res
!= EQUIP_ERR_OK
)
12210 SendEquipError( res
, NULL
, NULL
);
12216 if ( pQuest
->GetRewItemsCount() > 0 )
12218 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12220 if( pQuest
->RewItemId
[i
] )
12222 ItemPosCountVec dest
;
12223 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12224 if( res
!= EQUIP_ERR_OK
)
12226 SendEquipError( res
, NULL
, NULL
);
12236 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12238 uint16 log_slot
= FindQuestSlot( 0 );
12239 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12241 uint32 quest_id
= pQuest
->GetQuestId();
12243 // if not exist then created with set uState==NEW and rewarded=false
12244 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12246 // check for repeatable quests status reset
12247 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12248 questStatusData
.m_explored
= false;
12250 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12252 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12253 questStatusData
.m_itemcount
[i
] = 0;
12256 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12258 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12259 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12262 GiveQuestSourceItem( pQuest
);
12263 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12265 if( pQuest
->GetRepObjectiveFaction() )
12266 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
12267 GetReputationMgr().SetVisible(factionEntry
);
12270 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12272 uint32 limittime
= pQuest
->GetLimitTime();
12274 // shared timed quest
12275 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12276 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12278 AddTimedQuest( quest_id
);
12279 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12280 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12283 questStatusData
.m_timer
= 0;
12285 SetQuestSlot(log_slot
, quest_id
, qtime
);
12287 if (questStatusData
.uState
!= QUEST_NEW
)
12288 questStatusData
.uState
= QUEST_CHANGED
;
12290 //starting initial quest script
12291 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12292 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12294 // Some spells applied at quest activation
12295 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12296 if(saBounds
.first
!= saBounds
.second
)
12299 GetZoneAndAreaId(zone
,area
);
12301 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12302 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12303 if( !HasAura(itr
->second
->spellId
,0) )
12304 CastSpell(this,itr
->second
->spellId
,true);
12307 UpdateForQuestWorldObjects();
12310 void Player::CompleteQuest( uint32 quest_id
)
12314 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12316 uint16 log_slot
= FindQuestSlot( quest_id
);
12317 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12318 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12320 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12322 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12323 RewardQuest(qInfo
,0,this,false);
12325 SendQuestComplete( quest_id
);
12330 void Player::IncompleteQuest( uint32 quest_id
)
12334 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12336 uint16 log_slot
= FindQuestSlot( quest_id
);
12337 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12338 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12342 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12344 uint32 quest_id
= pQuest
->GetQuestId();
12346 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12348 if ( pQuest
->ReqItemId
[i
] )
12349 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12352 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12353 // SetTimedQuest( 0 );
12354 m_timedquests
.erase(pQuest
->GetQuestId());
12356 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12358 if( pQuest
->RewChoiceItemId
[reward
] )
12360 ItemPosCountVec dest
;
12361 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12363 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12364 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12369 if ( pQuest
->GetRewItemsCount() > 0 )
12371 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12373 if( pQuest
->RewItemId
[i
] )
12375 ItemPosCountVec dest
;
12376 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12378 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12379 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12385 RewardReputation( pQuest
);
12387 if( pQuest
->GetRewSpellCast() > 0 )
12388 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12389 else if( pQuest
->GetRewSpell() > 0)
12390 CastSpell( this, pQuest
->GetRewSpell(), true);
12392 uint16 log_slot
= FindQuestSlot( quest_id
);
12393 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12394 SetQuestSlot(log_slot
,0);
12396 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12398 // Not give XP in case already completed once repeatable quest
12399 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12401 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12402 GiveXP( XP
, NULL
);
12405 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12406 ModifyMoney( money
);
12407 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12410 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12411 if(pQuest
->GetRewOrReqMoney())
12413 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12415 if(pQuest
->GetRewOrReqMoney() > 0)
12416 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12420 if(pQuest
->GetRewHonorableKills())
12421 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12424 if(pQuest
->GetCharTitleId())
12426 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12427 SetTitle(titleEntry
);
12430 if(pQuest
->GetBonusTalents())
12432 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12433 InitTalentForLevel();
12436 // Send reward mail
12437 if(pQuest
->GetRewMailTemplateId())
12439 MailMessageType mailType
;
12440 uint32 senderGuidOrEntry
;
12441 switch(questGiver
->GetTypeId())
12444 mailType
= MAIL_CREATURE
;
12445 senderGuidOrEntry
= questGiver
->GetEntry();
12447 case TYPEID_GAMEOBJECT
:
12448 mailType
= MAIL_GAMEOBJECT
;
12449 senderGuidOrEntry
= questGiver
->GetEntry();
12452 mailType
= MAIL_ITEM
;
12453 senderGuidOrEntry
= questGiver
->GetEntry();
12455 case TYPEID_PLAYER
:
12456 mailType
= MAIL_NORMAL
;
12457 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12460 mailType
= MAIL_NORMAL
;
12461 senderGuidOrEntry
= GetGUIDLow();
12465 Loot questMailLoot
;
12467 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12470 MailItemsInfo mi
; // item list preparing
12472 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12473 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12475 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12477 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12479 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12480 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12485 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12488 if(pQuest
->IsDaily())
12490 SetDailyQuestStatus(quest_id
);
12491 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12494 if ( !pQuest
->IsRepeatable() )
12495 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12497 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12499 q_status
.m_rewarded
= true;
12502 SendQuestReward( pQuest
, XP
, questGiver
);
12504 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12505 if (pQuest
->GetZoneOrSort() > 0)
12506 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
12507 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12508 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
12513 // remove auras from spells with quest reward state limitations
12514 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12515 if(saEndBounds
.first
!= saEndBounds
.second
)
12517 GetZoneAndAreaId(zone
,area
);
12519 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12520 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12521 RemoveAurasDueToSpell(itr
->second
->spellId
);
12524 // Some spells applied at quest reward
12525 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12526 if(saBounds
.first
!= saBounds
.second
)
12529 GetZoneAndAreaId(zone
,area
);
12531 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12532 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12533 if( !HasAura(itr
->second
->spellId
,0) )
12534 CastSpell(this,itr
->second
->spellId
,true);
12538 void Player::FailQuest( uint32 quest_id
)
12542 IncompleteQuest( quest_id
);
12544 uint16 log_slot
= FindQuestSlot( quest_id
);
12545 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12547 SetQuestSlotTimer(log_slot
, 1 );
12548 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12550 SendQuestFailed( quest_id
);
12554 void Player::FailTimedQuest( uint32 quest_id
)
12558 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12560 q_status
.m_timer
= 0;
12561 if (q_status
.uState
!= QUEST_NEW
)
12562 q_status
.uState
= QUEST_CHANGED
;
12564 IncompleteQuest( quest_id
);
12566 uint16 log_slot
= FindQuestSlot( quest_id
);
12567 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12569 SetQuestSlotTimer(log_slot
, 1 );
12570 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12572 SendQuestTimerFailed( quest_id
);
12576 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12578 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12579 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12581 // skip zone zoneOrSort and 0 case skillOrClass
12582 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12585 int32 questSort
= -zoneOrSort
;
12586 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12588 // check class sort cases in zoneOrSort
12589 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12592 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12597 if( skillOrClass
< 0 )
12599 uint8 reqClass
= -int32(skillOrClass
);
12600 if(getClass() != reqClass
)
12603 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12608 else if( skillOrClass
> 0 )
12610 uint32 reqSkill
= skillOrClass
;
12611 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12614 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12622 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12624 if( getLevel() < qInfo
->GetMinLevel() )
12627 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12633 bool Player::SatisfyQuestLog( bool msg
)
12636 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12641 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12642 GetSession()->SendPacket( &data
);
12643 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12648 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12650 // No previous quest (might be first quest in a series)
12651 if( qInfo
->prevQuests
.empty())
12654 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12656 uint32 prevId
= abs(*iter
);
12658 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12659 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12661 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12663 // If any of the positive previous quests completed, return true
12664 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12666 // skip one-from-all exclusive group
12667 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12670 // each-from-all exclusive group ( < 0)
12671 // can be start if only all quests in prev quest exclusive group completed and rewarded
12672 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12673 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12675 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12677 for(; iter2
!= end
; ++iter2
)
12679 uint32 exclude_Id
= iter2
->second
;
12681 // skip checked quest id, only state of other quests in group is interesting
12682 if(exclude_Id
== prevId
)
12685 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12687 // alternative quest from group also must be completed and rewarded(reported)
12688 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12691 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12697 // If any of the negative previous quests active, return true
12698 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12699 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12701 // skip one-from-all exclusive group
12702 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12705 // each-from-all exclusive group ( < 0)
12706 // can be start if only all quests in prev quest exclusive group active
12707 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12708 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12710 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12712 for(; iter2
!= end
; ++iter2
)
12714 uint32 exclude_Id
= iter2
->second
;
12716 // skip checked quest id, only state of other quests in group is interesting
12717 if(exclude_Id
== prevId
)
12720 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12722 // alternative quest from group also must be active
12723 if( i_exstatus
== mQuestStatus
.end() ||
12724 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12725 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12728 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12737 // Has only positive prev. quests in non-rewarded state
12738 // and negative prev. quests in non-active state
12740 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12745 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12747 uint32 reqraces
= qInfo
->GetRequiredRaces();
12748 if ( reqraces
== 0 )
12750 if( (reqraces
& getRaceMask()) == 0 )
12753 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12759 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12761 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12762 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12765 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12769 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12770 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12773 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12780 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12782 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12783 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12786 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12792 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12794 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12797 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12803 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12805 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12806 if(qInfo
->GetExclusiveGroup() <= 0)
12809 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12810 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12812 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12814 for(; iter
!= end
; ++iter
)
12816 uint32 exclude_Id
= iter
->second
;
12818 // skip checked quest id, only state of other quests in group is interesting
12819 if(exclude_Id
== qInfo
->GetQuestId())
12822 // not allow have daily quest if daily quest from exclusive group already recently completed
12823 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12824 if( !SatisfyQuestDay(Nquest
, false) )
12827 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12831 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12833 // alternative quest already started or completed
12834 if( i_exstatus
!= mQuestStatus
.end()
12835 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12838 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12845 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12847 if(!qInfo
->GetNextQuestInChain())
12850 // next quest in chain already started or completed
12851 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12852 if( itr
!= mQuestStatus
.end()
12853 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12856 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12860 // check for all quests further up the chain
12861 // only necessary if there are quest chains with more than one quest that can be skipped
12862 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12866 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12868 // No previous quest in chain
12869 if( qInfo
->prevChainQuests
.empty())
12872 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12874 uint32 prevId
= *iter
;
12876 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12878 if( i_prevstatus
!= mQuestStatus
.end() )
12880 // If any of the previous quests in chain active, return false
12881 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12882 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12885 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12890 // check for all quests further down the chain
12891 // only necessary if there are quest chains with more than one quest that can be skipped
12892 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12896 // No previous quest in chain active
12900 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12902 if(!qInfo
->IsDaily())
12905 bool have_slot
= false;
12906 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12908 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12909 if(qInfo
->GetQuestId()==id
)
12919 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12926 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12928 uint32 srcitem
= pQuest
->GetSrcItemId();
12931 uint32 count
= pQuest
->GetSrcItemCount();
12935 ItemPosCountVec dest
;
12936 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12937 if( msg
== EQUIP_ERR_OK
)
12939 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12940 SendNewItem(item
, count
, true, false);
12943 // player already have max amount required item, just report success
12944 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12947 SendEquipError( msg
, NULL
, NULL
);
12954 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12956 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12959 uint32 srcitem
= qInfo
->GetSrcItemId();
12962 uint32 count
= qInfo
->GetSrcItemCount();
12966 // exist one case when destroy source quest item not possible:
12967 // non un-equippable item (equipped non-empty bag, for example)
12968 uint8 res
= CanUnequipItems(srcitem
,count
);
12969 if(res
!= EQUIP_ERR_OK
)
12972 SendEquipError( res
, NULL
, NULL
);
12976 DestroyItemCount(srcitem
, count
, true, true);
12982 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12984 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12987 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12988 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12989 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12990 && !qInfo
->IsRepeatable() )
12991 return itr
->second
.m_rewarded
;
12998 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13002 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13003 if( itr
!= mQuestStatus
.end() )
13004 return itr
->second
.m_status
;
13006 return QUEST_STATUS_NONE
;
13009 bool Player::CanShareQuest(uint32 quest_id
) const
13011 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13012 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13014 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13015 if( itr
!= mQuestStatus
.end() )
13016 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13021 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13023 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13026 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13028 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13029 m_timedquests
.erase(qInfo
->GetQuestId());
13032 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13034 q_status
.m_status
= status
;
13035 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13038 UpdateForQuestWorldObjects();
13041 // not used in MaNGOS, but used in scripting code
13042 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13044 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13048 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13049 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13050 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13055 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13057 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13059 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13061 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13062 if( reqitemcount
!= 0 )
13064 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13066 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13067 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13073 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13075 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13076 if ( GetQuestSlotQuestId(i
) == quest_id
)
13079 return MAX_QUEST_LOG_SIZE
;
13082 void Player::AreaExploredOrEventHappens( uint32 questId
)
13086 uint16 log_slot
= FindQuestSlot( questId
);
13087 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13089 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13091 if(!q_status
.m_explored
)
13093 q_status
.m_explored
= true;
13094 if (q_status
.uState
!= QUEST_NEW
)
13095 q_status
.uState
= QUEST_CHANGED
;
13098 if( CanCompleteQuest( questId
) )
13099 CompleteQuest( questId
);
13103 //not used in mangosd, function for external script library
13104 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13106 if( Group
*pGroup
= GetGroup() )
13108 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13110 Player
*pGroupGuy
= itr
->getSource();
13112 // for any leave or dead (with not released body) group member at appropriate distance
13113 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13114 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13118 AreaExploredOrEventHappens(questId
);
13121 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13123 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13125 uint32 questid
= GetQuestSlotQuestId(i
);
13126 if ( questid
== 0 )
13129 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13131 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13134 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13135 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13138 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13140 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13141 if ( reqitem
== entry
)
13143 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13144 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13145 if ( curitemcount
< reqitemcount
)
13147 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13148 q_status
.m_itemcount
[j
] += additemcount
;
13149 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13151 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13153 if ( CanCompleteQuest( questid
) )
13154 CompleteQuest( questid
);
13159 UpdateForQuestWorldObjects();
13162 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13164 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13166 uint32 questid
= GetQuestSlotQuestId(i
);
13169 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13172 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13175 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13177 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13178 if ( reqitem
== entry
)
13180 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13182 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13183 uint32 curitemcount
;
13184 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13185 curitemcount
= q_status
.m_itemcount
[j
];
13187 curitemcount
= GetItemCount(entry
,true);
13188 if ( curitemcount
< reqitemcount
+ count
)
13190 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13191 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13192 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13194 IncompleteQuest( questid
);
13200 UpdateForQuestWorldObjects();
13203 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13205 uint32 addkillcount
= 1;
13206 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13207 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13209 uint32 questid
= GetQuestSlotQuestId(i
);
13213 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13216 // just if !ingroup || !noraidgroup || raidgroup
13217 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13218 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13220 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13222 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13224 // skip GO activate objective or none
13225 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13228 // skip Cast at creature objective
13229 if(qInfo
->ReqSpell
[j
] !=0 )
13232 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13234 if ( reqkill
== entry
)
13236 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13237 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13238 if ( curkillcount
< reqkillcount
)
13240 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13241 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13243 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13245 if ( CanCompleteQuest( questid
) )
13246 CompleteQuest( questid
);
13248 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13257 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13259 bool isCreature
= IS_CREATURE_GUID(guid
);
13261 uint32 addCastCount
= 1;
13262 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13264 uint32 questid
= GetQuestSlotQuestId(i
);
13268 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13272 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13274 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13276 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13278 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13280 // skip kill creature objective (0) or wrong spell casts
13281 if(qInfo
->ReqSpell
[j
] != spell_id
)
13284 uint32 reqTarget
= 0;
13288 // creature activate objectives
13289 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13290 // checked at quest_template loading
13291 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13295 // GO activate objective
13296 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13297 // checked at quest_template loading
13298 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13301 // other not this creature/GO related objectives
13302 if( reqTarget
!= entry
)
13305 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13306 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13307 if ( curCastCount
< reqCastCount
)
13309 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13310 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13312 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13315 if ( CanCompleteQuest( questid
) )
13316 CompleteQuest( questid
);
13318 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13326 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13328 uint32 addTalkCount
= 1;
13329 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13331 uint32 questid
= GetQuestSlotQuestId(i
);
13335 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13339 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13341 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13343 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13345 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13347 // skip spell casts and Gameobject objectives
13348 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13351 uint32 reqTarget
= 0;
13353 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13354 // checked at quest_template loading
13355 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13359 if ( reqTarget
== entry
)
13361 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13362 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13363 if ( curTalkCount
< reqTalkCount
)
13365 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13366 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13368 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13370 if ( CanCompleteQuest( questid
) )
13371 CompleteQuest( questid
);
13373 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13382 void Player::MoneyChanged( uint32 count
)
13384 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13386 uint32 questid
= GetQuestSlotQuestId(i
);
13390 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13391 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13393 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13395 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13397 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13399 if ( CanCompleteQuest( questid
) )
13400 CompleteQuest( questid
);
13403 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13405 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13406 IncompleteQuest( questid
);
13412 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
13414 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13416 if(uint32 questid
= GetQuestSlotQuestId(i
))
13418 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
))
13420 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
13422 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13423 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13425 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
13426 if ( CanCompleteQuest( questid
) )
13427 CompleteQuest( questid
);
13429 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13431 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
13432 IncompleteQuest( questid
);
13440 bool Player::HasQuestForItem( uint32 itemid
) const
13442 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13444 uint32 questid
= GetQuestSlotQuestId(i
);
13445 if ( questid
== 0 )
13448 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13449 if(qs_itr
== mQuestStatus
.end())
13452 QuestStatusData
const& q_status
= qs_itr
->second
;
13454 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13456 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13460 // hide quest if player is in raid-group and quest is no raid quest
13461 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13464 // There should be no mixed ReqItem/ReqSource drop
13465 // This part for ReqItem drop
13466 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13468 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13471 // This part - for ReqSource
13472 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
13474 // examined item is a source item
13475 if (qinfo
->ReqSourceId
[j
] == itemid
)
13477 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13480 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13483 // allows custom amount drop when not 0
13484 if (qinfo
->ReqSourceCount
[j
])
13486 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13488 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13497 void Player::SendQuestComplete( uint32 quest_id
)
13501 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13502 data
<< uint32(quest_id
);
13503 GetSession()->SendPacket( &data
);
13504 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13508 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13510 uint32 questid
= pQuest
->GetQuestId();
13511 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13512 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13513 data
<< uint32(questid
);
13515 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13517 data
<< uint32(XP
);
13518 data
<< uint32(pQuest
->GetRewOrReqMoney());
13523 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13526 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13527 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13528 GetSession()->SendPacket( &data
);
13530 if (pQuest
->GetQuestCompleteScript() != 0)
13531 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13534 void Player::SendQuestFailed( uint32 quest_id
)
13538 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13540 data
<< uint32(0); // failed reason (4 for inventory is full)
13541 GetSession()->SendPacket( &data
);
13542 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13546 void Player::SendQuestTimerFailed( uint32 quest_id
)
13550 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13552 GetSession()->SendPacket( &data
);
13553 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13557 void Player::SendCanTakeQuestResponse( uint32 msg
)
13559 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13560 data
<< uint32(msg
);
13561 GetSession()->SendPacket( &data
);
13562 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13565 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13569 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13570 data
<< uint64(pPlayer
->GetGUID());
13571 data
<< uint8(msg
); // valid values: 0-8
13572 GetSession()->SendPacket( &data
);
13573 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13577 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13579 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13580 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13581 //data << pQuest->ReqItemId[item_idx];
13583 GetSession()->SendPacket( &data
);
13586 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13588 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13590 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13592 // client expected gameobject template id in form (id|0x80000000)
13593 entry
= (-entry
) | 0x80000000;
13595 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13596 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13597 data
<< uint32(pQuest
->GetQuestId());
13598 data
<< uint32(entry
);
13599 data
<< uint32(old_count
+ add_count
);
13600 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13601 data
<< uint64(guid
);
13602 GetSession()->SendPacket(&data
);
13604 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13605 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13606 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13609 /*********************************************************/
13610 /*** LOAD SYSTEM ***/
13611 /*********************************************************/
13613 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13615 bool delete_result
= true;
13618 // 0 1 2 3 4 5 6 7 8 9
13619 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13620 if(!result
) return false;
13622 else delete_result
= false;
13624 Field
*fields
= result
->Fetch();
13626 if(!LoadValues( fields
[1].GetString()))
13628 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13629 if(delete_result
) delete result
;
13633 // overwrite possible wrong/corrupted guid
13634 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13636 m_name
= fields
[2].GetCppString();
13638 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13639 SetMapId(fields
[6].GetUInt32());
13640 // the instance id is not needed at character enum
13642 m_Played_time
[0] = fields
[7].GetUInt32();
13643 m_Played_time
[1] = fields
[8].GetUInt32();
13645 m_atLoginFlags
= fields
[9].GetUInt32();
13647 // I don't see these used anywhere ..
13650 _LoadBoundInstances();*/
13652 if (delete_result
) delete result
;
13654 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
13657 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13658 m_deathState
= DEAD
;
13663 void Player::_LoadDeclinedNames(QueryResult
* result
)
13669 delete m_declinedname
;
13671 m_declinedname
= new DeclinedName
;
13672 Field
*fields
= result
->Fetch();
13673 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13674 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13679 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13681 // arenateamid, played_week, played_season, personal_rating
13682 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13688 Field
*fields
= result
->Fetch();
13690 uint32 arenateamid
= fields
[0].GetUInt32();
13691 uint32 played_week
= fields
[1].GetUInt32();
13692 uint32 played_season
= fields
[2].GetUInt32();
13693 uint32 personal_rating
= fields
[3].GetUInt32();
13695 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13698 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13701 uint8 arenaSlot
= aTeam
->GetSlot();
13703 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13704 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13705 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13706 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13707 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13708 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13710 }while (result
->NextRow());
13714 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13716 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13720 Field
*fields
= result
->Fetch();
13722 x
= fields
[0].GetFloat();
13723 y
= fields
[1].GetFloat();
13724 z
= fields
[2].GetFloat();
13725 o
= fields
[3].GetFloat();
13726 mapid
= fields
[4].GetUInt32();
13727 in_flight
= !fields
[5].GetCppString().empty();
13733 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13735 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13739 Field
*fields
= result
->Fetch();
13741 data
= StrSplit(fields
[0].GetCppString(), " ");
13748 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13750 if(index
>= data
.size())
13753 return (uint32
)atoi(data
[index
].c_str());
13756 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13759 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13760 memcpy(&result
, &temp
, sizeof(result
));
13765 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13768 if(!LoadValuesArrayFromDB(data
,guid
))
13771 return GetUInt32ValueFromArray(data
,index
);
13774 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13777 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13778 memcpy(&result
, &temp
, sizeof(result
));
13783 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13785 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13786 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13787 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13791 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13795 Field
*fields
= result
->Fetch();
13797 uint32 dbAccountId
= fields
[1].GetUInt32();
13799 // check if the character's account in the db and the logged in account match.
13800 // player should be able to load/delete character only with correct account!
13801 if( dbAccountId
!= GetSession()->GetAccountId() )
13803 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13808 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13810 m_name
= fields
[3].GetCppString();
13812 // check name limitations
13813 if(!ObjectMgr::IsValidName(m_name
) || (GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
)))
13816 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13820 if(!LoadValues( fields
[2].GetString()))
13822 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13827 // overwrite possible wrong/corrupted guid
13828 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13830 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13831 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13833 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13834 SetVisibleItemSlot(slot
,NULL
);
13838 delete m_items
[slot
];
13839 m_items
[slot
] = NULL
;
13843 // update money limits
13844 if(GetMoney() > MAX_MONEY_AMOUNT
)
13845 SetMoney(MAX_MONEY_AMOUNT
);
13847 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13850 m_race
= fields
[4].GetUInt8();
13851 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13852 //Other way is to saves m_team into characters table.
13853 setFactionForRace(m_race
);
13856 m_class
= fields
[5].GetUInt8();
13858 // load home bind and check in same time class/race pair, it used later for restore broken positions
13859 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13862 InitPrimaryProffesions(); // to max set before any spell loaded
13864 // init saved position, and fix it later if problematic
13865 uint32 transGUID
= fields
[24].GetUInt32();
13866 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13867 SetMapId(fields
[9].GetUInt32());
13868 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13870 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13872 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
13874 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
13875 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
13876 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
13878 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
13880 // check arena teams integrity
13881 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13883 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13887 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13888 if(at
->HaveMember(GetGUID()))
13891 // arena team not exist or not member, cleanup fields
13892 for(int j
=0; j
< 6; ++j
)
13893 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13896 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13898 if(!IsPositionValid())
13900 sLog
.outError("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());
13901 RelocateToHomebind();
13905 m_movementInfo
.t_x
= 0.0f
;
13906 m_movementInfo
.t_y
= 0.0f
;
13907 m_movementInfo
.t_z
= 0.0f
;
13908 m_movementInfo
.t_o
= 0.0f
;
13911 uint32 bgid
= fields
[34].GetUInt32();
13912 uint32 bgteam
= fields
[35].GetUInt32();
13914 if(bgid
) //saved in BattleGround
13916 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13918 // check entry point and fix to homebind if need
13919 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
13920 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
13921 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
13923 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
, BATTLEGROUND_TYPE_NONE
);
13925 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
13927 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
13928 AddBattleGroundQueueId(bgQueueTypeId
);
13930 SetBattleGroundId(currentBg
->GetInstanceID(), currentBg
->GetTypeID());
13933 //join player to battleground group
13934 currentBg
->EventPlayerLoggedIn(this, GetGUID());
13935 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
13937 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
13941 Relocate(GetBattleGroundEntryPoint());
13942 //RemoveArenaAuras(true);
13947 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
13948 // if server restart after player save in BG or area
13949 // player can have current coordinates in to BG/Arean map, fix this
13950 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
13952 // return to BG master
13953 SetMapId(fields
[36].GetUInt32());
13954 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13956 // check entry point and fix to homebind if need
13957 mapEntry
= sMapStore
.LookupEntry(GetMapId());
13958 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
13959 RelocateToHomebind();
13963 if (transGUID
!= 0)
13965 m_movementInfo
.t_x
= fields
[20].GetFloat();
13966 m_movementInfo
.t_y
= fields
[21].GetFloat();
13967 m_movementInfo
.t_z
= fields
[22].GetFloat();
13968 m_movementInfo
.t_o
= fields
[23].GetFloat();
13970 if( !MaNGOS::IsValidMapCoord(
13971 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13972 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13973 // transport size limited
13974 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13976 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13977 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13978 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13980 RelocateToHomebind();
13982 m_movementInfo
.t_x
= 0.0f
;
13983 m_movementInfo
.t_y
= 0.0f
;
13984 m_movementInfo
.t_z
= 0.0f
;
13985 m_movementInfo
.t_o
= 0.0f
;
13991 if (transGUID
!= 0)
13993 for (MapManager::TransportSet::const_iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13995 if( (*iter
)->GetGUIDLow() == transGUID
)
13997 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
13998 // client without expansion support
13999 if(GetSession()->Expansion() < transMapEntry
->Expansion())
14001 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
14005 m_transport
= *iter
;
14006 m_transport
->AddPassenger(this);
14007 SetMapId(m_transport
->GetMapId());
14014 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14017 RelocateToHomebind();
14019 m_movementInfo
.t_x
= 0.0f
;
14020 m_movementInfo
.t_y
= 0.0f
;
14021 m_movementInfo
.t_z
= 0.0f
;
14022 m_movementInfo
.t_o
= 0.0f
;
14027 else // not transport case
14029 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14030 // client without expansion support
14031 if(GetSession()->Expansion() < mapEntry
->Expansion())
14033 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14034 RelocateToHomebind();
14038 // NOW player must have valid map
14039 // load the player's map here if it's not already loaded
14040 Map
*map
= GetMap();
14042 // since the player may not be bound to the map yet, make sure subsequent
14043 // getmap calls won't create new maps
14044 SetInstanceId(map
->GetInstanceId());
14046 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14047 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14049 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14051 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14053 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14056 SaveRecallPosition();
14058 time_t now
= time(NULL
);
14059 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14061 // since last logout (in seconds)
14062 uint64 time_diff
= uint64(now
- logoutTime
);
14064 // set value, including drunk invisibility detection
14065 // calculate sobering. after 15 minutes logged out, the player will be sober again
14067 if(time_diff
> 15*MINUTE
)
14070 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14071 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14072 SetDrunkValue(newDrunkenValue
);
14074 m_rest_bonus
= fields
[15].GetFloat();
14075 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14076 float bubble0
= 0.031;
14077 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14078 float bubble1
= 0.125;
14080 if((int32
)fields
[16].GetUInt32() > 0)
14082 float bubble
= fields
[17].GetUInt32() > 0
14083 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14084 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14086 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14089 m_cinematic
= fields
[12].GetUInt32();
14090 m_Played_time
[0]= fields
[13].GetUInt32();
14091 m_Played_time
[1]= fields
[14].GetUInt32();
14093 m_resetTalentsCost
= fields
[18].GetUInt32();
14094 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14096 // reserve some flags
14097 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14099 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14100 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14102 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14104 uint32 extraflags
= fields
[25].GetUInt32();
14106 m_stableSlots
= fields
[26].GetUInt32();
14107 if(m_stableSlots
> MAX_PET_STABLES
)
14109 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
14110 m_stableSlots
= MAX_PET_STABLES
;
14113 m_atLoginFlags
= fields
[27].GetUInt32();
14116 // Update Honor kills data
14117 m_lastHonorUpdateTime
= logoutTime
;
14118 UpdateHonorFields();
14120 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14121 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14122 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14124 std::string taxi_nodes
= fields
[31].GetCppString();
14128 // clear channel spell data (if saved at channel spell casting)
14129 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14130 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14132 // clear charm/summon related fields
14139 // reset some aura modifiers before aura apply
14140 SetFarSightGUID(0);
14141 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14142 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14146 // make sure the unit is considered out of combat for proper loading
14149 // make sure the unit is considered not in duel for proper loading
14150 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14151 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14153 // remember loaded power/health values to restore after stats initialization and modifier applying
14154 uint32 savedHealth
= GetHealth();
14155 uint32 savedPower
[MAX_POWERS
];
14156 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14157 savedPower
[i
] = GetPower(Powers(i
));
14159 // reset stats before loading any modifiers
14160 InitStatsForLevel();
14161 InitTaxiNodesForLevel();
14162 InitGlyphsForLevel();
14165 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14167 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14170 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14173 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14174 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14175 m_deathState
= DEAD
;
14177 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14179 // after spell load, learn rewarded spell if need also
14180 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14181 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14183 // after spell and quest load
14184 InitTalentForLevel();
14185 learnDefaultSpells();
14187 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14189 // must be before inventory (some items required reputation check)
14190 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14192 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14194 // update items with duration and realtime
14195 UpdateItemDuration(time_diff
, true);
14197 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14199 // unread mails and next delivery time, actual mails not loaded
14200 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14202 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14204 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14205 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14206 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14208 if(!HasTitle(curTitle
))
14209 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14212 // Not finish taxi flight path
14213 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14215 // problems with taxi path loading
14216 TaxiNodesEntry
const* nodeEntry
= NULL
;
14217 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14218 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14220 if(!nodeEntry
) // don't know taxi start node, to homebind
14222 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14223 RelocateToHomebind();
14224 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14226 else // have start node, to it
14228 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14229 SetMapId(nodeEntry
->map_id
);
14230 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14231 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14233 m_taxi
.ClearTaxiDestinations();
14235 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14237 // save source node as recall coord to prevent recall and fall from sky
14238 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14239 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14240 m_recallMap
= nodeEntry
->map_id
;
14241 m_recallX
= nodeEntry
->x
;
14242 m_recallY
= nodeEntry
->y
;
14243 m_recallZ
= nodeEntry
->z
;
14245 // flight will started later
14248 // has to be called after last Relocate() in Player::LoadFromDB
14249 SetFallInformation(0, GetPositionZ());
14251 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14253 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14254 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14256 RemoveAllAurasOnDeath();
14258 //apply all stat bonuses from items and auras
14259 SetCanModifyStats(true);
14262 // restore remembered power/health values (but not more max values)
14263 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14264 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14265 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14267 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14271 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14273 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14276 case 0: break; // disable
14277 case 1: SetGameMaster(true); break; // enable
14278 case 2: // save state
14279 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14280 SetGameMaster(true);
14284 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14287 case 0: SetGMVisible(false); break; // invisible
14288 case 1: break; // visible
14289 case 2: // save state
14290 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14291 SetGMVisible(false);
14295 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14298 case 0: break; // disable
14299 case 1: SetAcceptTicket(true); break; // enable
14300 case 2: // save state
14301 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14302 SetAcceptTicket(true);
14306 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14309 case 0: break; // disable
14310 case 1: SetGMChat(true); break; // enable
14311 case 2: // save state
14312 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14317 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14320 case 0: break; // disable
14321 case 1: SetAcceptWhispers(true); break; // enable
14322 case 2: // save state
14323 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14324 SetAcceptWhispers(true);
14329 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14331 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14332 m_achievementMgr
.CheckAllAchievementCriteria();
14336 bool Player::isAllowedToLoot(Creature
* creature
)
14338 if(Player
* recipient
= creature
->GetLootRecipient())
14340 if (recipient
== this)
14342 if( Group
* otherGroup
= recipient
->GetGroup())
14344 Group
* thisGroup
= GetGroup();
14347 return thisGroup
== otherGroup
;
14352 // prevent other players from looting if the recipient got disconnected
14353 return !creature
->hasLootRecipient();
14356 void Player::_LoadActions(QueryResult
*result
)
14358 m_actionButtons
.clear();
14360 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14366 Field
*fields
= result
->Fetch();
14368 uint8 button
= fields
[0].GetUInt8();
14370 if(addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8()))
14371 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14374 sLog
.outError( " ...at loading, and will deleted in DB also");
14376 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14377 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14380 while( result
->NextRow() );
14386 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14389 for (int i
= 0; i
< TOTAL_AURAS
; ++i
)
14390 m_modAuras
[i
].clear();
14392 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14398 Field
*fields
= result
->Fetch();
14399 uint64 caster_guid
= fields
[0].GetUInt64();
14400 uint32 spellid
= fields
[1].GetUInt32();
14401 uint32 effindex
= fields
[2].GetUInt32();
14402 uint32 stackcount
= fields
[3].GetUInt32();
14403 int32 damage
= (int32
)fields
[4].GetUInt32();
14404 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14405 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14406 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14408 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14411 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14417 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14421 // negative effects should continue counting down after logout
14422 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14424 if(remaintime
<= int32(timediff
))
14427 remaintime
-= timediff
;
14430 // prevent wrong values of remaincharges
14431 if(spellproto
->procCharges
)
14433 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14434 remaincharges
= spellproto
->procCharges
;
14440 for(uint32 i
=0; i
<stackcount
; ++i
)
14442 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14444 damage
= aura
->GetModifier()->m_amount
;
14446 // reset stolen single target auras
14447 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
14448 aura
->SetIsSingleTarget(false);
14450 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14452 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14455 while( result
->NextRow() );
14460 if(m_class
== CLASS_WARRIOR
)
14461 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14464 void Player::_LoadGlyphAuras()
14466 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
14468 if (uint32 glyph
= GetGlyph(i
))
14470 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14472 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14474 if(gp
->TypeFlags
== gs
->TypeFlags
)
14476 CastSpell(this, gp
->SpellId
, true);
14480 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14483 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14486 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14488 // On any error remove glyph
14494 void Player::LoadCorpse()
14498 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14502 if(Corpse
*corpse
= GetCorpse())
14504 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14508 //Prevent Dead Player login without corpse
14509 ResurrectPlayer(0.5f
);
14514 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14516 //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());
14517 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14518 //NOTE: the "order by `bag`" is important because it makes sure
14519 //the bagMap is filled before items in the bags are loaded
14520 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14521 //expected to be equipped before offhand items (TODO: fixme)
14523 uint32 zone
= GetZoneId();
14527 std::list
<Item
*> problematicItems
;
14529 // prevent items from being added to the queue when stored
14530 m_itemUpdateQueueBlocked
= true;
14533 Field
*fields
= result
->Fetch();
14534 uint32 bag_guid
= fields
[1].GetUInt32();
14535 uint8 slot
= fields
[2].GetUInt8();
14536 uint32 item_guid
= fields
[3].GetUInt32();
14537 uint32 item_id
= fields
[4].GetUInt32();
14539 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14543 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14544 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14545 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14549 Item
*item
= NewItemOrBag(proto
);
14551 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14553 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14554 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14555 item
->FSetState(ITEM_REMOVED
);
14556 item
->SaveToDB(); // it also deletes item object !
14560 // not allow have in alive state item limited to another map/zone
14561 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14563 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14564 item
->FSetState(ITEM_REMOVED
);
14565 item
->SaveToDB(); // it also deletes item object !
14569 // "Conjured items disappear if you are logged out for more than 15 minutes"
14570 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14572 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14573 item
->FSetState(ITEM_REMOVED
);
14574 item
->SaveToDB(); // it also deletes item object !
14578 bool success
= true;
14582 // the item is not in a bag
14583 item
->SetContainer( NULL
);
14584 item
->SetSlot(slot
);
14586 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14588 ItemPosCountVec dest
;
14589 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14590 item
= StoreItem(dest
, item
, true);
14594 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14597 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14598 QuickEquipItem(dest
, item
);
14602 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14604 ItemPosCountVec dest
;
14605 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14606 item
= BankItem(dest
, item
, true);
14613 // store bags that may contain items in them
14614 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14615 bagMap
[item_guid
] = (Bag
*)item
;
14620 item
->SetSlot(NULL_SLOT
);
14621 // the item is in a bag, find the bag
14622 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
14623 if(itr
!= bagMap
.end())
14624 itr
->second
->StoreItem(slot
, item
, true );
14629 // item's state may have changed after stored
14631 item
->SetState(ITEM_UNCHANGED
, this);
14634 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
);
14635 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14636 problematicItems
.push_back(item
);
14638 } while (result
->NextRow());
14641 m_itemUpdateQueueBlocked
= false;
14643 // send by mail problematic items
14644 while(!problematicItems
.empty())
14647 MailItemsInfo mi
; // item list preparing
14649 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14651 Item
* item
= problematicItems
.front();
14652 problematicItems
.pop_front();
14654 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14657 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14659 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14663 _ApplyAllItemMods();
14666 // load mailed item which should receive current player
14667 void Player::_LoadMailedItems(Mail
*mail
)
14669 // data needs to be at first place for Item::LoadFromDB
14670 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail
->messageID
);
14676 Field
*fields
= result
->Fetch();
14677 uint32 item_guid_low
= fields
[1].GetUInt32();
14678 uint32 item_template
= fields
[2].GetUInt32();
14680 mail
->AddItem(item_guid_low
, item_template
);
14682 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14686 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
);
14687 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14688 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14692 Item
*item
= NewItemOrBag(proto
);
14694 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14696 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14697 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14698 item
->FSetState(ITEM_REMOVED
);
14699 item
->SaveToDB(); // it also deletes item object !
14704 } while (result
->NextRow());
14709 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14711 //set a count of unread mails
14712 //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);
14715 Field
*fieldMail
= resultUnread
->Fetch();
14716 unReadMails
= fieldMail
[0].GetUInt8();
14717 delete resultUnread
;
14720 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14721 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14722 if (resultDelivery
)
14724 Field
*fieldMail
= resultDelivery
->Fetch();
14725 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14726 delete resultDelivery
;
14730 void Player::_LoadMail()
14733 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14734 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());
14739 Field
*fields
= result
->Fetch();
14740 Mail
*m
= new Mail
;
14741 m
->messageID
= fields
[0].GetUInt32();
14742 m
->messageType
= fields
[1].GetUInt8();
14743 m
->sender
= fields
[2].GetUInt32();
14744 m
->receiver
= fields
[3].GetUInt32();
14745 m
->subject
= fields
[4].GetCppString();
14746 m
->itemTextId
= fields
[5].GetUInt32();
14747 bool has_items
= fields
[6].GetBool();
14748 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14749 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14750 m
->money
= fields
[9].GetUInt32();
14751 m
->COD
= fields
[10].GetUInt32();
14752 m
->checked
= fields
[11].GetUInt32();
14753 m
->stationery
= fields
[12].GetUInt8();
14754 m
->mailTemplateId
= fields
[13].GetInt16();
14756 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14758 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14759 m
->mailTemplateId
= 0;
14762 m
->state
= MAIL_STATE_UNCHANGED
;
14765 _LoadMailedItems(m
);
14767 m_mail
.push_back(m
);
14768 } while( result
->NextRow() );
14771 m_mailsLoaded
= true;
14774 void Player::LoadPet()
14776 //fixme: the pet should still be loaded if the player is not in world
14777 // just not added to the map
14780 Pet
*pet
= new Pet
;
14781 if(!pet
->LoadPetFromDB(this,0,0,true))
14786 void Player::_LoadQuestStatus(QueryResult
*result
)
14788 mQuestStatus
.clear();
14792 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14793 //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());
14799 Field
*fields
= result
->Fetch();
14801 uint32 quest_id
= fields
[0].GetUInt32();
14802 // used to be new, no delete?
14803 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14807 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14809 uint32 qstatus
= fields
[1].GetUInt32();
14810 if(qstatus
< MAX_QUEST_STATUS
)
14811 questStatusData
.m_status
= QuestStatus(qstatus
);
14814 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14815 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14818 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14819 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14821 time_t quest_time
= time_t(fields
[4].GetUInt64());
14823 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14825 AddTimedQuest( quest_id
);
14827 if (quest_time
<= sWorld
.GetGameTime())
14828 questStatusData
.m_timer
= 1;
14830 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
14835 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14836 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14837 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14838 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14839 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14840 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14841 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14842 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14844 questStatusData
.uState
= QUEST_UNCHANGED
;
14846 // add to quest log
14847 if( slot
< MAX_QUEST_LOG_SIZE
&&
14848 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14849 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14850 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14852 SetQuestSlot(slot
,quest_id
,quest_time
);
14854 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14855 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14857 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14858 if(questStatusData
.m_creatureOrGOcount
[idx
])
14859 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14864 if(questStatusData
.m_rewarded
)
14866 // learn rewarded spell if unknown
14867 learnQuestRewardedSpells(pQuest
);
14869 // set rewarded title if any
14870 if(pQuest
->GetCharTitleId())
14872 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14873 SetTitle(titleEntry
);
14876 if(pQuest
->GetBonusTalents())
14877 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
14880 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14883 while( result
->NextRow() );
14888 // clear quest log tail
14889 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14893 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14895 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14896 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14898 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14902 uint32 quest_daily_idx
= 0;
14906 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14908 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14912 Field
*fields
= result
->Fetch();
14914 uint32 quest_id
= fields
[0].GetUInt32();
14916 // save _any_ from daily quest times (it must be after last reset anyway)
14917 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14919 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14923 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14926 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14928 while( result
->NextRow() );
14933 m_DailyQuestChanged
= false;
14936 void Player::_LoadSpells(QueryResult
*result
)
14938 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14944 Field
*fields
= result
->Fetch();
14946 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
14948 while( result
->NextRow() );
14954 void Player::_LoadTutorials(QueryResult
*result
)
14956 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14962 Field
*fields
= result
->Fetch();
14964 for (int iI
=0; iI
<8; ++iI
)
14965 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14967 while( result
->NextRow() );
14972 m_TutorialsChanged
= false;
14975 void Player::_LoadGroup(QueryResult
*result
)
14977 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14980 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14982 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14985 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14986 SetGroup(group
, subgroup
);
14987 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14989 // the group leader may change the instance difficulty while the player is offline
14990 SetDifficulty(group
->GetDifficulty());
14996 void Player::_LoadBoundInstances(QueryResult
*result
)
14998 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
14999 m_boundInstances
[i
].clear();
15001 Group
*group
= GetGroup();
15003 //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));
15008 Field
*fields
= result
->Fetch();
15009 bool perm
= fields
[1].GetBool();
15010 uint32 mapId
= fields
[2].GetUInt32();
15011 uint32 instanceId
= fields
[0].GetUInt32();
15012 uint8 difficulty
= fields
[3].GetUInt8();
15013 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15014 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15015 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15016 // and in that case it is not used
15018 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
15019 if(!mapEntry
|| !mapEntry
->IsDungeon())
15021 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
15022 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15028 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
);
15029 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15033 // since non permanent binds are always solo bind, they can always be reset
15034 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15035 if(save
) BindToInstance(save
, perm
, true);
15036 } while(result
->NextRow());
15041 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15043 // some instances only have one difficulty
15044 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15045 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15047 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15048 if(itr
!= m_boundInstances
[difficulty
].end())
15049 return &itr
->second
;
15054 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15056 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15057 UnbindInstance(itr
, difficulty
, unload
);
15060 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15062 if(itr
!= m_boundInstances
[difficulty
].end())
15064 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15065 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15066 m_boundInstances
[difficulty
].erase(itr
++);
15070 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15074 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15077 // update the save when the group kills a boss
15078 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15079 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());
15082 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15084 if(bind
.save
!= save
)
15086 if(bind
.save
) bind
.save
->RemovePlayer(this);
15087 save
->AddPlayer(this);
15090 if(permanent
) save
->SetCanReset(false);
15093 bind
.perm
= permanent
;
15094 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());
15101 void Player::SendRaidInfo()
15103 uint32 counter
= 0;
15105 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15107 size_t p_counter
= data
.wpos();
15108 data
<< uint32(counter
); // placeholder
15110 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15112 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15114 if(itr
->second
.perm
)
15116 InstanceSave
*save
= itr
->second
.save
;
15117 data
<< uint32(save
->GetMapId());
15118 data
<< uint32(save
->GetResetTime() - time(NULL
));
15119 data
<< uint32(save
->GetInstanceId());
15120 data
<< uint32(save
->GetDifficulty());
15125 data
.put
<uint32
>(p_counter
,counter
);
15126 GetSession()->SendPacket(&data
);
15130 - called on every successful teleportation to a map
15132 void Player::SendSavedInstances()
15134 bool hasBeenSaved
= false;
15137 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15139 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15141 if(itr
->second
.perm
) // only permanent binds are sent
15143 hasBeenSaved
= true;
15149 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15150 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15151 data
<< uint32(hasBeenSaved
);
15152 GetSession()->SendPacket(&data
);
15157 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15159 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15161 if(itr
->second
.perm
)
15163 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15164 data
<< uint32(itr
->second
.save
->GetMapId());
15165 GetSession()->SendPacket(&data
);
15171 /// convert the player's binds to the group
15172 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15174 bool has_binds
= false;
15175 bool has_solo
= false;
15177 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15178 assert(player_guid
);
15180 // copy all binds to the group, when changing leader it's assumed the character
15181 // will not have any solo binds
15185 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15187 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15190 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15191 // permanent binds are not removed
15192 if(!itr
->second
.perm
)
15194 player
->UnbindInstance(itr
, i
, true); // increments itr
15203 // if the player's not online we don't know what binds it has
15204 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
));
15205 // the following should not get executed when changing leaders
15206 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15209 bool Player::_LoadHomeBind(QueryResult
*result
)
15211 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15214 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15219 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15222 Field
*fields
= result
->Fetch();
15223 m_homebindMapId
= fields
[0].GetUInt32();
15224 m_homebindZoneId
= fields
[1].GetUInt16();
15225 m_homebindX
= fields
[2].GetFloat();
15226 m_homebindY
= fields
[3].GetFloat();
15227 m_homebindZ
= fields
[4].GetFloat();
15230 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15232 // accept saved data only for valid position (and non instanceable), and accessable
15233 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15234 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15239 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15244 m_homebindMapId
= info
->mapId
;
15245 m_homebindZoneId
= info
->zoneId
;
15246 m_homebindX
= info
->positionX
;
15247 m_homebindY
= info
->positionY
;
15248 m_homebindZ
= info
->positionZ
;
15250 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
);
15253 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15254 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15259 /*********************************************************/
15260 /*** SAVE SYSTEM ***/
15261 /*********************************************************/
15263 void Player::SaveToDB()
15265 // delay auto save at any saves (manual, in code, or autosave)
15266 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15268 // first save/honor gain after midnight will also update the player's honor fields
15269 UpdateHonorFields();
15271 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15272 //save, far from tavern/city
15273 //save, but in tavern/city
15274 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15277 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15278 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15279 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15280 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15281 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15282 uint32 tmp_displayid
= GetDisplayId();
15284 // Set player sit state to standing on save, also stealth and shifted form
15285 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15286 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15287 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15288 SetDisplayId(GetNativeDisplayId());
15290 bool inworld
= IsInWorld();
15292 CharacterDatabase
.BeginTransaction();
15294 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15296 std::string sql_name
= m_name
;
15297 CharacterDatabase
.escape_string(sql_name
);
15299 std::ostringstream ss
;
15300 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15301 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15302 "taximask, online, cinematic, "
15303 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15304 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15305 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15306 << GetGUIDLow() << ", "
15307 << GetSession()->GetAccountId() << ", '"
15308 << sql_name
<< "', "
15310 << m_class
<< ", ";
15312 if(!IsBeingTeleported())
15314 ss
<< GetMapId() << ", "
15315 << (uint32
)GetDifficulty() << ", "
15316 << finiteAlways(GetPositionX()) << ", "
15317 << finiteAlways(GetPositionY()) << ", "
15318 << finiteAlways(GetPositionZ()) << ", "
15319 << finiteAlways(GetOrientation()) << ", '";
15323 ss
<< GetTeleportDest().mapid
<< ", "
15324 << (uint32
)GetDifficulty() << ", "
15325 << finiteAlways(GetTeleportDest().x
) << ", "
15326 << finiteAlways(GetTeleportDest().y
) << ", "
15327 << finiteAlways(GetTeleportDest().z
) << ", "
15328 << finiteAlways(GetTeleportDest().o
) << ", '";
15332 for( i
= 0; i
< m_valuesCount
; ++i
)
15334 ss
<< GetUInt32Value(i
) << " ";
15339 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15342 ss
<< (inworld
? 1 : 0);
15348 ss
<< m_Played_time
[0];
15350 ss
<< m_Played_time
[1];
15353 ss
<< finiteAlways(m_rest_bonus
);
15355 ss
<< (uint64
)time(NULL
);
15357 ss
<< is_save_resting
;
15359 ss
<< m_resetTalentsCost
;
15361 ss
<< (uint64
)m_resetTalentsTime
;
15364 ss
<< finiteAlways(m_movementInfo
.t_x
);
15366 ss
<< finiteAlways(m_movementInfo
.t_y
);
15368 ss
<< finiteAlways(m_movementInfo
.t_z
);
15370 ss
<< finiteAlways(m_movementInfo
.t_o
);
15373 ss
<< m_transport
->GetGUIDLow();
15378 ss
<< m_ExtraFlags
;
15381 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15384 ss
<< uint32(m_atLoginFlags
);
15390 ss
<< (uint64
)m_deathExpireTime
;
15393 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15395 ss
<< GetBattleGroundId();
15399 ss
<< m_bgEntryPoint
.mapid
<< ", "
15400 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15401 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15402 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15403 << finiteAlways(m_bgEntryPoint
.o
);
15406 CharacterDatabase
.Execute( ss
.str().c_str() );
15408 if(m_mailsUpdated
) //save mails only when needed
15412 _SaveQuestStatus();
15413 _SaveDailyQuestStatus();
15416 _SaveSpellCooldowns();
15419 m_achievementMgr
.SaveToDB();
15420 m_reputationMgr
.SaveToDB();
15422 CharacterDatabase
.CommitTransaction();
15424 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15425 SetDisplayId(tmp_displayid
);
15426 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15427 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15428 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15429 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15431 // save pet (hunter pet level and experience and all type pets health/mana).
15432 if(Pet
* pet
= GetPet())
15433 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15436 // fast save function for item/money cheating preventing - save only inventory and money state
15437 void Player::SaveInventoryAndGoldToDB()
15440 //money is in data field
15441 SaveDataFieldToDB();
15444 void Player::_SaveActions()
15446 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15448 switch (itr
->second
.uState
)
15450 case ACTIONBUTTON_NEW
:
15451 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15452 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15453 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15456 case ACTIONBUTTON_CHANGED
:
15457 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15458 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15459 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15462 case ACTIONBUTTON_DELETED
:
15463 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15464 m_actionButtons
.erase(itr
++);
15473 void Player::_SaveAuras()
15475 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15477 AuraMap
const& auras
= GetAuras();
15482 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15483 uint32 stackCounter
= 1;
15485 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15487 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15489 AuraMap::const_iterator itr2
= itr
;
15490 // save previous spellEffectPair to db
15493 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15495 //skip all auras from spells that are passive or need a shapeshift
15496 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15498 //do not save single target auras (unless they were cast by the player)
15499 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && itr2
->second
->IsSingleTarget()))
15502 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15503 for (i
= 0; i
< 3; ++i
)
15504 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15505 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15510 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15511 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15512 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->GetAuraCharges()));
15517 if(itr
== auras
.end())
15521 if (lastEffectPair
== itr
->first
)
15525 lastEffectPair
= itr
->first
;
15531 void Player::_SaveInventory()
15533 // force items in buyback slots to new state
15534 // and remove those that aren't already
15535 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
15537 Item
*item
= m_items
[i
];
15538 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15539 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15540 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15541 m_items
[i
]->FSetState(ITEM_NEW
);
15544 // update enchantment durations
15545 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15547 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15551 if (m_itemUpdateQueue
.empty()) return;
15553 // do not save if the update queue is corrupt
15554 bool error
= false;
15555 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15557 Item
*item
= m_itemUpdateQueue
[i
];
15558 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15559 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15563 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());
15566 else if (test
!= item
)
15568 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());
15575 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15576 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15580 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15582 Item
*item
= m_itemUpdateQueue
[i
];
15583 if(!item
) continue;
15585 Bag
*container
= item
->GetContainer();
15586 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15588 switch(item
->GetState())
15591 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());
15594 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());
15597 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15599 case ITEM_UNCHANGED
:
15603 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15605 m_itemUpdateQueue
.clear();
15608 void Player::_SaveMail()
15610 if (!m_mailsLoaded
)
15613 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15616 if (m
->state
== MAIL_STATE_CHANGED
)
15618 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'",
15619 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15620 if(m
->removedItems
.size())
15622 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15623 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15624 m
->removedItems
.clear();
15626 m
->state
= MAIL_STATE_UNCHANGED
;
15628 else if (m
->state
== MAIL_STATE_DELETED
)
15631 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15632 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15634 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15635 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15636 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15640 //deallocate deleted mails...
15641 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15643 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15648 itr
= m_mail
.begin();
15654 m_mailsUpdated
= false;
15657 void Player::_SaveQuestStatus()
15659 // we don't need transactions here.
15660 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15662 switch (i
->second
.uState
)
15665 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15666 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15667 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ 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]);
15669 case QUEST_CHANGED
:
15670 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' ",
15671 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ 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
);
15673 case QUEST_UNCHANGED
:
15676 i
->second
.uState
= QUEST_UNCHANGED
;
15680 void Player::_SaveDailyQuestStatus()
15682 if(!m_DailyQuestChanged
)
15685 m_DailyQuestChanged
= false;
15687 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15689 // we don't need transactions here.
15690 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15691 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15692 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15693 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15694 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15697 void Player::_SaveSpells()
15699 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15701 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15702 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15704 // add only changed/new not dependent spells
15705 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15706 CharacterDatabase
.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr
->first
, itr
->second
->active
? 1 : 0,itr
->second
->disabled
? 1 : 0);
15708 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15710 delete itr
->second
;
15711 m_spells
.erase(itr
++);
15715 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15722 void Player::_SaveTutorials()
15724 if(!m_TutorialsChanged
)
15728 // it's better than rebuilding indexes multiple times
15729 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15732 Rows
= result
->Fetch()[0].GetUInt32();
15738 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'",
15739 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
);
15743 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]);
15746 m_TutorialsChanged
= false;
15749 void Player::outDebugValues() const
15751 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15754 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15755 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15756 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15757 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15758 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15759 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15760 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15761 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15762 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15763 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15764 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15765 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15768 /*********************************************************/
15769 /*** FLOOD FILTER SYSTEM ***/
15770 /*********************************************************/
15772 void Player::UpdateSpeakTime()
15774 // ignore chat spam protection for GMs in any mode
15775 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15778 time_t current
= time (NULL
);
15779 if(m_speakTime
> current
)
15781 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15786 if(m_speakCount
>= max_count
)
15788 // prevent overwrite mute time, if message send just before mutes set, for example.
15789 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15790 if(GetSession()->m_muteTime
< new_mute
)
15791 GetSession()->m_muteTime
= new_mute
;
15799 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15802 bool Player::CanSpeak() const
15804 return GetSession()->m_muteTime
<= time (NULL
);
15807 /*********************************************************/
15808 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15809 /*********************************************************/
15811 void Player::SendAttackSwingNotInRange()
15813 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15814 GetSession()->SendPacket( &data
);
15817 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15819 std::ostringstream ss
;
15820 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15821 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15822 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15823 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15824 sLog
.outDebug(ss
.str().c_str());
15825 CharacterDatabase
.Execute(ss
.str().c_str());
15828 void Player::SaveDataFieldToDB()
15830 std::ostringstream ss
;
15831 ss
<<"UPDATE characters SET data='";
15833 for(uint16 i
= 0; i
< m_valuesCount
; ++i
)
15835 ss
<< GetUInt32Value(i
) << " ";
15837 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15839 CharacterDatabase
.Execute(ss
.str().c_str());
15842 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15844 std::ostringstream ss2
;
15845 ss2
<<"UPDATE characters SET data='";
15847 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15849 ss2
<<tokens
[i
]<<" ";
15851 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15853 return CharacterDatabase
.Execute(ss2
.str().c_str());
15856 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15859 snprintf(buf
,11,"%u",value
);
15861 if(index
>= tokens
.size())
15864 tokens
[index
] = buf
;
15867 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15870 if(!LoadValuesArrayFromDB(tokens
,guid
))
15873 if(index
>= tokens
.size())
15877 snprintf(buf
,11,"%u",value
);
15878 tokens
[index
] = buf
;
15880 SaveValuesArrayInDB(tokens
,guid
);
15883 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15886 memcpy(&temp
, &value
, sizeof(value
));
15887 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15890 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
15893 if(!LoadValuesArrayFromDB(tokens
, guid
))
15896 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
15897 uint8 race
= unit_bytes0
& 0xFF;
15898 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
15900 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
15904 unit_bytes0
&= ~(0xFF << 16);
15905 unit_bytes0
|= (gender
<< 16);
15906 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
15908 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15909 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15911 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
15913 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
15914 player_bytes2
&= ~0xFF;
15915 player_bytes2
|= facialHair
;
15916 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
15918 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
15919 player_bytes3
&= ~0xFF;
15920 player_bytes3
|= gender
;
15921 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
15923 SaveValuesArrayInDB(tokens
, guid
);
15926 void Player::SendAttackSwingNotStanding()
15928 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15929 GetSession()->SendPacket( &data
);
15932 void Player::SendAttackSwingDeadTarget()
15934 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15935 GetSession()->SendPacket( &data
);
15938 void Player::SendAttackSwingCantAttack()
15940 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15941 GetSession()->SendPacket( &data
);
15944 void Player::SendAttackSwingCancelAttack()
15946 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15947 GetSession()->SendPacket( &data
);
15950 void Player::SendAttackSwingBadFacingAttack()
15952 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15953 GetSession()->SendPacket( &data
);
15956 void Player::SendAutoRepeatCancel()
15958 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15959 data
.append(GetPackGUID()); // may be it's target guid
15960 GetSession()->SendPacket( &data
);
15963 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15965 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15967 data
<< Experience
;
15968 GetSession()->SendPacket(&data
);
15971 void Player::SendDungeonDifficulty(bool IsInGroup
)
15973 uint8 val
= 0x00000001;
15974 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15975 data
<< (uint32
)GetDifficulty();
15976 data
<< uint32(val
);
15977 data
<< uint32(IsInGroup
);
15978 GetSession()->SendPacket(&data
);
15981 void Player::SendResetFailedNotify(uint32 mapid
)
15983 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15984 data
<< uint32(mapid
);
15985 GetSession()->SendPacket(&data
);
15988 /// Reset all solo instances and optionally send a message on success for each
15989 void Player::ResetInstances(uint8 method
)
15991 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15993 // we assume that when the difficulty changes, all instances that can be reset will be
15994 uint8 dif
= GetDifficulty();
15996 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15998 InstanceSave
*p
= itr
->second
.save
;
15999 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16000 if(!entry
|| !p
->CanReset())
16006 if(method
== INSTANCE_RESET_ALL
)
16008 // the "reset all instances" method can only reset normal maps
16009 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16016 // if the map is loaded, reset it
16017 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16018 if(map
&& map
->IsDungeon())
16019 ((InstanceMap
*)map
)->Reset(method
);
16021 // since this is a solo instance there should not be any players inside
16022 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16023 SendResetInstanceSuccess(p
->GetMapId());
16026 m_boundInstances
[dif
].erase(itr
++);
16028 // the following should remove the instance save from the manager and delete it as well
16029 p
->RemovePlayer(this);
16033 void Player::SendResetInstanceSuccess(uint32 MapId
)
16035 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16037 GetSession()->SendPacket(&data
);
16040 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16042 // TODO: find what other fail reasons there are besides players in the instance
16043 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16046 GetSession()->SendPacket(&data
);
16049 /*********************************************************/
16050 /*** Update timers ***/
16051 /*********************************************************/
16053 ///checks the 15 afk reports per 5 minutes limit
16054 void Player::UpdateAfkReport(time_t currTime
)
16056 if(m_bgAfkReportedTimer
<= currTime
)
16058 m_bgAfkReportedCount
= 0;
16059 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16063 void Player::UpdateContestedPvP(uint32 diff
)
16065 if(!m_contestedPvPTimer
||isInCombat())
16067 if(m_contestedPvPTimer
<= diff
)
16069 ResetContestedPvP();
16072 m_contestedPvPTimer
-= diff
;
16075 void Player::UpdatePvPFlag(time_t currTime
)
16079 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16085 void Player::UpdateDuelFlag(time_t currTime
)
16087 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16090 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16091 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16093 duel
->startTimer
= 0;
16094 duel
->startTime
= currTime
;
16095 duel
->opponent
->duel
->startTimer
= 0;
16096 duel
->opponent
->duel
->startTime
= currTime
;
16099 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16104 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16106 //returning of reagents only for players, so best done here
16107 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16108 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16112 for(uint32 i
= 0; i
< 7; ++i
)
16114 if(spellInfo
->Reagent
[i
] > 0)
16116 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16117 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16118 if( msg
== EQUIP_ERR_OK
)
16120 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16122 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16127 m_temporaryUnsummonedPetNumber
= 0;
16130 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16133 // only if current pet in slot
16134 switch(pet
->getPetType())
16140 m_guardianPets
.erase(pet
->GetGUID());
16143 if(GetPetGUID() == pet
->GetGUID())
16152 switch(pet
->GetEntry())
16154 //warlock pets except imp are removed(?) when logging out
16159 mode
= PET_SAVE_NOT_IN_SLOT
;
16164 pet
->SavePetToDB(mode
);
16166 pet
->CleanupsBeforeDelete();
16167 pet
->AddObjectToRemoveList();
16168 pet
->m_removed
= true;
16170 if(pet
->isControlled())
16172 WorldPacket
data(SMSG_PET_SPELLS
, 8+4);
16175 GetSession()->SendPacket(&data
);
16178 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16182 void Player::RemoveMiniPet()
16184 if(Pet
* pet
= GetMiniPet())
16186 pet
->Remove(PET_SAVE_AS_DELETED
);
16191 Pet
* Player::GetMiniPet()
16195 return ObjectAccessor::GetPet(m_miniPet
);
16198 void Player::RemoveGuardians()
16200 while(!m_guardianPets
.empty())
16202 uint64 guid
= *m_guardianPets
.begin();
16203 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16204 pet
->Remove(PET_SAVE_AS_DELETED
);
16206 m_guardianPets
.erase(guid
);
16210 bool Player::HasGuardianWithEntry(uint32 entry
)
16212 // pet guid middle part is entry (and creature also)
16213 // and in guardian list must be guardians with same entry _always_
16214 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16216 if(Pet
* pet
= ObjectAccessor::GetPet(*itr
))
16217 if (pet
->GetEntry() == entry
)
16224 void Player::Uncharm()
16226 Unit
* charm
= GetCharm();
16230 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16231 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16234 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16236 *data
<< (uint8
)msgtype
;
16237 *data
<< (uint32
)language
;
16238 *data
<< (uint64
)GetGUID();
16239 *data
<< (uint32
)language
; //language 2.1.0 ?
16240 *data
<< (uint64
)GetGUID();
16241 *data
<< (uint32
)(text
.length()+1);
16243 *data
<< (uint8
)chatTag();
16246 void Player::Say(const std::string
& text
, const uint32 language
)
16248 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16249 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16250 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16253 void Player::Yell(const std::string
& text
, const uint32 language
)
16255 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16256 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16257 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16260 void Player::TextEmote(const std::string
& text
)
16262 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16263 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16264 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16267 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16269 if (language
!= LANG_ADDON
) // if not addon data
16270 language
= LANG_UNIVERSAL
; // whispers should always be readable
16272 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16274 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16275 if(!rPlayer
->isDND() || isGameMaster())
16277 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16278 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16279 rPlayer
->GetSession()->SendPacket(&data
);
16281 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16282 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16283 GetSession()->SendPacket(&data
);
16287 // announce to player that player he is whispering to is dnd and cannot receive his message
16288 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16291 if(!isAcceptWhispers())
16293 SetAcceptWhispers(true);
16294 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16297 // announce to player that player he is whispering to is afk
16298 if(rPlayer
->isAFK())
16299 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16301 // if player whisper someone, auto turn of dnd to be able to receive an answer
16302 if(isDND() && !rPlayer
->isGameMaster())
16306 void Player::PetSpellInitialize()
16308 Pet
* pet
= GetPet();
16313 sLog
.outDebug("Pet Spells Groups");
16315 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16317 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16318 data
<< uint64(pet
->GetGUID());
16319 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16321 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16324 for(uint32 i
= 0; i
< 10; ++i
)
16326 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16329 size_t spellsCountPos
= data
.wpos();
16333 data
<< uint8(addlist
); // placeholder
16335 if (pet
->IsPermanentPetFor(this))
16338 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16340 if(itr
->second
->state
== PETSPELL_REMOVED
)
16343 data
<< uint16(itr
->first
);
16344 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16349 data
.put
<uint8
>(spellsCountPos
, addlist
);
16351 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16352 data
<< uint8(cooldownsCount
);
16354 time_t curTime
= time(NULL
);
16356 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16358 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16360 data
<< uint16(itr
->first
); // spellid
16361 data
<< uint16(0); // spell category?
16362 data
<< uint32(cooldown
); // cooldown
16363 data
<< uint32(0); // category cooldown
16366 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16368 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16370 data
<< uint16(itr
->first
); // spellid
16371 data
<< uint16(0); // spell category?
16372 data
<< uint32(0); // cooldown
16373 data
<< uint32(cooldown
); // category cooldown
16376 GetSession()->SendPacket(&data
);
16379 void Player::PossessSpellInitialize()
16381 Unit
* charm
= GetCharm();
16386 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16390 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16395 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16398 data
<< uint64(charm
->GetGUID());
16399 data
<< uint32(0x00000000);
16403 for(uint32 i
= 0; i
< 10; ++i
) //40
16405 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16408 data
<< uint8(addlist
); //1
16411 data
<< uint8(count
); // cooldowns count
16413 GetSession()->SendPacket(&data
);
16416 void Player::CharmSpellInitialize()
16418 Unit
* charm
= GetCharm();
16423 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16426 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16432 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16434 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16436 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16438 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16440 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16446 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16448 data
<< uint64(charm
->GetGUID());
16449 data
<< uint32(0x00000000);
16451 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16452 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16454 data
<< uint8(0) << uint8(0);
16457 for(uint32 i
= 0; i
< 10; ++i
) //40
16459 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16462 data
<< uint8(addlist
); //1
16466 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16468 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16469 if(cspell
->spellId
)
16471 data
<< uint16(cspell
->spellId
);
16472 data
<< uint16(cspell
->active
);
16478 data
<< uint8(count
); // cooldowns count
16480 GetSession()->SendPacket(&data
);
16483 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16485 if (!mod
|| !spellInfo
)
16488 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16490 // prevent apply to any spell except spell that trigger expire
16493 if(mod
->lastAffected
!= spell
)
16496 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16500 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16503 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16505 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16507 for(int eff
=0;eff
<96;++eff
)
16511 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16512 else _mask2
= uint64(1) << (eff
-64);
16513 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16516 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16518 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16519 val
+= (*itr
)->value
;
16521 val
+= apply
? mod
->value
: -(mod
->value
);
16522 WorldPacket
data(Opcode
, (1+1+4));
16523 data
<< uint8(eff
);
16524 data
<< uint8(mod
->op
);
16525 data
<< int32(val
);
16526 SendDirectMessage(&data
);
16531 m_spellMods
[mod
->op
].push_back(mod
);
16534 if (mod
->charges
== -1)
16535 --m_SpellModRemoveCount
;
16536 m_spellMods
[mod
->op
].remove(mod
);
16541 void Player::RemoveSpellMods(Spell
const* spell
)
16543 if(!spell
|| (m_SpellModRemoveCount
== 0))
16546 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16548 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16550 SpellModifier
*mod
= *itr
;
16553 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16555 RemoveAurasDueToSpell(mod
->spellId
);
16556 if (m_spellMods
[i
].empty())
16559 itr
= m_spellMods
[i
].begin();
16565 // send Proficiency
16566 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16568 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16569 data
<< pr1
<< pr2
;
16570 GetSession()->SendPacket (&data
);
16573 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16575 QueryResult
*result
= NULL
;
16577 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16579 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16582 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.
16583 { // and SendPetitionQueryOpcode reads data from the DB
16584 Field
*fields
= result
->Fetch();
16585 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16586 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16588 // send update if charter owner in game
16589 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16591 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16593 } while ( result
->NextRow() );
16598 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16600 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16603 CharacterDatabase
.BeginTransaction();
16606 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16607 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16611 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16612 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16614 CharacterDatabase
.CommitTransaction();
16617 void Player::LeaveAllArenaTeams(uint64 guid
)
16619 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid
));
16625 Field
*fields
= result
->Fetch();
16626 uint32 at_id
= fields
[0].GetUInt32();
16629 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16631 at
->DelMember(guid
);
16633 } while (result
->NextRow());
16638 void Player::SetRestBonus (float rest_bonus_new
)
16640 // Prevent resting on max level
16641 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16642 rest_bonus_new
= 0;
16644 if(rest_bonus_new
< 0)
16645 rest_bonus_new
= 0;
16647 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16649 if(rest_bonus_new
> rest_bonus_max
)
16650 m_rest_bonus
= rest_bonus_max
;
16652 m_rest_bonus
= rest_bonus_new
;
16654 // update data for client
16655 if(m_rest_bonus
>10)
16656 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16657 else if(m_rest_bonus
<=1)
16658 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16661 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16664 void Player::HandleStealthedUnitsDetection()
16666 std::list
<Unit
*> stealthedUnits
;
16668 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16670 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16671 cell
.SetNoCreate();
16673 MaNGOS::AnyStealthedCheck u_check
;
16674 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16676 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16677 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16679 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16680 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16681 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16683 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16687 i
= stealthedUnits
.erase(i
);
16691 if ((*i
)->isVisibleForOrDetect(this,true))
16694 (*i
)->SendUpdateToPlayer(this);
16695 m_clientGUIDs
.insert((*i
)->GetGUID());
16697 #ifdef MANGOS_DEBUG
16698 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16699 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16702 // target aura duration for caster show only if target exist at caster client
16703 // send data at target visibility change (adding to client)
16704 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16705 SendAurasForTarget(*i
);
16707 i
= stealthedUnits
.erase(i
);
16715 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, Creature
* npc
/*= NULL*/, uint32 spellid
/*= 0*/)
16717 if(nodes
.size() < 2)
16720 // 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
16721 if(GetSession()->isLogingOut() || isInCombat())
16723 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16724 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16725 GetSession()->SendPacket(&data
);
16729 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16735 // not let cheating with start flight mounted
16738 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16739 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16740 GetSession()->SendPacket(&data
);
16744 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16746 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16747 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16748 GetSession()->SendPacket(&data
);
16752 // 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
16753 if(IsNonMeleeSpellCasted(false))
16755 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16756 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16757 GetSession()->SendPacket(&data
);
16761 // cast case or scripted call case
16764 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
16766 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16767 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
16769 if(m_currentSpells
[CURRENT_GENERIC_SPELL
] && m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Id
!= spellid
)
16770 InterruptSpell(CURRENT_GENERIC_SPELL
,false);
16772 InterruptSpell(CURRENT_AUTOREPEAT_SPELL
,false);
16774 if(m_currentSpells
[CURRENT_CHANNELED_SPELL
] && m_currentSpells
[CURRENT_CHANNELED_SPELL
]->m_spellInfo
->Id
!= spellid
)
16775 InterruptSpell(CURRENT_CHANNELED_SPELL
,true);
16778 uint32 sourcenode
= nodes
[0];
16780 // starting node too far away (cheat?)
16781 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16784 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16785 data
<< uint32(ERR_TAXINOSUCHPATH
);
16786 GetSession()->SendPacket(&data
);
16790 // check node starting pos data set case if provided
16791 if (node
->x
!= 0.0f
|| node
->y
!= 0.0f
|| node
->z
!= 0.0f
)
16793 if (node
->map_id
!= GetMapId() ||
16794 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16795 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16796 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16797 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
))
16799 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16800 data
<< uint32(ERR_TAXITOOFARAWAY
);
16801 GetSession()->SendPacket(&data
);
16805 // node must have pos if taxi master case (npc != NULL)
16808 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16809 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16810 GetSession()->SendPacket(&data
);
16814 // Prepare to flight start now
16816 // stop combat at start taxi flight if any
16819 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16822 // clean not finished taxi path if any
16823 m_taxi
.ClearTaxiDestinations();
16825 // 0 element current node
16826 m_taxi
.AddTaxiDestination(sourcenode
);
16828 // fill destinations path tail
16829 uint32 sourcepath
= 0;
16830 uint32 totalcost
= 0;
16832 uint32 prevnode
= sourcenode
;
16833 uint32 lastnode
= 0;
16835 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16839 lastnode
= nodes
[i
];
16840 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16844 m_taxi
.ClearTaxiDestinations();
16850 if(prevnode
== sourcenode
)
16853 m_taxi
.AddTaxiDestination(lastnode
);
16855 prevnode
= lastnode
;
16858 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16859 uint16 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam(), npc
== NULL
);
16861 // in spell case allow 0 model
16862 if (mount_id
== 0 && spellid
== 0 || sourcepath
== 0)
16864 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16865 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16866 GetSession()->SendPacket(&data
);
16867 m_taxi
.ClearTaxiDestinations();
16871 uint32 money
= GetMoney();
16874 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16876 if(money
< totalcost
)
16878 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16879 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16880 GetSession()->SendPacket(&data
);
16881 m_taxi
.ClearTaxiDestinations();
16885 //Checks and preparations done, DO FLIGHT
16886 ModifyMoney(-(int32
)totalcost
);
16887 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
16888 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN
, 1);
16890 // prevent stealth flight
16891 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16893 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16894 data
<< uint32(ERR_TAXIOK
);
16895 GetSession()->SendPacket(&data
);
16897 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16899 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16904 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id
, uint32 spellid
/*= 0*/ )
16906 TaxiPathEntry
const* entry
= sTaxiPathStore
.LookupEntry(taxi_path_id
);
16910 std::vector
<uint32
> nodes
;
16913 nodes
[0] = entry
->from
;
16914 nodes
[1] = entry
->to
;
16916 return ActivateTaxiPathTo(nodes
,NULL
,spellid
);
16919 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16921 // last check 2.0.10
16922 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16924 data
<< uint8(0x0); // flags (0x1, 0x2)
16925 time_t curTime
= time(NULL
);
16926 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16928 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16930 uint32 unSpellId
= itr
->first
;
16931 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16938 // Not send cooldown for this spells
16939 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16942 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16945 data
<< unTimeMs
; // in m.secs
16946 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
16949 GetSession()->SendPacket(&data
);
16952 void Player::InitDataForForm(bool reapplyMods
)
16954 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16955 if(ssEntry
&& ssEntry
->attackSpeed
)
16957 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16958 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16959 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16962 SetRegularAttackTime();
16968 if(getPowerType()!=POWER_ENERGY
)
16969 setPowerType(POWER_ENERGY
);
16973 case FORM_DIREBEAR
:
16975 if(getPowerType()!=POWER_RAGE
)
16976 setPowerType(POWER_RAGE
);
16979 default: // 0, for example
16981 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16982 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16983 setPowerType(Powers(cEntry
->powerType
));
16988 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16990 UpdateEquipSpellsAtFormChange();
16992 UpdateAttackPowerAndDamage();
16993 UpdateAttackPowerAndDamage(true);
16996 // Return true is the bought item has a max count to force refresh of window by caller
16997 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16999 // cheating attempt
17000 if(count
< 1) count
= 1;
17005 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17008 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17012 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17015 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17016 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17020 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17021 if(!vItems
|| vItems
->Empty())
17023 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17027 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17028 if(vendor_slot
>= vItems
->GetItemCount())
17030 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17034 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17036 // check current item amount if it limited
17037 if( crItem
->maxcount
!= 0 )
17039 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17041 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17046 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17048 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17052 if(crItem
->ExtendedCost
)
17054 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17057 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17061 // honor points price
17062 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17064 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17068 // arena points price
17069 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17071 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17076 for (uint8 i
= 0; i
< 5; ++i
)
17078 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17080 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17085 // check for personal arena rating requirement
17086 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17088 // probably not the proper equip err
17089 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17094 uint32 price
= pProto
->BuyPrice
* count
;
17096 // reputation discount
17097 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17099 if( GetMoney() < price
)
17101 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17105 uint8 bag
= 0; // init for case invalid bagGUID
17107 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17110 if( bagguid
== GetGUID() )
17112 bag
= INVENTORY_SLOT_BAG_0
;
17116 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;++i
)
17118 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17121 if( bagguid
== pBag
->GetGUID() )
17131 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17133 ItemPosCountVec dest
;
17134 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17135 if( msg
!= EQUIP_ERR_OK
)
17137 SendEquipError( msg
, NULL
, NULL
);
17141 ModifyMoney( -(int32
)price
);
17142 if(crItem
->ExtendedCost
) // case for new honor system
17144 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17145 if(iece
->reqhonorpoints
)
17146 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17147 if(iece
->reqarenapoints
)
17148 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17149 for (uint8 i
= 0; i
< 5; ++i
)
17151 if(iece
->reqitem
[i
])
17152 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17156 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17158 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17160 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17161 data
<< pCreature
->GetGUID();
17162 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17163 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17164 data
<< (uint32
)count
;
17165 GetSession()->SendPacket(&data
);
17167 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17170 else if( IsEquipmentPos( bag
, slot
) )
17172 if(pProto
->BuyCount
* count
!= 1)
17174 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17179 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17180 if( msg
!= EQUIP_ERR_OK
)
17182 SendEquipError( msg
, NULL
, NULL
);
17186 ModifyMoney( -(int32
)price
);
17187 if(crItem
->ExtendedCost
) // case for new honor system
17189 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17190 if(iece
->reqhonorpoints
)
17191 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17192 if(iece
->reqarenapoints
)
17193 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17194 for (uint8 i
= 0; i
< 5; ++i
)
17196 if(iece
->reqitem
[i
])
17197 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17201 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17203 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17205 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17206 data
<< pCreature
->GetGUID();
17207 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17208 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17209 data
<< (uint32
)count
;
17210 GetSession()->SendPacket(&data
);
17212 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17214 AutoUnequipOffhandIfNeed();
17219 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17223 return crItem
->maxcount
!=0;
17226 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17228 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17229 // the personal rating of the arena team must match the required limit as well
17230 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17231 uint32 max_personal_rating
= 0;
17232 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17234 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17236 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17237 uint32 t_rating
= at
->GetRating();
17238 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17239 if(max_personal_rating
< p_rating
)
17240 max_personal_rating
= p_rating
;
17243 return max_personal_rating
;
17246 void Player::UpdateHomebindTime(uint32 time
)
17248 // GMs never get homebind timer online
17249 if (m_InstanceValid
|| isGameMaster())
17251 if(m_HomebindTimer
) // instance valid, but timer not reset
17254 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17257 GetSession()->SendPacket(&data
);
17259 // instance is valid, reset homebind timer
17260 m_HomebindTimer
= 0;
17262 else if (m_HomebindTimer
> 0)
17264 if (time
>= m_HomebindTimer
)
17266 // teleport to homebind location
17267 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17270 m_HomebindTimer
-= time
;
17274 // instance is invalid, start homebind timer
17275 m_HomebindTimer
= 60000;
17276 // send message to player
17277 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17278 data
<< m_HomebindTimer
;
17280 GetSession()->SendPacket(&data
);
17281 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17285 void Player::UpdatePvP(bool state
, bool ovrride
)
17287 if(!state
|| ovrride
)
17290 if(Pet
* pet
= GetPet())
17291 pet
->SetPvP(state
);
17292 if(Unit
* charmed
= GetCharm())
17293 charmed
->SetPvP(state
);
17295 pvpInfo
.endTimer
= 0;
17299 if(pvpInfo
.endTimer
!= 0)
17300 pvpInfo
.endTimer
= time(NULL
);
17305 if(Pet
* pet
= GetPet())
17306 pet
->SetPvP(state
);
17307 if(Unit
* charmed
= GetCharm())
17308 charmed
->SetPvP(state
);
17313 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17315 // init cooldown values
17320 // some special item spells without correct cooldown in SpellInfo
17321 // cooldown information stored in item prototype
17322 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17326 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17328 for(int idx
= 0; idx
< 5; ++idx
)
17330 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17332 cat
= proto
->Spells
[idx
].SpellCategory
;
17333 rec
= proto
->Spells
[idx
].SpellCooldown
;
17334 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17341 // if no cooldown found above then base at DBC data
17342 if(rec
< 0 && catrec
< 0)
17344 cat
= spellInfo
->Category
;
17345 rec
= spellInfo
->RecoveryTime
;
17346 catrec
= spellInfo
->CategoryRecoveryTime
;
17349 time_t curTime
= time(NULL
);
17354 // overwrite time for selected category
17355 if(infinityCooldown
)
17357 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17358 // but not allow ignore until reset or re-login
17359 catrecTime
= catrec
> 0 ? curTime
+MONTH
: 0;
17360 recTime
= rec
> 0 ? curTime
+MONTH
: catrecTime
;
17364 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17365 // prevent 0 cooldowns set by another way
17366 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17367 rec
= GetAttackTime(RANGED_ATTACK
);
17369 // Now we have cooldown data (if found any), time to apply mods
17371 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17374 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17376 // replace negative cooldowns by 0
17377 if (rec
< 0) rec
= 0;
17378 if (catrec
< 0) catrec
= 0;
17380 // no cooldown after applying spell mods
17381 if( rec
== 0 && catrec
== 0)
17384 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17385 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17388 // self spell cooldown
17390 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17393 if (cat
&& catrec
> 0)
17395 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17396 if(i_scstore
!= sSpellCategoryStore
.end())
17398 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17400 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17403 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17409 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17413 sc
.itemid
= itemid
;
17414 m_spellCooldowns
[spellid
] = sc
;
17417 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17419 // start cooldowns at server side, if any
17420 AddSpellAndCategoryCooldowns(spellInfo
,itemId
,spell
);
17422 // Send activate cooldown timer (possible 0) at client side
17423 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17424 data
<< spellInfo
->Id
;
17426 SendDirectMessage(&data
);
17429 void Player::UpdatePotionCooldown(Spell
* spell
)
17431 // no potion used i combat or still in combat
17432 if(!m_lastPotionId
|| isInCombat())
17435 // Call not from spell cast, send cooldown event for item spells if no in combat
17438 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17439 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17440 for(int idx
= 0; idx
< 5; ++idx
)
17441 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17442 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17443 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17445 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17447 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17449 m_lastPotionId
= 0;
17452 //slot to be excluded while counting
17453 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17455 if(!enchantmentcondition
)
17458 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17463 uint8 curcount
[4] = {0, 0, 0, 0};
17465 //counting current equipped gem colors
17466 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17470 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17471 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17473 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17475 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17479 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17483 uint32 gemid
= enchantEntry
->GemID
;
17487 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17491 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17495 uint8 GemColor
= gemProperty
->color
;
17497 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17499 if(tmpcolormask
& GemColor
)
17506 bool activate
= true;
17508 for(int i
= 0; i
< 5; ++i
)
17510 if(!Condition
->Color
[i
])
17513 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17515 // if have <CompareColor> use them as count, else use <value> from Condition
17516 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17518 switch(Condition
->Comparator
[i
])
17520 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17521 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17523 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17524 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17526 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17527 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17532 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");
17537 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17539 //cycle all equipped items
17540 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17542 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17543 if(slot
== exceptslot
)
17546 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17548 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17551 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17553 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17557 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17561 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17564 //was enchant active with/without item?
17565 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17566 //should it now be?
17567 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17569 // ignore item gem conditions
17570 //if state changed, (dis)apply enchant
17571 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17578 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17579 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17581 //cycle all equipped items
17582 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17584 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17585 if(slot
== exceptslot
)
17588 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17590 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17593 //cycle all (gem)enchants
17594 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17596 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17597 if(!enchant_id
) //if no enchant go to next enchant(slot)
17600 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17604 //only metagems to be (de)activated, so only enchants with condition
17605 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17607 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17612 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17614 if(BattleGround
*bg
= GetBattleGround())
17616 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17618 // call after remove to be sure that player resurrected for correct cast
17619 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
) )
17621 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
17622 CastSpell(this, 26013, true); // Deserter
17627 bool Player::CanJoinToBattleground() const
17629 // check Deserter debuff
17630 if(GetDummyAura(26013))
17636 bool Player::CanReportAfkDueToLimit()
17638 // a player can complain about 15 people per 5 minutes
17639 if(m_bgAfkReportedCount
>= 15)
17641 ++m_bgAfkReportedCount
;
17645 ///This player has been blamed to be inactive in a battleground
17646 void Player::ReportedAfkBy(Player
* reporter
)
17648 BattleGround
*bg
= GetBattleGround();
17649 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17652 // check if player has 'Idle' or 'Inactive' debuff
17653 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17655 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17656 // 3 players have to complain to apply debuff
17657 if(m_bgAfkReporter
.size() >= 3)
17659 // cast 'Idle' spell
17660 CastSpell(this, 43680, true);
17661 m_bgAfkReporter
.clear();
17666 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17668 // gamemaster in GM mode see all, including ghosts
17669 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17672 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17673 if (InBattleGround())
17675 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17680 // Live player see live player or dead player with not realized corpse
17681 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17683 return isAlive() || m_deathTimer
> 0;
17686 // Ghost see other friendly ghosts, that's for sure
17687 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17690 // Dead player see live players near own corpse
17693 Corpse
*corpse
= pl
->GetCorpse();
17696 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17697 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17702 // and not see any other
17706 bool Player::IsVisibleGloballyFor( Player
* u
) const
17711 // Always can see self
17715 // Visible units, always are visible for all players
17716 if (GetVisibility() == VISIBILITY_ON
)
17719 // GMs are visible for higher gms (or players are visible for gms)
17720 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17721 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17723 // non faction visibility non-breakable for non-GMs
17724 if (GetVisibility() == VISIBILITY_OFF
)
17727 // non-gm stealth/invisibility not hide from global player lists
17731 void Player::UpdateVisibilityOf(WorldObject
* target
)
17733 if(HaveAtClient(target
))
17735 if(!target
->isVisibleForInState(this,true))
17737 target
->DestroyForPlayer(this);
17738 m_clientGUIDs
.erase(target
->GetGUID());
17740 #ifdef MANGOS_DEBUG
17741 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17742 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17748 if(target
->isVisibleForInState(this,false))
17750 target
->SendUpdateToPlayer(this);
17751 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17752 m_clientGUIDs
.insert(target
->GetGUID());
17754 #ifdef MANGOS_DEBUG
17755 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17756 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17759 // target aura duration for caster show only if target exist at caster client
17760 // send data at target visibility change (adding to client)
17761 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17762 SendAurasForTarget((Unit
*)target
);
17764 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17765 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17771 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17773 s64
.insert(target
->GetGUID());
17777 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17779 if(!target
->IsTransport())
17780 s64
.insert(target
->GetGUID());
17784 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17786 if(HaveAtClient(target
))
17788 if(!target
->isVisibleForInState(this,true))
17790 target
->BuildOutOfRangeUpdateBlock(&data
);
17791 m_clientGUIDs
.erase(target
->GetGUID());
17793 #ifdef MANGOS_DEBUG
17794 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17795 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
));
17801 if(target
->isVisibleForInState(this,false))
17803 visibleNow
.insert(target
);
17804 target
->BuildUpdate(data_updates
);
17805 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17806 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17808 #ifdef MANGOS_DEBUG
17809 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17810 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
));
17816 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17817 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17818 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17819 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17820 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17822 void Player::InitPrimaryProffesions()
17824 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17827 void Player::SendComboPoints()
17829 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17832 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17833 data
.append(combotarget
->GetPackGUID());
17834 data
<< uint8(m_comboPoints
);
17835 GetSession()->SendPacket(&data
);
17839 void Player::AddComboPoints(Unit
* target
, int8 count
)
17844 // without combo points lost (duration checked in aura)
17845 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17847 if(target
->GetGUID() == m_comboTarget
)
17849 m_comboPoints
+= count
;
17854 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17855 target2
->RemoveComboPointHolder(GetGUIDLow());
17857 m_comboTarget
= target
->GetGUID();
17858 m_comboPoints
= count
;
17860 target
->AddComboPointHolder(GetGUIDLow());
17863 if (m_comboPoints
> 5) m_comboPoints
= 5;
17864 if (m_comboPoints
< 0) m_comboPoints
= 0;
17869 void Player::ClearComboPoints()
17874 // without combopoints lost (duration checked in aura)
17875 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17881 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17882 target
->RemoveComboPointHolder(GetGUIDLow());
17887 void Player::SetGroup(Group
*group
, int8 subgroup
)
17893 // never use SetGroup without a subgroup unless you specify NULL for group
17894 assert(subgroup
>= 0);
17895 m_group
.link(group
, this);
17896 m_group
.setSubGroup((uint8
)subgroup
);
17900 void Player::SendInitialPacketsBeforeAddToMap()
17902 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17903 data
<< uint32(0); // unknown, may be rest state time or experience
17904 GetSession()->SendPacket(&data
);
17907 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17908 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17909 data
<< (uint32
) m_homebindMapId
;
17910 data
<< (uint32
) m_homebindZoneId
;
17911 GetSession()->SendPacket(&data
);
17913 // SMSG_SET_PROFICIENCY
17914 // SMSG_UPDATE_AURA_DURATION
17917 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17918 for (int i
= 0; i
< 8; ++i
)
17919 data
<< uint32( GetTutorialInt(i
) );
17920 GetSession()->SendPacket(&data
);
17922 SendInitialSpells();
17924 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17925 data
<< uint32(0); // count, for(count) uint32;
17926 GetSession()->SendPacket(&data
);
17928 SendInitialActionButtons();
17929 m_reputationMgr
.SendInitialReputations();
17930 m_achievementMgr
.SendAllAchievementData();
17933 uint32 newzone
, newarea
;
17934 GetZoneAndAreaId(newzone
,newarea
);
17935 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
17937 // SMSG_SET_AURA_SINGLE
17939 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17940 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17941 data
<< (float)0.01666667f
; // game speed
17942 GetSession()->SendPacket( &data
);
17944 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17945 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17946 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17951 void Player::SendInitialPacketsAfterAddToMap()
17953 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17954 data
<< uint32(0x00000000); // on blizz it increments periodically
17955 GetSession()->SendPacket(&data
);
17957 CastSpell(this, 836, true); // LOGINEFFECT
17959 // set some aura effects that send packet to player client after add player to map
17960 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17961 // same auras state lost at far teleport, send it one more time in this case also
17962 static const AuraType auratypes
[] =
17964 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17965 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17966 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17968 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17970 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17971 if(!auraList
.empty())
17972 auraList
.front()->ApplyModifier(true,true);
17975 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17976 SetMovement(MOVE_ROOT
);
17978 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17979 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17981 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
17982 data2
.append(GetPackGUID());
17983 data2
<< (uint32
)2;
17984 SendMessageToSet(&data2
,true);
17987 SendAurasForTarget(this);
17988 SendEnchantmentDurations(); // must be after add to map
17989 SendItemDurations(); // must be after add to map
17992 void Player::SendUpdateToOutOfRangeGroupMembers()
17994 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17996 if(Group
* group
= GetGroup())
17997 group
->UpdatePlayerOutOfRange(this);
17999 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18000 m_auraUpdateMask
= 0;
18001 if(Pet
*pet
= GetPet())
18002 pet
->ResetAuraUpdateMask();
18005 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18007 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18008 data
<< uint32(mapid
);
18009 data
<< uint8(reason
); // transfer abort reason
18012 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18013 case TRANSFER_ABORT_DIFFICULTY
:
18014 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18015 data
<< uint8(arg
);
18018 GetSession()->SendPacket(&data
);
18021 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
18023 // type of warning, based on the time remaining until reset
18026 type
= RAID_INSTANCE_WELCOME
;
18027 else if(time
> 900 && time
<= 3600)
18028 type
= RAID_INSTANCE_WARNING_HOURS
;
18029 else if(time
> 300 && time
<= 900)
18030 type
= RAID_INSTANCE_WARNING_MIN
;
18032 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18033 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
18034 data
<< uint32(type
);
18035 data
<< uint32(mapid
);
18036 data
<< uint32(time
);
18037 GetSession()->SendPacket(&data
);
18040 void Player::ApplyEquipCooldown( Item
* pItem
)
18042 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
18044 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18047 if( !spellData
.SpellId
)
18050 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18051 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18054 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18056 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18057 data
<< pItem
->GetGUID();
18058 data
<< uint32(spellData
.SpellId
);
18059 GetSession()->SendPacket(&data
);
18063 void Player::resetSpells()
18065 // not need after this call
18066 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18068 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
18069 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18072 // make full copy of map (spells removed and marked as deleted at another spell remove
18073 // and we can't use original map for safe iterative with visit each spell at loop end
18074 PlayerSpellMap smap
= GetSpellMap();
18076 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18077 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18079 learnDefaultSpells();
18080 learnQuestRewardedSpells();
18083 void Player::learnDefaultSpells()
18085 // learn default race/class spells
18086 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18087 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18089 uint32 tspell
= *itr
;
18090 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18091 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18092 addSpell(tspell
,true,true,true,false);
18093 else // but send in normal spell in game learn case
18094 learnSpell(tspell
,true);
18098 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18100 uint32 spell_id
= quest
->GetRewSpellCast();
18102 // skip quests without rewarded spell
18106 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18110 // check learned spells state
18111 bool found
= false;
18112 for(int i
=0; i
< 3; ++i
)
18114 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18121 // skip quests with not teaching spell or already known spell
18125 // prevent learn non first rank unknown profession and second specialization for same profession)
18126 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18127 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18129 // not have first rank learned (unlearned prof?)
18130 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18131 if( !HasSpell(first_spell
) )
18134 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18139 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18141 // search other specialization for same prof
18142 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18144 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18147 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18151 // compare only specializations
18152 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18155 // compare same chain spells
18156 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18159 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18160 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18166 CastSpell( this, spell_id
, true);
18169 void Player::learnQuestRewardedSpells()
18171 // learn spells received from quest completing
18172 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18174 // skip no rewarded quests
18175 if(!itr
->second
.m_rewarded
)
18178 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18182 learnQuestRewardedSpells(quest
);
18186 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18188 uint32 raceMask
= getRaceMask();
18189 uint32 classMask
= getClassMask();
18190 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18192 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18193 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18195 // Check race if set
18196 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18198 // Check class if set
18199 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18202 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18204 // need unlearn spell
18205 if (skill_value
< pAbility
->req_skill_value
)
18206 removeSpell(pAbility
->spellId
);
18208 else if (!IsInWorld())
18209 addSpell(pAbility
->spellId
,true,true,true,false);
18211 learnSpell(pAbility
->spellId
,true);
18216 void Player::SendAurasForTarget(Unit
*target
)
18218 if(target
->GetVisibleAuras()->empty()) // speedup things
18221 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18222 data
.append(target
->GetPackGUID());
18224 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18225 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18227 for(uint32 j
= 0; j
< 3; ++j
)
18229 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18231 data
<< uint8(aura
->GetAuraSlot());
18232 data
<< uint32(aura
->GetId());
18236 uint8 auraFlags
= aura
->GetAuraFlags();
18238 data
<< uint8(auraFlags
);
18240 data
<< uint8(aura
->GetAuraLevel());
18242 data
<< uint8(aura
->GetAuraCharges());
18244 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18246 data
<< uint8(0); // packed GUID of someone (caster?)
18249 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18251 data
<< uint32(aura
->GetAuraMaxDuration());
18252 data
<< uint32(aura
->GetAuraDuration());
18260 GetSession()->SendPacket(&data
);
18263 void Player::SetDailyQuestStatus( uint32 quest_id
)
18265 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18267 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18269 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18270 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18271 m_DailyQuestChanged
= true;
18277 void Player::ResetDailyQuestStatus()
18279 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18280 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18282 // DB data deleted in caller
18283 m_DailyQuestChanged
= false;
18284 m_lastDailyQuestTime
= 0;
18287 BattleGround
* Player::GetBattleGround() const
18289 if(GetBattleGroundId()==0)
18292 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgTypeID
);
18295 bool Player::InArena() const
18297 BattleGround
*bg
= GetBattleGround();
18298 if(!bg
|| !bg
->isArena())
18304 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18306 // get a template bg instead of running one
18307 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18311 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18317 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18319 //returned to hardcoded version of this function, because there is no way to code it dynamic
18320 uint32 level
= getLevel();
18321 if( bgTypeId
== BATTLEGROUND_AV
)
18324 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18325 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18327 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18328 return QUEUE_ID_MAX_LEVEL_80
;
18330 return BGQueueIdBasedOnLevel(queue_id
);
18333 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18335 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18336 if(!vendor_faction
|| !vendor_faction
->faction
)
18339 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18340 if(rank
<= REP_NEUTRAL
)
18343 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18346 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18348 uint32 racemask
= getRaceMask();
18349 uint32 classmask
= getClassMask();
18351 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18352 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18356 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18358 // skip wrong race skills
18359 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18362 // skip wrong class skills
18363 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18372 bool Player::HasQuestForGO(int32 GOId
) const
18374 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18376 uint32 questid
= GetQuestSlotQuestId(i
);
18377 if ( questid
== 0 )
18380 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18381 if(qs_itr
== mQuestStatus
.end())
18384 QuestStatusData
const& qs
= qs_itr
->second
;
18386 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18388 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18392 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18395 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
18397 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18400 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18408 void Player::UpdateForQuestWorldObjects()
18410 if(m_clientGUIDs
.empty())
18414 WorldPacket packet
;
18415 for(ClientGUIDs::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18417 if(IS_GAMEOBJECT_GUID(*itr
))
18419 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18421 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18423 else if(IS_CREATURE_GUID(*itr
) || IS_VEHICLE_GUID(*itr
))
18425 Creature
*obj
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr
);
18428 // check if this unit requires quest specific flags
18430 SpellClickInfoMap
const& map
= objmgr
.mSpellClickInfoMap
;
18431 for(SpellClickInfoMap::const_iterator itr
= map
.lower_bound(obj
->GetEntry()); itr
!= map
.upper_bound(obj
->GetEntry()); ++itr
)
18433 if(itr
->second
.questId
!= 0)
18435 obj
->BuildCreateUpdateBlockForPlayer(&udata
,this);
18442 udata
.BuildPacket(&packet
);
18443 GetSession()->SendPacket(&packet
);
18446 void Player::SummonIfPossible(bool agree
)
18450 m_summon_expire
= 0;
18454 // expire and auto declined
18455 if(m_summon_expire
< time(NULL
))
18458 // stop taxi flight at summon
18461 GetMotionMaster()->MovementExpired();
18462 m_taxi
.ClearTaxiDestinations();
18465 // drop flag at summon
18466 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18467 if(BattleGround
*bg
= GetBattleGround())
18468 bg
->EventPlayerDroppedFlag(this);
18470 m_summon_expire
= 0;
18472 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS
, 1);
18474 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18477 void Player::RemoveItemDurations( Item
*item
)
18479 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18483 m_itemDuration
.erase(itr
);
18489 void Player::AddItemDurations( Item
*item
)
18491 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18493 m_itemDuration
.push_back(item
);
18494 item
->SendTimeUpdate(this);
18498 void Player::AutoUnequipOffhandIfNeed()
18500 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18504 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18505 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18508 ItemPosCountVec off_dest
;
18509 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18510 if( off_msg
== EQUIP_ERR_OK
)
18512 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18513 StoreItem( off_dest
, offItem
, true );
18518 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18519 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18520 CharacterDatabase
.BeginTransaction();
18521 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18522 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18523 CharacterDatabase
.CommitTransaction();
18525 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18526 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18530 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18532 if(spellInfo
->EquippedItemClass
< 0)
18535 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18536 // for optimize check 2 used cases only
18537 switch(spellInfo
->EquippedItemClass
)
18539 case ITEM_CLASS_WEAPON
:
18541 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18542 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18543 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18547 case ITEM_CLASS_ARMOR
:
18549 // tabard not have dependent spells
18550 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18551 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18552 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18555 // shields can be equipped to offhand slot
18556 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18557 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18560 // ranged slot can have some armor subclasses
18561 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18562 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18568 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18575 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18577 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18578 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18579 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18582 // Check no reagent use mask
18583 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18584 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18585 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18586 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18592 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18594 AuraMap
& auras
= GetAuras();
18595 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18597 Aura
* aura
= itr
->second
;
18599 // skip passive (passive item dependent spells work in another way) and not self applied auras
18600 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18601 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18607 // skip if not item dependent or have alternative item
18608 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18614 // no alt item, remove aura, restart check
18615 RemoveAurasDueToSpell(aura
->GetId());
18616 itr
= auras
.begin();
18619 // currently casted spells can be dependent from item
18620 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
18622 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18623 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18628 uint32
Player::GetResurrectionSpellId()
18630 // search priceless resurrection possibilities
18632 uint32 spell_id
= 0;
18633 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18634 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18636 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18637 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18639 switch((*itr
)->GetId())
18641 case 20707: spell_id
= 3026; break; // rank 1
18642 case 20762: spell_id
= 20758; break; // rank 2
18643 case 20763: spell_id
= 20759; break; // rank 3
18644 case 20764: spell_id
= 20760; break; // rank 4
18645 case 20765: spell_id
= 20761; break; // rank 5
18646 case 27239: spell_id
= 27240; break; // rank 6
18647 case 47883: spell_id
= 47882; break; // rank 7
18649 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
18655 // Twisting Nether // prio: 2 (max)
18656 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18663 // Reincarnation (passive spell) // prio: 1
18664 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18670 // Used in triggers for check "Only to targets that grant experience or honor" req
18671 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18673 uint32 v_level
= pVictim
->getLevel();
18674 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18676 // Victim level less gray level
18677 if(v_level
<=k_grey
)
18680 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18682 if (((Creature
*)pVictim
)->isTotem() ||
18683 ((Creature
*)pVictim
)->isPet() ||
18684 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18690 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18692 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18694 // prepare data for near group iteration (PvP and !PvP cases)
18696 bool honored_kill
= false;
18698 if(Group
*pGroup
= GetGroup())
18701 uint32 sum_level
= 0;
18702 Player
* member_with_max_level
= NULL
;
18703 Player
* not_gray_member_with_max_level
= NULL
;
18705 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18707 if(member_with_max_level
)
18709 /// not get Xp in PvP or no not gray players in group
18710 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18712 /// skip in check PvP case (for speed, not used)
18713 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18714 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18715 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18717 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18719 Player
* pGroupGuy
= itr
->getSource();
18723 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18724 continue; // member (alive or dead) or his corpse at req. distance
18726 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18727 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18728 honored_kill
= true;
18730 // xp and reputation only in !PvP case
18733 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18735 // if is in dungeon then all receive full reputation at kill
18736 // rewarded any alive/dead/near_corpse group member
18737 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18739 // XP updated only for alive group member
18740 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18741 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18743 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18745 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18746 if(Pet
* pet
= pGroupGuy
->GetPet())
18747 pet
->GivePetXP(itr_xp
/2);
18750 // quest objectives updated only for alive group member or dead but with not released body
18751 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18753 // normal creature (not pet/etc) can be only in !PvP case
18754 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18755 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18761 else // if (!pGroup)
18763 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18765 // honor can be in PvP and !PvP (racial leader) cases
18766 if(RewardHonor(pVictim
,1))
18767 honored_kill
= true;
18769 // xp and reputation only in !PvP case
18772 RewardReputation(pVictim
,1);
18773 GiveXP(xp
, pVictim
);
18775 if(Pet
* pet
= GetPet())
18776 pet
->GivePetXP(xp
);
18778 // normal creature (not pet/etc) can be only in !PvP case
18779 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18780 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18783 return xp
|| honored_kill
;
18786 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
18788 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
18790 // prepare data for near group iteration
18791 if(Group
*pGroup
= GetGroup())
18793 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18795 Player
* pGroupGuy
= itr
->getSource();
18799 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
18800 continue; // member (alive or dead) or his corpse at req. distance
18802 // quest objectives updated only for alive group member or dead but with not released body
18803 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18804 pGroupGuy
->KilledMonster(creature_id
, creature_guid
);
18807 else // if (!pGroup)
18808 KilledMonster(creature_id
, creature_guid
);
18811 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18813 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
)))
18819 Corpse
* corpse
= GetCorpse();
18823 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
));
18826 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18828 Item
* item
= GetWeaponForAttack(attType
,true);
18830 // unarmed only with base attack
18831 if(attType
!= BASE_ATTACK
&& !item
)
18834 // weapon skill or (unarmed for base attack)
18835 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
18836 return GetBaseSkillValue(skill
);
18839 void Player::ResurectUsingRequestData()
18841 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18842 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18844 ResurrectPlayer(0.0f
,false);
18846 if(GetMaxHealth() > m_resurrectHealth
)
18847 SetHealth( m_resurrectHealth
);
18849 SetHealth( GetMaxHealth() );
18851 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18852 SetPower(POWER_MANA
, m_resurrectMana
);
18854 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18856 SetPower(POWER_RAGE
, 0 );
18858 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18860 SpawnCorpseBones();
18863 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18865 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18866 data
.append(target
->GetPackGUID());
18867 data
<< uint8(allowMove
);
18868 GetSession()->SendPacket(&data
);
18871 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18873 // remove new continent flight forms
18874 if( !IsAllowUseFlyMountsHere() )
18876 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18877 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18880 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18881 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
18882 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18883 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
18884 if( !HasAura(itr
->second
->spellId
,0) )
18885 CastSpell(this,itr
->second
->spellId
,true);
18888 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18890 // remove auras from spells with area limitations
18891 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18893 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18894 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
18900 // some auras applied at subzone enter
18901 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
18902 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18903 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
18904 if( !HasAura(itr
->second
->spellId
,0) )
18905 CastSpell(this,itr
->second
->spellId
,true);
18908 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18910 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18911 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18913 return copseReclaimDelay
[0];
18916 time_t now
= time(NULL
);
18917 // 0..2 full period
18918 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18919 return copseReclaimDelay
[count
];
18922 void Player::UpdateCorpseReclaimDelay()
18924 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18926 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18927 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18930 time_t now
= time(NULL
);
18931 if(now
< m_deathExpireTime
)
18933 // full and partly periods 1..3
18934 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18935 if(count
< MAX_DEATH_COUNT
)
18936 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18938 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18941 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18944 void Player::SendCorpseReclaimDelay(bool load
)
18946 Corpse
* corpse
= GetCorpse();
18953 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18956 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18959 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18960 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18962 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18963 if(count
>=MAX_DEATH_COUNT
)
18964 count
= MAX_DEATH_COUNT
-1;
18969 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18971 time_t now
= time(NULL
);
18972 if(now
>= expected_time
)
18975 delay
= expected_time
-now
;
18978 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18980 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18981 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18982 data
<< uint32(delay
*IN_MILISECONDS
);
18983 GetSession()->SendPacket( &data
);
18986 Player
* Player::GetNextRandomRaidMember(float radius
)
18988 Group
*pGroup
= GetGroup();
18992 std::vector
<Player
*> nearMembers
;
18993 nearMembers
.reserve(pGroup
->GetMembersCount());
18995 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18997 Player
* Target
= itr
->getSource();
18999 // IsHostileTo check duel and controlled by enemy
19000 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19001 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19002 nearMembers
.push_back(Target
);
19005 if (nearMembers
.empty())
19008 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19009 return nearMembers
[randTarget
];
19012 PartyResult
Player::CanUninviteFromGroup() const
19014 const Group
* grp
= GetGroup();
19016 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19018 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19019 return PARTY_RESULT_YOU_NOT_LEADER
;
19021 if(InBattleGround())
19022 return PARTY_RESULT_INVITE_RESTRICTED
;
19024 return PARTY_RESULT_OK
;
19027 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
19029 //we must move references from m_group to m_originalGroup
19030 SetOriginalGroup(GetGroup(), GetSubGroup());
19033 m_group
.link(group
, this);
19034 m_group
.setSubGroup((uint8
)subgroup
);
19037 void Player::RemoveFromBattleGroundRaid()
19039 //remove existing reference
19041 if( Group
* group
= GetOriginalGroup() )
19043 m_group
.link(group
, this);
19044 m_group
.setSubGroup(GetOriginalSubGroup());
19046 SetOriginalGroup(NULL
);
19049 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
19051 if( group
== NULL
)
19052 m_originalGroup
.unlink();
19055 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19056 assert(subgroup
>= 0);
19057 m_originalGroup
.link(group
, this);
19058 m_originalGroup
.setSubGroup((uint8
)subgroup
);
19062 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19064 LiquidData liquid_status
;
19065 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
19068 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
19069 // Small hack for enable breath in WMO
19071 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
19075 // All liquids type - check under water position
19076 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
19078 if ( res
& LIQUID_MAP_UNDER_WATER
)
19079 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
19081 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
19084 // Allow travel in dark water on taxi or transport
19085 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
19086 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
19088 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
19090 // in lava check, anywhere in lava level
19091 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
19093 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19094 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
19096 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
19098 // in slime check, anywhere in slime level
19099 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
19101 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19102 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
19104 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
19108 void Player::SetCanParry( bool value
)
19110 if(m_canParry
==value
)
19113 m_canParry
= value
;
19114 UpdateParryPercentage();
19117 void Player::SetCanBlock( bool value
)
19119 if(m_canBlock
==value
)
19122 m_canBlock
= value
;
19123 UpdateBlockPercentage();
19126 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19128 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19129 if(itr
->pos
== pos
)
19135 bool Player::CanUseBattleGroundObject()
19137 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19138 // maybe gameobject code should handle that ForceReaction usage
19139 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19140 return ( //InBattleGround() && // in battleground - not need, check in other cases
19141 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19142 //player cannot use object when he is invulnerable (immune)
19143 !isTotalImmune() && // not totally immune
19144 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19145 !HasStealthAura() && // not stealthed
19146 !HasInvisibilityAura() && // not invisible
19147 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19148 isAlive() // live player
19152 bool Player::CanCaptureTowerPoint()
19154 return ( !HasStealthAura() && // not stealthed
19155 !HasInvisibilityAura() && // not invisible
19156 isAlive() // live player
19160 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19162 uint32 level
= getLevel();
19164 if(level
> GT_MAX_LEVEL
)
19165 level
= GT_MAX_LEVEL
; // max level in this dbc
19167 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19168 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19169 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19171 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19174 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19176 if(!bsc
) // shouldn't happen
19181 if(hairstyle
!= newhairstyle
)
19182 cost
+= bsc
->cost
; // full price
19184 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19185 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19187 if(facialhair
!= newfacialhair
)
19188 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19190 return uint32(cost
);
19193 void Player::InitGlyphsForLevel()
19195 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19196 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19198 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19200 uint32 level
= getLevel();
19203 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19205 value
|= (0x01 | 0x02);
19215 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19218 void Player::EnterVehicle(Vehicle
*vehicle
)
19220 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19224 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19228 vehicle
->SetCharmerGUID(GetGUID());
19229 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19230 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19231 vehicle
->setFaction(getFaction());
19233 SetCharm(vehicle
); // charm
19234 SetFarSightGUID(vehicle
->GetGUID()); // set view
19236 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19238 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19239 GetSession()->SendPacket(&data
);
19241 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19242 data
.append(GetPackGUID());
19243 data
<< uint32(0); // counter?
19244 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19245 data
<< uint16(0); // special flags
19246 data
<< uint32(getMSTime()); // time
19247 data
<< vehicle
->GetPositionX(); // x
19248 data
<< vehicle
->GetPositionY(); // y
19249 data
<< vehicle
->GetPositionZ(); // z
19250 data
<< vehicle
->GetOrientation(); // o
19251 // transport part, TODO: load/calculate seat offsets
19252 data
<< uint64(vehicle
->GetGUID()); // transport guid
19253 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19254 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19255 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19256 data
<< float(0); // transport orientation
19257 data
<< uint32(getMSTime()); // transport time
19258 data
<< uint8(0); // seat
19259 // end of transport part
19260 data
<< uint32(0); // fall time
19261 GetSession()->SendPacket(&data
);
19263 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19264 data
<< uint64(vehicle
->GetGUID());
19265 data
<< uint32(0x00000000);
19266 data
<< uint32(0x00000000);
19267 data
<< uint32(0x00000101);
19269 for(uint32 i
= 0; i
< 10; ++i
)
19270 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19274 GetSession()->SendPacket(&data
);
19277 void Player::ExitVehicle(Vehicle
*vehicle
)
19279 vehicle
->SetCharmerGUID(0);
19280 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19281 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19282 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19285 SetFarSightGUID(0);
19287 SetClientControl(vehicle
, 0);
19289 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19290 data
.append(GetPackGUID());
19291 data
<< uint32(0); // counter?
19292 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19293 data
<< uint16(0x40); // special flags
19294 data
<< uint32(getMSTime()); // time
19295 data
<< vehicle
->GetPositionX(); // x
19296 data
<< vehicle
->GetPositionY(); // y
19297 data
<< vehicle
->GetPositionZ(); // z
19298 data
<< vehicle
->GetOrientation(); // o
19299 data
<< uint32(0); // fall time
19300 GetSession()->SendPacket(&data
);
19302 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19305 GetSession()->SendPacket(&data
);
19307 // maybe called at dummy aura remove?
19308 // CastSpell(this, 45472, true); // Parachute
19311 bool Player::isTotalImmune()
19313 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
19315 uint32 immuneMask
= 0;
19316 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
19318 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
19319 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
19325 bool Player::HasTitle(uint32 bitIndex
)
19327 if (bitIndex
> 128)
19330 uint32 fieldIndexOffset
= bitIndex
/32;
19331 uint32 flag
= 1 << (bitIndex
%32);
19332 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19335 void Player::SetTitle(CharTitlesEntry
const* title
)
19337 uint32 fieldIndexOffset
= title
->bit_index
/32;
19338 uint32 flag
= 1 << (title
->bit_index
%32);
19339 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19342 void Player::ConvertRune(uint8 index
, uint8 newType
)
19344 SetCurrentRune(index
, newType
);
19346 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19347 data
<< uint8(index
);
19348 data
<< uint8(newType
);
19349 GetSession()->SendPacket(&data
);
19352 void Player::ResyncRunes(uint8 count
)
19354 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19355 for(uint32 i
= 0; i
< count
; ++i
)
19357 data
<< uint8(GetCurrentRune(i
)); // rune type
19358 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19360 GetSession()->SendPacket(&data
);
19363 void Player::AddRunePower(uint8 index
)
19365 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19366 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19367 GetSession()->SendPacket(&data
);
19370 void Player::InitRunes()
19372 if(getClass() != CLASS_DEATH_KNIGHT
)
19375 m_runes
= new Runes
;
19377 m_runes
->runeState
= 0;
19379 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19381 SetBaseRune(i
, i
/ 2); // init base types
19382 SetCurrentRune(i
, i
/ 2); // init current types
19383 SetRuneCooldown(i
, 0); // reset cooldowns
19384 m_runes
->SetRuneState(i
);
19387 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19388 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19391 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19394 loot
.FillLoot (loot_id
,store
,this,true);
19396 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19397 for(uint32 i
= 0; i
< max_slot
; ++i
)
19399 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19401 ItemPosCountVec dest
;
19402 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19403 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19404 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19405 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19406 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19407 if(msg
!= EQUIP_ERR_OK
)
19409 SendEquipError( msg
, NULL
, NULL
);
19413 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19414 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19418 uint32
Player::CalculateTalentsPoints() const
19420 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19422 if(getClass() != CLASS_DEATH_KNIGHT
)
19423 return base_talent
;
19425 uint32 talentPointsForLevel
=
19426 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19427 + m_questRewardTalentCount
;
19429 if(talentPointsForLevel
> base_talent
)
19430 talentPointsForLevel
= base_talent
;
19432 return talentPointsForLevel
;
19435 bool Player::IsAllowUseFlyMountsHere() const
19437 if (isGameMaster())
19440 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19441 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19444 void Player::learnSpellHighRank(uint32 spellid
)
19446 learnSpell(spellid
,false);
19448 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19449 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19450 learnSpellHighRank(itr
->second
);
19453 void Player::_LoadSkills()
19455 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19457 // reset skill modifiers and set correct unlearn flags
19458 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
19460 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19462 // set correct unlearn bit
19463 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19466 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19467 if(!pSkill
) continue;
19469 // enable unlearn button for primary professions only
19470 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19471 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19473 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19475 // set fixed skill ranges
19476 switch(GetSkillRangeType(pSkill
,false))
19478 case SKILL_RANGE_LANGUAGE
: // 300..300
19479 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(300,300));
19481 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
19482 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(1,1));
19488 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19489 learnSkillRewardedSpells(id
, vskill
);
19492 // special settings
19493 if(getClass()==CLASS_DEATH_KNIGHT
)
19495 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19498 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19500 base_skill
= 1; // skill mast be known and then > 0 in any case
19502 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19503 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19504 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19505 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19506 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19507 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19508 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19509 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19510 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19511 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19512 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19513 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19514 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19515 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19516 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19517 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19521 uint32
Player::GetPhaseMaskForSpawn() const
19523 uint32 phase
= PHASEMASK_NORMAL
;
19524 if(!isGameMaster())
19525 phase
= GetPhaseMask();
19528 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19529 if(!phases
.empty())
19530 phase
= phases
.front()->GetMiscValue();
19533 // some aura phases include 1 normal map in addition to phase itself
19534 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19537 return PHASEMASK_NORMAL
;
19540 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19542 ItemPrototype
const* pProto
= pItem
->GetProto();
19544 // proto based limitations
19545 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19548 // check unique-equipped on gems
19549 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19551 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19554 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19558 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19562 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19563 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19564 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19566 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19570 return EQUIP_ERR_OK
;
19573 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19575 // check unique-equipped on item
19576 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19578 // there is an equip limit on this item
19579 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19580 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19583 // check unique-equipped limit
19584 if (itemProto
->ItemLimitCategory
)
19586 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19588 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19590 if(limit_count
> limitEntry
->maxCount
)
19591 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19593 // there is an equip limit on this item
19594 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19595 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19598 return EQUIP_ERR_OK
;
19601 void Player::HandleFall(MovementInfo
const& movementInfo
)
19603 // calculate total z distance of the fall
19604 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19605 sLog
.outDebug("zDiff = %f", z_diff
);
19607 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19608 // 14.57 can be calculated by resolving damageperc formula below to 0
19609 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19610 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19611 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19613 //Safe fall, fall height reduction
19614 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19616 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19620 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19622 float height
= movementInfo
.z
;
19623 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
19627 //Prevent fall damage from being more than the player maximum health
19628 if (damage
> GetMaxHealth())
19629 damage
= GetMaxHealth();
19632 if (GetDummyAura(43621))
19633 damage
= GetMaxHealth()/2;
19635 EnvironmentalDamage(DAMAGE_FALL
, damage
);
19637 // recheck alive, might have died of EnvironmentalDamage
19639 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
19642 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19643 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo
.z
, height
, GetPositionZ(), movementInfo
.fallTime
, height
, damage
, safe_fall
);
19648 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
19650 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
19653 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
19655 uint32 CurTalentPoints
= GetFreeTalentPoints();
19657 if(CurTalentPoints
== 0)
19660 if (talentRank
>= MAX_TALENT_RANK
)
19663 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
19668 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
19673 // prevent learn talent for different class (cheating)
19674 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
19677 // find current max talent rank
19678 int32 curtalent_maxrank
= 0;
19679 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19681 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
19683 curtalent_maxrank
= k
+ 1;
19688 // we already have same or higher talent rank learned
19689 if(curtalent_maxrank
>= (talentRank
+ 1))
19692 // check if we have enough talent points
19693 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19696 // Check if it requires another talent
19697 if (talentInfo
->DependsOn
> 0)
19699 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19701 bool hasEnoughRank
= false;
19702 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
19704 if (depTalentInfo
->RankID
[i
] != 0)
19705 if (HasSpell(depTalentInfo
->RankID
[i
]))
19706 hasEnoughRank
= true;
19708 if (!hasEnoughRank
)
19713 // Find out how many points we have in this field
19714 uint32 spentPoints
= 0;
19716 uint32 tTab
= talentInfo
->TalentTab
;
19717 if (talentInfo
->Row
> 0)
19719 unsigned int numRows
= sTalentStore
.GetNumRows();
19720 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19722 // Someday, someone needs to revamp
19723 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19724 if (tmpTalent
) // the way talents are tracked
19726 if (tmpTalent
->TalentTab
== tTab
)
19728 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
19730 if (tmpTalent
->RankID
[j
] != 0)
19732 if (HasSpell(tmpTalent
->RankID
[j
]))
19734 spentPoints
+= j
+ 1;
19743 // not have required min points spent in talent tree
19744 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
19747 // spell not set in talent.dbc
19748 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19751 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19756 if(HasSpell(spellid
))
19759 // learn! (other talent ranks will unlearned at learning)
19760 learnSpell(spellid
, false);
19761 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19763 // update free talent points
19764 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19767 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
19769 Pet
*pet
= GetPet();
19774 if(petGuid
!= pet
->GetGUID())
19777 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
19779 if(CurTalentPoints
== 0)
19782 if (talentRank
>= MAX_PET_TALENT_RANK
)
19785 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
19790 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
19795 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
19800 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
19805 if(pet_family
->petTalentType
< 0) // not hunter pet
19808 // prevent learn talent for different family (cheating)
19809 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
19812 // find current max talent rank
19813 int32 curtalent_maxrank
= 0;
19814 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19816 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
19818 curtalent_maxrank
= k
+ 1;
19823 // we already have same or higher talent rank learned
19824 if(curtalent_maxrank
>= (talentRank
+ 1))
19827 // check if we have enough talent points
19828 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19831 // Check if it requires another talent
19832 if (talentInfo
->DependsOn
> 0)
19834 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19836 bool hasEnoughRank
= false;
19837 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
19839 if (depTalentInfo
->RankID
[i
] != 0)
19840 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
19841 hasEnoughRank
= true;
19843 if (!hasEnoughRank
)
19848 // Find out how many points we have in this field
19849 uint32 spentPoints
= 0;
19851 uint32 tTab
= talentInfo
->TalentTab
;
19852 if (talentInfo
->Row
> 0)
19854 unsigned int numRows
= sTalentStore
.GetNumRows();
19855 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19857 // Someday, someone needs to revamp
19858 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19859 if (tmpTalent
) // the way talents are tracked
19861 if (tmpTalent
->TalentTab
== tTab
)
19863 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
19865 if (tmpTalent
->RankID
[j
] != 0)
19867 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
19869 spentPoints
+= j
+ 1;
19878 // not have required min points spent in talent tree
19879 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
19882 // spell not set in talent.dbc
19883 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19886 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19891 if(pet
->HasSpell(spellid
))
19894 // learn! (other talent ranks will unlearned at learning)
19895 pet
->learnSpell(spellid
);
19896 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19898 // update free talent points
19899 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19902 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
19904 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
19907 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19909 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19913 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
19915 if (m_lastFallTime
>= minfo
.fallTime
|| m_lastFallZ
<=minfo
.z
|| opcode
== MSG_MOVE_FALL_LAND
)
19916 SetFallInformation(minfo
.fallTime
, minfo
.z
);
19919 void Player::UnsummonPetTemporaryIfAny()
19921 Pet
* pet
= GetPet();
19925 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
19927 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
19928 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
19931 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
19934 void Player::ResummonPetTemporaryUnSummonedIfAny()
19936 if(!m_temporaryUnsummonedPetNumber
)
19939 // not resummon in not appropriate state
19940 if(IsPetNeedBeTemporaryUnsummoned())
19946 Pet
* NewPet
= new Pet
;
19947 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
19950 m_temporaryUnsummonedPetNumber
= 0;
19953 bool Player::canSeeSpellClickOn(Creature
const *c
) const
19955 SpellClickInfoMap
const& map
= objmgr
.mSpellClickInfoMap
;
19956 for(SpellClickInfoMap::const_iterator itr
= map
.lower_bound(c
->GetEntry()); itr
!= map
.upper_bound(c
->GetEntry()); ++itr
)
19958 if(itr
->second
.questId
== 0 || GetQuestStatus(itr
->second
.questId
) == QUEST_STATUS_INCOMPLETE
)