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
))
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::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
491 for (ItemMap::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 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
850 data
<< uint64(GetGUID());
851 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
852 data
<< uint32(damage
);
853 data
<< uint32(absorb
);
854 data
<< uint32(resist
);
855 SendMessageToSet(&data
, true);
857 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
861 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
863 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
864 DurabilityLossAll(0.10f
,false);
865 // durability lost message
866 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
867 GetSession()->SendPacket(&data2
);
870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
874 int32
Player::getMaxTimer(MirrorTimerType timer
)
879 return MINUTE
*IN_MILISECONDS
;
882 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
883 return DISABLED_MIRROR_TIMER
;
884 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
885 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
886 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
887 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
888 return UnderWaterTime
;
893 return DISABLED_MIRROR_TIMER
;
894 return 1*IN_MILISECONDS
;
902 void Player::UpdateMirrorTimers()
904 // Desync flags for update on next HandleDrowning
905 if (m_MirrorTimerFlags
)
906 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
909 void Player::HandleDrowning(uint32 time_diff
)
911 if (!m_MirrorTimerFlags
)
915 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
917 // Breath timer not activated - activate it
918 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
920 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
921 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
923 else // If activated - do tick
925 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
926 // Timer limit - need deal damage
927 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
929 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
930 // Calculate and deal damage
931 // TODO: Check this formula
932 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
933 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
935 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
936 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
939 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
941 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
943 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
944 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
945 StopMirrorTimer(BREATH_TIMER
);
946 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
947 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
951 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
953 // Fatigue timer not activated - activate it
954 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
956 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
957 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
961 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
962 // Timer limit - need deal damage or teleport ghost to graveyard
963 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
965 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
966 if (isAlive()) // Calculate and deal damage
968 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
969 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
971 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
974 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
975 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
978 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
980 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
981 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
982 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
983 StopMirrorTimer(FATIGUE_TIMER
);
984 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
985 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
988 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
990 // Breath timer not activated - activate it
991 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
992 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
995 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
996 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
998 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
999 // Calculate and deal damage
1000 // TODO: Check this formula
1001 uint32 damage
= urand(600, 700);
1002 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1003 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1005 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1010 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1012 // Recheck timers flag
1013 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1014 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1015 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1017 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1020 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1023 ///The player sobers by 256 every 10 seconds
1024 void Player::HandleSobering()
1028 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1029 SetDrunkValue(drunk
);
1032 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1035 return DRUNKEN_SMASHED
;
1037 return DRUNKEN_DRUNK
;
1039 return DRUNKEN_TIPSY
;
1040 return DRUNKEN_SOBER
;
1043 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1045 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1047 m_drunk
= newDrunkenValue
;
1048 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1050 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1052 // special drunk invisibility detection
1053 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1054 m_detectInvisibilityMask
|= (1<<6);
1056 m_detectInvisibilityMask
&= ~(1<<6);
1058 if(newDrunkenState
== oldDrunkenState
)
1061 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1062 data
<< uint64(GetGUID());
1063 data
<< uint32(newDrunkenState
);
1064 data
<< uint32(itemId
);
1066 SendMessageToSet(&data
, true);
1069 void Player::Update( uint32 p_time
)
1075 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1080 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1081 m_nextMailDelivereTime
= 0;
1084 Unit::Update( p_time
);
1086 // update player only attacks
1087 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1089 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1092 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1094 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1097 time_t now
= time (NULL
);
1101 UpdateContestedPvP(p_time
);
1103 UpdateDuelFlag(now
);
1105 CheckDuelDistance(now
);
1107 UpdateAfkReport(now
);
1109 // Update items that have just a limited lifetime
1110 if (now
>m_Last_tick
)
1111 UpdateItemDuration(uint32(now
- m_Last_tick
));
1113 if (!m_timedquests
.empty())
1115 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1116 while (iter
!= m_timedquests
.end())
1118 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1119 if( q_status
.m_timer
<= p_time
)
1121 uint32 quest_id
= *iter
;
1122 ++iter
; // current iter will be removed in FailTimedQuest
1123 FailTimedQuest( quest_id
);
1127 q_status
.m_timer
-= p_time
;
1128 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1134 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1136 Unit
*pVictim
= getVictim();
1137 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1139 // default combat reach 10
1140 // TODO add weapon,skill check
1142 float pldistance
= ATTACK_DISTANCE
;
1144 if (isAttackReady(BASE_ATTACK
))
1146 if(!IsWithinDistInMap(pVictim
, pldistance
))
1148 setAttackTimer(BASE_ATTACK
,100);
1149 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1151 SendAttackSwingNotInRange();
1152 m_swingErrorMsg
= 1;
1155 //120 degrees of radiant range
1156 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1158 setAttackTimer(BASE_ATTACK
,100);
1159 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1161 SendAttackSwingBadFacingAttack();
1162 m_swingErrorMsg
= 2;
1167 m_swingErrorMsg
= 0; // reset swing error state
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 if(haveOffhandWeapon())
1172 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1173 if(off_att
< ATTACK_DISPLAY_DELAY
)
1174 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1176 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1177 resetAttackTimer(BASE_ATTACK
);
1181 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1183 if(!IsWithinDistInMap(pVictim
, pldistance
))
1185 setAttackTimer(OFF_ATTACK
,100);
1187 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1189 setAttackTimer(OFF_ATTACK
,100);
1193 // prevent base and off attack in same time, delay attack at 0.2 sec
1194 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1195 if(base_att
< ATTACK_DISPLAY_DELAY
)
1196 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1198 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1199 resetAttackTimer(OFF_ATTACK
);
1203 Unit
*owner
= pVictim
->GetOwner();
1204 Unit
*u
= owner
? owner
: pVictim
;
1205 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1208 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1213 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1215 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1217 int time_inn
= time(NULL
)-GetTimeInnEnter();
1218 if (time_inn
>= 10) //freeze update
1220 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1221 //speed collect rest bonus (section/in hour)
1222 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1223 UpdateInnerTime(time(NULL
));
1228 if(m_regenTimer
> 0)
1230 if(p_time
>= m_regenTimer
)
1233 m_regenTimer
-= p_time
;
1236 if (m_weaponChangeTimer
> 0)
1238 if(p_time
>= m_weaponChangeTimer
)
1239 m_weaponChangeTimer
= 0;
1241 m_weaponChangeTimer
-= p_time
;
1244 if (m_zoneUpdateTimer
> 0)
1246 if(p_time
>= m_zoneUpdateTimer
)
1248 uint32 newzone
, newarea
;
1249 GetZoneAndAreaId(newzone
,newarea
);
1251 if( m_zoneUpdateId
!= newzone
)
1252 UpdateZone(newzone
,newarea
); // also update area
1255 // use area updates as well
1256 // needed for free far all arenas for example
1257 if( m_areaUpdateId
!= newarea
)
1258 UpdateArea(newarea
);
1260 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1264 m_zoneUpdateTimer
-= p_time
;
1272 if (m_deathState
== JUST_DIED
)
1279 if(p_time
>= m_nextSave
)
1281 // m_nextSave reseted in SaveToDB call
1283 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1287 m_nextSave
-= p_time
;
1291 //Handle Water/drowning
1292 HandleDrowning(p_time
);
1294 //Handle detect stealth players
1295 if (m_DetectInvTimer
> 0)
1297 if (p_time
>= m_DetectInvTimer
)
1299 m_DetectInvTimer
= 3000;
1300 HandleStealthedUnitsDetection();
1303 m_DetectInvTimer
-= p_time
;
1307 if (now
> m_Last_tick
)
1309 uint32 elapsed
= uint32(now
- m_Last_tick
);
1310 m_Played_time
[0] += elapsed
; // Total played time
1311 m_Played_time
[1] += elapsed
; // Level played time
1317 m_drunkTimer
+= p_time
;
1319 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1323 // not auto-free ghost from body in instances
1324 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1326 if(p_time
>= m_deathTimer
)
1333 m_deathTimer
-= p_time
;
1336 UpdateEnchantTime(p_time
);
1337 UpdateHomebindTime(p_time
);
1340 SendUpdateToOutOfRangeGroupMembers();
1342 Pet
* pet
= GetPet();
1343 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1345 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1350 void Player::setDeathState(DeathState s
)
1352 uint32 ressSpellId
= 0;
1354 bool cur
= isAlive();
1356 if(s
== JUST_DIED
&& cur
)
1358 // drunken state is cleared on death
1360 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1363 clearResurrectRequestData();
1365 // remove form before other mods to prevent incorrect stats calculation
1366 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1368 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1369 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1371 // remove uncontrolled pets
1375 // save value before aura remove in Unit::setDeathState
1376 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1380 ressSpellId
= GetResurrectionSpellId();
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1385 Unit::setDeathState(s
);
1387 // restore resurrection spell id for player after aura remove
1388 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1389 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1391 if(isAlive() && !cur
)
1393 //clear aura case after resurrection by another way (spells will be applied before next death)
1394 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1396 // restore default warrior stance
1397 if(getClass()== CLASS_WARRIOR
)
1398 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1402 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1404 Field
*fields
= result
->Fetch();
1406 *p_data
<< uint64(GetGUID());
1409 *p_data
<< uint8(getRace());
1410 uint8 pClass
= getClass();
1411 *p_data
<< uint8(pClass
);
1412 *p_data
<< uint8(getGender());
1414 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1415 *p_data
<< uint8(bytes
);
1416 *p_data
<< uint8(bytes
>> 8);
1417 *p_data
<< uint8(bytes
>> 16);
1418 *p_data
<< uint8(bytes
>> 24);
1420 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1421 *p_data
<< uint8(bytes
);
1423 *p_data
<< uint8(getLevel()); // player level
1424 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1425 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1426 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1427 *p_data
<< uint32(zoneId
);
1428 *p_data
<< uint32(GetMapId());
1430 *p_data
<< GetPositionX();
1431 *p_data
<< GetPositionY();
1432 *p_data
<< GetPositionZ();
1435 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1437 uint32 char_flags
= 0;
1438 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1439 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1440 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1441 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1442 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1443 char_flags
|= CHARACTER_FLAG_GHOST
;
1444 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1445 char_flags
|= CHARACTER_FLAG_RENAME
;
1446 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1447 char_flags
|= CHARACTER_FLAG_DECLINED
;
1449 *p_data
<< uint32(char_flags
); // character flags
1450 // character customize (flags?)
1451 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1452 *p_data
<< uint8(1); // unknown
1456 uint32 petDisplayId
= 0;
1457 uint32 petLevel
= 0;
1458 uint32 petFamily
= 0;
1460 // show pet at selection character in character list only for non-ghost character
1461 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1463 uint32 entry
= fields
[10].GetUInt32();
1464 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1467 petDisplayId
= fields
[11].GetUInt32();
1468 petLevel
= fields
[12].GetUInt32();
1469 petFamily
= cInfo
->family
;
1473 *p_data
<< uint32(petDisplayId
);
1474 *p_data
<< uint32(petLevel
);
1475 *p_data
<< uint32(petFamily
);
1478 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1480 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1481 uint32 item_id
= GetUInt32Value(visualbase
);
1482 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1483 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1485 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1487 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1488 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1494 *p_data
<< uint32(proto
->DisplayInfoID
);
1495 *p_data
<< uint8(proto
->InventoryType
);
1496 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1500 *p_data
<< uint32(0);
1501 *p_data
<< uint8(0);
1502 *p_data
<< uint32(0); // enchant?
1505 *p_data
<< uint32(0); // first bag display id
1506 *p_data
<< uint8(0); // first bag inventory type
1507 *p_data
<< uint32(0); // enchant?
1510 bool Player::ToggleAFK()
1512 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1514 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1516 // afk player not allowed in battleground
1517 if(state
&& InBattleGround())
1518 LeaveBattleground();
1523 bool Player::ToggleDND()
1525 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1527 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1530 uint8
Player::chatTag() const
1547 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1549 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1551 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1555 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1556 Pet
* pet
= GetPet();
1558 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1560 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1561 // don't let gm level > 1 either
1562 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1565 // client without expansion support
1566 if(GetSession()->Expansion() < mEntry
->Expansion())
1568 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1571 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1573 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1575 return false; // normal client can't teleport to this map...
1579 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1582 // if we were on a transport, leave
1583 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1585 m_transport
->RemovePassenger(this);
1587 m_movementInfo
.t_x
= 0.0f
;
1588 m_movementInfo
.t_y
= 0.0f
;
1589 m_movementInfo
.t_z
= 0.0f
;
1590 m_movementInfo
.t_o
= 0.0f
;
1591 m_movementInfo
.t_time
= 0;
1594 // The player was ported to another map and looses the duel immediately.
1595 // We have to perform this check before the teleport, otherwise the
1596 // ObjectAccessor won't find the flag.
1597 if (duel
&& GetMapId()!=mapid
)
1599 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1601 DuelComplete(DUEL_FLED
);
1604 // reset movement flags at teleport, because player will continue move with these flags after teleport
1605 SetUnitMovementFlags(0);
1607 if ((GetMapId() == mapid
) && (!m_transport
))
1609 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1611 //same map, only remove pet if out of range for new position
1612 if(pet
&& pet
->GetDistance(x
,y
,z
) >= OWNER_MAX_DISTANCE
)
1613 UnsummonPetTemporaryIfAny();
1616 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1619 // this will be used instead of the current location in SaveToDB
1620 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1621 SetFallInformation(0, z
);
1623 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1624 // at client packet MSG_MOVE_TELEPORT_ACK
1625 SetSemaphoreTeleportNear(true);
1626 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1627 if(!GetSession()->PlayerLogout())
1630 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1631 GetSession()->SendPacket(&data
);
1636 // far teleport to another map
1637 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1638 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1640 // Check enter rights before map getting to avoid creating instance copy for player
1641 // this check not dependent from map instance copy and same for all instance copies of selected map
1642 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1645 // If the map is not created, assume it is possible to enter it.
1646 // It will be created in the WorldPortAck.
1647 Map
*map
= MapManager::Instance().FindMap(mapid
);
1648 if (!map
|| map
->CanEnter(this))
1654 ResetContestedPvP();
1656 // remove player from battleground on far teleport (when changing maps)
1657 if(BattleGround
const* bg
= GetBattleGround())
1659 // Note: at battleground join battleground id set before teleport
1660 // and we already will found "current" battleground
1661 // just need check that this is targeted map or leave
1662 if(bg
->GetMapId() != mapid
)
1663 LeaveBattleground(false); // don't teleport to entry point
1666 // remove pet on map change
1668 UnsummonPetTemporaryIfAny();
1670 // remove all dyn objects
1671 RemoveAllDynObjects();
1673 // stop spellcasting
1674 // not attempt interrupt teleportation spell at caster teleport
1675 if(!(options
& TELE_TO_SPELL
))
1676 if(IsNonMeleeSpellCasted(true))
1677 InterruptNonMeleeSpells(true);
1679 if(!GetSession()->PlayerLogout())
1681 // send transfer packets
1682 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1683 data
<< uint32(mapid
);
1686 data
<< m_transport
->GetEntry() << GetMapId();
1688 GetSession()->SendPacket(&data
);
1690 data
.Initialize(SMSG_NEW_WORLD
, (20));
1693 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1697 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1699 GetSession()->SendPacket( &data
);
1700 SendSavedInstances();
1702 // remove from old map now
1703 if(oldmap
) oldmap
->Remove(this, false);
1706 // new final coordinates
1710 float final_o
= orientation
;
1714 final_x
+= m_movementInfo
.t_x
;
1715 final_y
+= m_movementInfo
.t_y
;
1716 final_z
+= m_movementInfo
.t_z
;
1717 final_o
+= m_movementInfo
.t_o
;
1720 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1721 SetFallInformation(0, final_z
);
1722 // if the player is saved before worldportack (at logout for example)
1723 // this will be used instead of the current location in SaveToDB
1725 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1727 // move packet sent by client always after far teleport
1728 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1729 SetSemaphoreTeleportFar(true);
1737 void Player::AddToWorld()
1739 ///- Do not add/remove the player from the object storage
1740 ///- It will crash when updating the ObjectAccessor
1741 ///- The player should only be added when logging in
1744 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1747 m_items
[i
]->AddToWorld();
1751 void Player::RemoveFromWorld()
1756 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1758 UnsummonAllTotems();
1763 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1766 m_items
[i
]->RemoveFromWorld();
1769 ///- Do not add/remove the player from the object storage
1770 ///- It will crash when updating the ObjectAccessor
1771 ///- The player should only be removed when logging out
1772 Unit::RemoveFromWorld();
1775 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1779 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1783 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1785 // talent who gave more rage on attack
1786 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1790 addRage
= damage
/rageconversion
*2.5;
1792 // Berserker Rage effect
1793 if(HasAura(18499,0))
1797 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1799 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1802 void Player::RegenerateAll()
1804 if (m_regenTimer
!= 0)
1806 uint32 regenDelay
= 2000;
1808 // Not in combat or they have regeneration
1809 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1810 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1813 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1815 Regenerate(POWER_RAGE
);
1816 if(getClass() == CLASS_DEATH_KNIGHT
)
1817 Regenerate(POWER_RUNIC_POWER
);
1821 Regenerate( POWER_ENERGY
);
1823 Regenerate( POWER_MANA
);
1825 if(getClass() == CLASS_DEATH_KNIGHT
)
1826 Regenerate( POWER_RUNE
);
1828 m_regenTimer
= regenDelay
;
1831 void Player::Regenerate(Powers power
)
1833 uint32 curValue
= GetPower(power
);
1834 uint32 maxValue
= GetMaxPower(power
);
1836 float addvalue
= 0.0f
;
1842 bool recentCast
= IsUnderLastManaUseEffect();
1843 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1846 // Mangos Updates Mana in intervals of 2s, which is correct
1847 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1851 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1854 case POWER_RAGE
: // Regenerate rage
1856 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1857 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1859 case POWER_ENERGY
: // Regenerate energy (rogue)
1862 case POWER_RUNIC_POWER
:
1864 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1865 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1869 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1870 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1871 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1874 case POWER_HAPPINESS
:
1878 // Mana regen calculated in Player::UpdateManaRegen()
1879 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1880 if(power
!= POWER_MANA
)
1882 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1883 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1884 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1885 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1888 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1890 curValue
+= uint32(addvalue
);
1891 if (curValue
> maxValue
)
1892 curValue
= maxValue
;
1896 if(curValue
<= uint32(addvalue
))
1899 curValue
-= uint32(addvalue
);
1901 SetPower(power
, curValue
);
1904 void Player::RegenerateHealth()
1906 uint32 curValue
= GetHealth();
1907 uint32 maxValue
= GetMaxHealth();
1909 if (curValue
>= maxValue
) return;
1911 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1913 float addvalue
= 0.0f
;
1916 if ( IsPolymorphed() )
1917 addvalue
= GetMaxHealth()/3;
1918 // normal regen case (maybe partly in combat case)
1919 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1921 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1924 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1925 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1926 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1928 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1929 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1935 // always regeneration bonus (including combat)
1936 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1941 ModifyHealth(int32(addvalue
));
1944 bool Player::CanInteractWithNPCs(bool alive
) const
1946 if(alive
&& !isAlive())
1955 Player::GetNPCIfCanInteractWith(uint64 guid
, uint32 npcflagmask
)
1965 Creature
*unit
= GetMap()->GetCreature(guid
);
1970 if(!CanInteractWithNPCs(!unit
->isSpiritService()))
1973 // appropriate npc type
1974 if(npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
1977 // alive or spirit healer
1978 if(!unit
->isAlive() && (!unit
->isSpiritService() || isAlive() ))
1981 // not allow interaction under control
1982 if(unit
->GetCharmerOrOwnerGUID())
1986 if( unit
->IsHostileTo(this))
1990 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
1991 if(factionTemplate
->faction
)
1992 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
1993 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
1997 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2003 GameObject
* Player::GetGameObjectIfCanInteractWith(uint64 guid
, GameobjectTypes type
) const
2005 if(GameObject
*go
= GetMap()->GetGameObject(guid
))
2007 if(go
->GetGoType() == type
)
2012 // TODO: find out how the client calculates the maximal usage distance to spellless working
2013 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2014 case GAMEOBJECT_TYPE_GUILD_BANK
:
2015 case GAMEOBJECT_TYPE_MAILBOX
:
2018 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2019 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2022 maxdist
= INTERACTION_DISTANCE
;
2026 if (go
->IsWithinDistInMap(this, maxdist
))
2029 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
,
2030 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2036 bool Player::IsUnderWater() const
2038 return IsInWater() &&
2039 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2042 void Player::SetInWater(bool apply
)
2044 if(m_isInWater
==apply
)
2047 //define player in water by opcodes
2048 //move player's guid into HateOfflineList of those mobs
2049 //which can't swim and move guid back into ThreatList when
2051 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2052 m_isInWater
= apply
;
2054 // remove auras that need water/land
2055 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2057 getHostilRefManager().updateThreatTables();
2060 void Player::SetGameMaster(bool on
)
2064 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2066 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2068 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2069 ResetContestedPvP();
2071 getHostilRefManager().setOnlineOfflineState(false);
2074 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2079 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2080 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2082 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2083 setFactionForRace(getRace());
2084 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2086 // restore FFA PvP Server state
2087 if(sWorld
.IsFFAPvPRealm())
2088 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2090 // restore FFA PvP area state, remove not allowed for GM mounts
2091 UpdateArea(m_areaUpdateId
);
2093 getHostilRefManager().setOnlineOfflineState(true);
2096 ObjectAccessor::UpdateVisibilityForPlayer(this);
2099 void Player::SetGMVisible(bool on
)
2103 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2105 // Reapply stealth/invisibility if active or show if not any
2106 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2107 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2108 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2109 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2111 SetVisibility(VISIBILITY_ON
);
2115 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2117 SetAcceptWhispers(false);
2118 SetGameMaster(true);
2120 SetVisibility(VISIBILITY_OFF
);
2124 bool Player::IsGroupVisibleFor(Player
* p
) const
2126 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2128 default: return IsInSameGroupWith(p
);
2129 case 1: return IsInSameRaidWith(p
);
2130 case 2: return GetTeam()==p
->GetTeam();
2134 bool Player::IsInSameGroupWith(Player
const* p
) const
2136 return p
==this || GetGroup() != NULL
&&
2137 GetGroup() == p
->GetGroup() &&
2138 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2141 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2142 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2143 void Player::UninviteFromGroup()
2145 Group
* group
= GetGroupInvite();
2149 group
->RemoveInvite(this);
2151 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2153 if(group
->IsCreated())
2155 group
->Disband(true);
2156 objmgr
.RemoveGroup(group
);
2159 group
->RemoveAllInvites();
2165 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2169 if (group
->RemoveMember(guid
, 0) <= 1)
2171 // group->Disband(); already disbanded in RemoveMember
2172 objmgr
.RemoveGroup(group
);
2174 // removemember sets the player's group pointer to NULL
2179 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2181 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2182 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2183 data
<< uint32(GivenXP
+RestXP
); // given experience
2184 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2187 data
<< uint32(GivenXP
); // experience without rested bonus
2188 data
<< float(1); // 1 - none 0 - 100% group bonus output
2190 data
<< uint8(0); // new 2.4.0
2191 GetSession()->SendPacket(&data
);
2194 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2202 uint32 level
= getLevel();
2204 // XP to money conversion processed in Player::RewardQuest
2205 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2208 // handle SPELL_AURA_MOD_XP_PCT auras
2209 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2210 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2211 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2213 // XP resting bonus for kill
2214 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2216 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2218 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2219 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2220 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2222 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2226 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2227 GiveLevel(level
+ 1);
2230 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2233 SetUInt32Value(PLAYER_XP
, newXP
);
2236 // Update player to next level
2237 // Current player experience not update (must be update by caller)
2238 void Player::GiveLevel(uint32 level
)
2240 if ( level
== getLevel() )
2243 PlayerLevelInfo info
;
2244 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2246 PlayerClassLevelInfo classInfo
;
2247 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2249 // send levelup info to client
2250 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2251 data
<< uint32(level
);
2252 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2253 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2254 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2262 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2263 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2265 GetSession()->SendPacket(&data
);
2267 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2269 //update level, max level of skills
2270 if(getLevel()!= level
)
2271 m_Played_time
[1] = 0; // Level Played Time reset
2273 UpdateSkillsForLevel ();
2275 // save base values (bonuses already included in stored stats
2276 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2277 SetCreateStat(Stats(i
), info
.stats
[i
]);
2279 SetCreateHealth(classInfo
.basehealth
);
2280 SetCreateMana(classInfo
.basemana
);
2282 InitTalentForLevel();
2283 InitTaxiNodesForLevel();
2284 InitGlyphsForLevel();
2288 // set current level health and mana/energy to maximum after applying all mods.
2289 SetHealth(GetMaxHealth());
2290 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2291 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2292 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2293 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2294 SetPower(POWER_FOCUS
, 0);
2295 SetPower(POWER_HAPPINESS
, 0);
2297 // give level to summoned pet
2298 Pet
* pet
= GetPet();
2299 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2300 pet
->GivePetLevel(level
);
2301 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2304 void Player::InitTalentForLevel()
2306 uint32 level
= getLevel();
2307 // talents base at level diff ( talents = level - 9 but some can be used already)
2310 // Remove all talent points
2311 if(m_usedTalentCount
> 0) // Free any used talents
2314 SetFreeTalentPoints(0);
2319 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2321 // if used more that have then reset
2322 if(m_usedTalentCount
> talentPointsForLevel
)
2324 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2327 SetFreeTalentPoints(0);
2329 // else update amount of free points
2331 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2335 void Player::InitStatsForLevel(bool reapplyMods
)
2337 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2338 _RemoveAllStatBonuses();
2340 PlayerClassLevelInfo classInfo
;
2341 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2343 PlayerLevelInfo info
;
2344 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2346 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2347 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2349 UpdateSkillsForLevel ();
2351 // set default cast time multiplier
2352 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2354 // reset size before reapply auras
2355 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2357 // save base values (bonuses already included in stored stats
2358 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2359 SetCreateStat(Stats(i
), info
.stats
[i
]);
2361 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2362 SetStat(Stats(i
), info
.stats
[i
]);
2364 SetCreateHealth(classInfo
.basehealth
);
2367 SetCreateMana(classInfo
.basemana
);
2369 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2373 //reset rating fields values
2374 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2375 SetUInt32Value(index
, 0);
2377 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2378 for (int i
= 0; i
< 7; i
++)
2380 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2381 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2382 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2385 //reset attack power, damage and attack speed fields
2386 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2387 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2388 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2390 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2391 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2392 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2393 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2394 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2395 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2397 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2398 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2399 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2400 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2401 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2402 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2404 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2405 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2406 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2407 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2409 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2410 for (uint8 i
= 0; i
< 7; ++i
)
2411 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2413 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2414 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2415 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2418 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2420 // set armor (resistance 0) to original value (create_agility*2)
2421 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2422 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2423 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2424 // set other resistance to original value (0)
2425 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2427 SetResistance(SpellSchools(i
), 0);
2428 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2429 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2432 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2433 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2434 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2436 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2437 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2439 // Reset no reagent cost field
2440 for(int i
= 0; i
< 3; i
++)
2441 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2442 // Init data for form but skip reapply item mods for form
2443 InitDataForForm(reapplyMods
);
2446 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2447 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2449 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2451 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2452 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2454 // cleanup unit flags (will be re-applied if need at aura load).
2455 RemoveFlag( UNIT_FIELD_FLAGS
,
2456 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2457 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2458 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2459 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2460 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2461 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2463 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2465 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2466 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2468 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2469 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2471 // restore if need some important flags
2472 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2474 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2475 _ApplyAllStatBonuses();
2477 // set current level health and mana/energy to maximum after applying all mods.
2478 SetHealth(GetMaxHealth());
2479 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2480 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2481 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2482 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2483 SetPower(POWER_FOCUS
, 0);
2484 SetPower(POWER_HAPPINESS
, 0);
2485 SetPower(POWER_RUNIC_POWER
, 0);
2488 void Player::SendInitialSpells()
2490 time_t curTime
= time(NULL
);
2491 time_t infTime
= curTime
+ MONTH
/2;
2493 uint16 spellCount
= 0;
2495 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2498 size_t countPos
= data
.wpos();
2499 data
<< uint16(spellCount
); // spell count placeholder
2501 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2503 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2506 if(!itr
->second
->active
|| itr
->second
->disabled
)
2509 data
<< uint16(itr
->first
);
2510 data
<< uint16(0); // it's not slot id
2515 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2517 uint16 spellCooldowns
= m_spellCooldowns
.size();
2518 data
<< uint16(spellCooldowns
);
2519 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2521 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2525 // not send infinity cooldown
2526 if(itr
->second
.end
> infTime
)
2529 data
<< uint16(itr
->first
);
2531 time_t cooldown
= 0;
2532 if(itr
->second
.end
> curTime
)
2533 cooldown
= (itr
->second
.end
-curTime
)*IN_MILISECONDS
;
2535 data
<< uint16(itr
->second
.itemid
); // cast item id
2536 data
<< uint16(sEntry
->Category
); // spell category
2537 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2539 data
<< uint32(0); // cooldown
2540 data
<< uint32(cooldown
); // category cooldown
2544 data
<< uint32(cooldown
); // cooldown
2545 data
<< uint32(0); // category cooldown
2549 GetSession()->SendPacket(&data
);
2551 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2554 void Player::RemoveMail(uint32 id
)
2556 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2558 if ((*itr
)->messageID
== id
)
2560 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2567 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2569 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2570 data
<< (uint32
) mailId
;
2571 data
<< (uint32
) mailAction
;
2572 data
<< (uint32
) mailError
;
2573 if ( mailError
== MAIL_ERR_BAG_FULL
)
2574 data
<< (uint32
) equipError
;
2575 else if( mailAction
== MAIL_ITEM_TAKEN
)
2577 data
<< (uint32
) item_guid
; // item guid low?
2578 data
<< (uint32
) item_count
; // item count?
2580 GetSession()->SendPacket(&data
);
2583 void Player::SendNewMail()
2585 // deliver undelivered mail
2586 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2588 GetSession()->SendPacket(&data
);
2591 void Player::UpdateNextMailTimeAndUnreads()
2593 // calculate next delivery time (min. from non-delivered mails
2594 // and recalculate unReadMail
2595 time_t cTime
= time(NULL
);
2596 m_nextMailDelivereTime
= 0;
2598 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2600 if((*itr
)->deliver_time
> cTime
)
2602 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2603 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2605 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2610 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2612 if(deliver_time
<= time(NULL
)) // ready now
2617 else // not ready and no have ready mails
2619 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2620 m_nextMailDelivereTime
= deliver_time
;
2624 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2626 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2629 // do character spell book cleanup (all characters)
2630 if(!IsInWorld() && !learning
) // spell load case
2632 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2633 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2636 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2641 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2643 // do character spell book cleanup (all characters)
2644 if(!IsInWorld() && !learning
) // spell load case
2646 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2647 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2650 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2655 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2657 bool dependent_set
= false;
2658 bool disabled_case
= false;
2659 bool superceded_old
= false;
2661 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2662 if (itr
!= m_spells
.end())
2664 uint32 next_active_spell_id
= 0;
2665 // fix activate state for non-stackable low rank (and find next spell for !active case)
2666 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2668 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2669 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2671 if(HasSpell(next_itr
->second
))
2673 // high rank already known so this must !active
2675 next_active_spell_id
= next_itr
->second
;
2681 // not do anything if already known in expected state
2682 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2683 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2685 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2686 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2691 // dependent spell known as not dependent, overwrite state
2692 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2694 itr
->second
->dependent
= dependent
;
2695 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2696 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2697 dependent_set
= true;
2700 // update active state for known spell
2701 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2703 itr
->second
->active
= active
;
2705 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2706 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2707 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2708 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2712 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2713 CastSpell (this,spell_id
,true);
2715 else if(IsInWorld())
2717 if(next_active_spell_id
)
2719 // update spell ranks in spellbook and action bar
2720 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2721 data
<< uint16(spell_id
);
2722 data
<< uint16(next_active_spell_id
);
2723 GetSession()->SendPacket( &data
);
2727 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2728 data
<< uint16(spell_id
);
2729 GetSession()->SendPacket(&data
);
2733 return active
; // learn (show in spell book if active now)
2736 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2738 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2739 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2740 itr
->second
->disabled
= disabled
;
2745 disabled_case
= true;
2747 else switch(itr
->second
->state
)
2749 case PLAYERSPELL_UNCHANGED
: // known saved spell
2751 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2754 m_spells
.erase(itr
);
2755 state
= PLAYERSPELL_CHANGED
;
2756 break; // need re-add
2758 default: // known not saved yet spell (new or modified)
2760 // can be in case spell loading but learned at some previous spell loading
2761 if(!IsInWorld() && !learning
&& !dependent_set
)
2762 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2769 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2771 // talent: unlearn all other talent ranks (high and low)
2772 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2774 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2776 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
2778 // skip learning spell and no rank spell case
2779 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2780 if(!rankSpellId
|| rankSpellId
==spell_id
)
2783 removeSpell(rankSpellId
);
2787 // non talent spell: learn low ranks (recursive call)
2788 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2790 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2791 addSpell(prev_spell
,active
,true,true,disabled
);
2792 else // at normal learning
2793 learnSpell(prev_spell
,true);
2796 PlayerSpell
*newspell
= new PlayerSpell
;
2797 newspell
->state
= state
;
2798 newspell
->active
= active
;
2799 newspell
->dependent
= dependent
;
2800 newspell
->disabled
= disabled
;
2802 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2803 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2805 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
2807 if(itr2
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2808 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
2809 if(!i_spellInfo
) continue;
2811 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
2813 if(itr2
->second
->active
)
2815 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
2817 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2819 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2820 data
<< uint16(itr2
->first
);
2821 data
<< uint16(spell_id
);
2822 GetSession()->SendPacket( &data
);
2825 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2826 itr2
->second
->active
= false;
2827 if(itr2
->second
->state
!= PLAYERSPELL_NEW
)
2828 itr2
->second
->state
= PLAYERSPELL_CHANGED
;
2829 superceded_old
= true; // new spell replace old in action bars and spell book.
2831 else if(spellmgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
2833 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2835 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2836 data
<< uint16(spell_id
);
2837 data
<< uint16(itr2
->first
);
2838 GetSession()->SendPacket( &data
);
2841 // mark new spell as disable (not learned yet for client and will not learned)
2842 newspell
->active
= false;
2843 if(newspell
->state
!= PLAYERSPELL_NEW
)
2844 newspell
->state
= PLAYERSPELL_CHANGED
;
2851 m_spells
[spell_id
] = newspell
;
2853 // return false if spell disabled
2854 if (newspell
->disabled
)
2858 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2860 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2861 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2862 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2864 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2865 CastSpell(this, spell_id
, true);
2867 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2868 else if (IsPassiveSpell(spell_id
))
2870 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2871 CastSpell(this, spell_id
, true);
2873 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2875 CastSpell(this, spell_id
, true);
2879 // update used talent points count
2880 m_usedTalentCount
+= talentCost
;
2882 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2883 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2885 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2886 SetFreePrimaryProffesions(freeProfs
-1);
2889 // add dependent skills
2890 uint16 maxskill
= GetMaxSkillValueForLevel();
2892 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2894 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2895 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2899 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2900 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2902 if(skill_value
< spellLearnSkill
->value
)
2903 skill_value
= spellLearnSkill
->value
;
2905 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2907 if(skill_max_value
< new_skill_max_value
)
2908 skill_max_value
= new_skill_max_value
;
2910 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2914 // not ranked skills
2915 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2917 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2921 if(HasSkill(pSkill
->id
))
2924 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2925 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2926 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
2928 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2930 case SKILL_RANGE_LANGUAGE
:
2931 SetSkill(pSkill
->id
, 300, 300 );
2933 case SKILL_RANGE_LEVEL
:
2934 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2936 case SKILL_RANGE_MONO
:
2937 SetSkill(pSkill
->id
, 1, 1 );
2946 // learn dependent spells
2947 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2948 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2950 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2952 if(!itr2
->second
.autoLearned
)
2954 if(!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
2955 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
2956 else // at normal learning
2957 learnSpell(itr2
->second
.spell
,true);
2961 if(!GetSession()->PlayerLoading())
2963 // not ranked skills
2964 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2966 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
2967 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
2970 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
2973 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2974 return active
&& !disabled
&& !superceded_old
;
2977 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2979 bool need_cast
= false;
2981 switch(spellInfo
->Id
)
2983 // some spells not have stance data expacted cast at form change or present
2984 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2985 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2986 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2987 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2988 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2989 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2990 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2991 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2992 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2993 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2994 // another spells have proper stance data
2995 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2998 //Check CasterAuraStates
2999 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3002 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3004 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3006 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
3007 bool active
= disabled
? itr
->second
->active
: true;
3009 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3011 // learn all disabled higher ranks (recursive)
3014 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3015 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3017 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3018 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
3019 learnSpell(i
->second
,false);
3023 // prevent duplicated entires in spell book, also not send if not in world (loading)
3024 if(!learning
|| !IsInWorld ())
3027 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3028 data
<< uint32(spell_id
);
3029 GetSession()->SendPacket(&data
);
3032 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
3034 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3035 if (itr
== m_spells
.end())
3038 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
3041 // unlearn non talent higher ranks (recursive)
3042 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3043 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3044 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3045 removeSpell(itr2
->second
,disabled
);
3047 bool cur_active
= itr
->second
->active
;
3048 bool cur_dependent
= itr
->second
->dependent
;
3052 itr
->second
->disabled
= disabled
;
3053 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3054 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3058 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3061 m_spells
.erase(itr
);
3064 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3067 RemoveAurasDueToSpell(spell_id
);
3070 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
3071 RemovePetAura(petSpell
);
3073 // free talent points
3074 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3077 if(talentCosts
< m_usedTalentCount
)
3078 m_usedTalentCount
-= talentCosts
;
3080 m_usedTalentCount
= 0;
3083 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3084 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3086 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
3087 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3088 SetFreePrimaryProffesions(freeProfs
);
3091 // remove dependent skill
3092 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3095 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3096 if(!prev_spell
) // first rank, remove skill
3097 SetSkill(spellLearnSkill
->skill
,0,0);
3100 // search prev. skill setting by spell ranks chain
3101 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3102 while(!prevSkill
&& prev_spell
)
3104 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3105 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3108 if(!prevSkill
) // not found prev skill setting, remove skill
3109 SetSkill(spellLearnSkill
->skill
,0,0);
3110 else // set to prev. skill setting values
3112 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3113 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3115 if(skill_value
> prevSkill
->value
)
3116 skill_value
= prevSkill
->value
;
3118 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3120 if(skill_max_value
> new_skill_max_value
)
3121 skill_max_value
= new_skill_max_value
;
3123 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3130 // not ranked skills
3131 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3132 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3134 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3136 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3140 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3141 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3142 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
3144 // not reset skills for professions and racial abilities
3145 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3146 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3149 SetSkill(pSkill
->id
, 0, 0 );
3154 // remove dependent spells
3155 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3156 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3158 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3159 removeSpell(itr2
->second
.spell
, disabled
);
3161 // activate lesser rank in spellbook/action bar, and cast it if need
3162 bool prev_activate
= false;
3164 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3166 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3168 // if talent then lesser rank also talent and need learn
3170 learnSpell (prev_id
,false);
3171 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3172 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3174 // need manually update dependence state (learn spell ignore like attempts)
3175 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3176 if (prev_itr
!= m_spells
.end())
3178 if(prev_itr
->second
->dependent
!= cur_dependent
)
3180 prev_itr
->second
->dependent
= cur_dependent
;
3181 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3182 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3185 // now re-learn if need re-activate
3186 if(cur_active
&& !prev_itr
->second
->active
)
3188 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3190 if(update_action_bar_for_low_rank
)
3192 // downgrade spell ranks in spellbook and action bar
3193 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3194 data
<< uint16(spell_id
);
3195 data
<< uint16(prev_id
);
3196 GetSession()->SendPacket( &data
);
3197 prev_activate
= true;
3205 // remove from spell book if not replaced by lesser rank
3208 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3209 data
<< uint16(spell_id
);
3210 GetSession()->SendPacket(&data
);
3214 void Player::RemoveArenaSpellCooldowns()
3216 // remove cooldowns on spells that has < 15 min CD
3217 SpellCooldowns::iterator itr
, next
;
3218 // iterate spell cooldowns
3219 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3223 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3224 // check if spellentry is present and if the cooldown is less than 15 mins
3226 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3227 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3230 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3231 data
<< uint32(itr
->first
);
3232 data
<< uint64(GetGUID());
3233 GetSession()->SendPacket(&data
);
3235 m_spellCooldowns
.erase(itr
);
3240 void Player::RemoveAllSpellCooldown()
3242 if(!m_spellCooldowns
.empty())
3244 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3246 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3247 data
<< uint32(itr
->first
);
3248 data
<< uint64(GetGUID());
3249 GetSession()->SendPacket(&data
);
3251 m_spellCooldowns
.clear();
3255 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3257 // some cooldowns can be already set at aura loading...
3259 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3263 time_t curTime
= time(NULL
);
3267 Field
*fields
= result
->Fetch();
3269 uint32 spell_id
= fields
[0].GetUInt32();
3270 uint32 item_id
= fields
[1].GetUInt32();
3271 time_t db_time
= (time_t)fields
[2].GetUInt64();
3273 if(!sSpellStore
.LookupEntry(spell_id
))
3275 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3279 // skip outdated cooldown
3280 if(db_time
<= curTime
)
3283 AddSpellCooldown(spell_id
, item_id
, db_time
);
3285 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3287 while( result
->NextRow() );
3293 void Player::_SaveSpellCooldowns()
3295 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3297 time_t curTime
= time(NULL
);
3298 time_t infTime
= curTime
+ MONTH
/2;
3300 // remove outdated and save active
3301 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3303 if(itr
->second
.end
<= curTime
)
3304 m_spellCooldowns
.erase(itr
++);
3305 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3307 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
));
3315 uint32
Player::resetTalentsCost() const
3317 // The first time reset costs 1 gold
3318 if(m_resetTalentsCost
< 1*GOLD
)
3321 else if(m_resetTalentsCost
< 5*GOLD
)
3323 // After that it increases in increments of 5 gold
3324 else if(m_resetTalentsCost
< 10*GOLD
)
3328 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3331 // This cost will be reduced by a rate of 5 gold per month
3332 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3333 // to a minimum of 10 gold.
3334 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3338 // After that it increases in increments of 5 gold
3339 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3340 // until it hits a cap of 50 gold.
3341 if(new_cost
> 50*GOLD
)
3348 bool Player::resetTalents(bool no_cost
)
3350 // not need after this call
3351 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3353 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3354 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3357 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3359 if (m_usedTalentCount
== 0)
3361 SetFreeTalentPoints(talentPointsForLevel
);
3369 cost
= resetTalentsCost();
3371 if (GetMoney() < cost
)
3373 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3378 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3380 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3382 if (!talentInfo
) continue;
3384 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3389 // unlearn only talents for character class
3390 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3391 // to prevent unexpected lost normal learned spell skip another class talents
3392 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3395 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
3397 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3399 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3405 // remove learned spells (all ranks)
3406 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3408 // unlearn if first rank is talent or learned by talent
3409 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3411 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3412 itr
= GetSpellMap().begin();
3421 SetFreeTalentPoints(talentPointsForLevel
);
3425 ModifyMoney(-(int32
)cost
);
3426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3428 m_resetTalentsCost
= cost
;
3429 m_resetTalentsTime
= time(NULL
);
3432 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3433 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3437 m_canTitanGrip
= false;
3438 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3439 AutoUnequipOffhandIfNeed();
3445 Mail
* Player::GetMail(uint32 id
)
3447 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3449 if ((*itr
)->messageID
== id
)
3457 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3461 Object::_SetCreateBits(updateMask
, target
);
3465 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3467 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3468 updateMask
->SetBit(index
);
3473 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3477 Object::_SetUpdateBits(updateMask
, target
);
3481 Object::_SetUpdateBits(updateMask
, target
);
3482 *updateMask
&= updateVisualBits
;
3486 void Player::InitVisibleBits()
3488 updateVisualBits
.SetCount(PLAYER_END
);
3490 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3491 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3492 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3493 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3494 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3495 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3496 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3497 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3498 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3499 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3500 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3501 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3502 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3503 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3504 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3505 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3506 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3507 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3508 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3509 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3510 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3511 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3512 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3513 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3514 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3515 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3516 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3517 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3518 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3519 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3520 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3521 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3522 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3523 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3524 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3525 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3526 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3527 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3528 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3529 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3530 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3531 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3532 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3533 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3534 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3535 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3536 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3537 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3538 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3539 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3540 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3541 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3542 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3543 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3544 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3546 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3547 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3548 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3549 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3550 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3551 updateVisualBits
.SetBit(PLAYER_BYTES
);
3552 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3553 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3554 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3555 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3557 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3558 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3559 updateVisualBits
.SetBit(i
);
3561 // Players visible items are not inventory stuff
3562 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3564 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3567 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3568 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3571 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3573 // item enchantments
3574 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3575 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3577 // random properties
3578 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3579 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3580 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3583 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3586 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3588 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3590 if(m_items
[i
] == NULL
)
3593 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3598 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3600 if(m_items
[i
] == NULL
)
3603 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3605 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3607 if(m_items
[i
] == NULL
)
3610 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3614 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3617 void Player::DestroyForPlayer( Player
*target
) const
3619 Unit::DestroyForPlayer( target
);
3621 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3623 if(m_items
[i
] == NULL
)
3626 m_items
[i
]->DestroyForPlayer( target
);
3631 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3633 if(m_items
[i
] == NULL
)
3636 m_items
[i
]->DestroyForPlayer( target
);
3638 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3640 if(m_items
[i
] == NULL
)
3643 m_items
[i
]->DestroyForPlayer( target
);
3648 bool Player::HasSpell(uint32 spell
) const
3650 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3651 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3652 !itr
->second
->disabled
);
3655 bool Player::HasActiveSpell(uint32 spell
) const
3657 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3658 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3659 itr
->second
->active
&& !itr
->second
->disabled
);
3662 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3665 return TRAINER_SPELL_RED
;
3667 if (!trainer_spell
->learnedSpell
)
3668 return TRAINER_SPELL_RED
;
3671 if(HasSpell(trainer_spell
->learnedSpell
))
3672 return TRAINER_SPELL_GRAY
;
3674 // check race/class requirement
3675 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3676 return TRAINER_SPELL_RED
;
3678 // check level requirement
3679 if(getLevel() < trainer_spell
->reqLevel
)
3680 return TRAINER_SPELL_RED
;
3682 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3684 // check prev.rank requirement
3685 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3686 return TRAINER_SPELL_RED
;
3688 // check additional spell requirement
3689 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3690 return TRAINER_SPELL_RED
;
3693 // check skill requirement
3694 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3695 return TRAINER_SPELL_RED
;
3697 // exist, already checked at loading
3698 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3700 // secondary prof. or not prof. spell
3701 uint32 skill
= spell
->EffectMiscValue
[1];
3703 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3704 return TRAINER_SPELL_GREEN
;
3706 // check primary prof. limit
3707 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3708 return TRAINER_SPELL_RED
;
3710 return TRAINER_SPELL_GREEN
;
3713 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3715 uint32 guid
= GUID_LOPART(playerguid
);
3717 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3718 // bones will be deleted by corpse/bones deleting thread shortly
3719 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3721 // remove from guild
3722 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3725 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3727 guild
->DelMember(guid
);
3730 // remove from arena teams
3731 LeaveAllArenaTeams(playerguid
);
3733 // the player was uninvited already on logout so just remove from group
3734 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3737 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3739 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3742 RemoveFromGroup(group
, playerguid
);
3746 // remove signs from petitions (also remove petitions if owner);
3747 RemovePetitionsAndSigns(playerguid
, 10);
3749 // return back all mails with COD and Item 0 1 2 3 4 5 6
3750 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
);
3755 Field
*fields
= resultMail
->Fetch();
3757 uint32 mail_id
= fields
[0].GetUInt32();
3758 uint16 mailTemplateId
= fields
[1].GetUInt16();
3759 uint32 sender
= fields
[2].GetUInt32();
3760 std::string subject
= fields
[3].GetCppString();
3761 uint32 itemTextId
= fields
[4].GetUInt32();
3762 uint32 money
= fields
[5].GetUInt32();
3763 bool has_items
= fields
[6].GetBool();
3765 //we can return mail now
3766 //so firstly delete the old one
3767 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3772 // data needs to be at first place for Item::LoadFromDB
3773 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
);
3778 Field
*fields2
= resultItems
->Fetch();
3780 uint32 item_guidlow
= fields2
[1].GetUInt32();
3781 uint32 item_template
= fields2
[2].GetUInt32();
3783 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3786 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3790 Item
*pItem
= NewItemOrBag(itemProto
);
3791 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3793 pItem
->FSetState(ITEM_REMOVED
);
3794 pItem
->SaveToDB(); // it also deletes item object !
3798 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3800 while (resultItems
->NextRow());
3806 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3808 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3810 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3812 while (resultMail
->NextRow());
3817 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3818 // Get guids of character's pets, will deleted in transaction
3819 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3821 // NOW we can finally clear other DB data related to character
3822 CharacterDatabase
.BeginTransaction();
3827 Field
*fields3
= resultPets
->Fetch();
3828 uint32 petguidlow
= fields3
[0].GetUInt32();
3829 Pet::DeleteFromDB(petguidlow
);
3830 } while (resultPets
->NextRow());
3834 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3835 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3836 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3837 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3838 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3839 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3840 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3841 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3842 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3843 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3844 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3845 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3846 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3847 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3848 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3849 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3850 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3851 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3852 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3853 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3854 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3855 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3856 CharacterDatabase
.CommitTransaction();
3858 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3859 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3862 void Player::SetMovement(PlayerMovementType pType
)
3867 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3868 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3869 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3870 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3872 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3875 data
.append(GetPackGUID());
3877 GetSession()->SendPacket( &data
);
3881 - a resurrectable corpse must not be loaded for the player (only bones)
3882 - the player must be in world
3884 void Player::BuildPlayerRepop()
3886 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3887 data
.append(GetPackGUID());
3888 GetSession()->SendPacket(&data
);
3890 if(getRace() == RACE_NIGHTELF
)
3891 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)
3892 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3894 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3895 // there must be SMSG.STOP_MIRROR_TIMER
3896 // there we must send 888 opcode
3898 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3901 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3905 // create a corpse and place it at the player's location
3907 Corpse
*corpse
= GetCorpse();
3910 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3913 GetMap()->Add(corpse
);
3915 // convert player body to ghost
3918 SetMovement(MOVE_WATER_WALK
);
3919 if(!GetSession()->isLogingOut())
3920 SetMovement(MOVE_UNROOT
);
3922 // BG - remove insignia related
3923 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3925 SendCorpseReclaimDelay();
3927 // to prevent cheating
3928 corpse
->ResetGhostTime();
3930 StopMirrorTimers(); //disable timers(bars)
3932 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3934 // set and clear other
3935 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3938 void Player::SendDelayResponse(const uint32 ml_seconds
)
3940 //FIXME: is this delay time arg really need? 50msec by default in code
3941 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3942 data
<< (uint32
)time(NULL
);
3944 GetSession()->SendPacket( &data
);
3947 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3949 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3954 GetSession()->SendPacket(&data
);
3956 // speed change, land walk
3958 // remove death flag + set aura
3959 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3960 if(getRace() == RACE_NIGHTELF
)
3961 RemoveAurasDueToSpell(20584); // speed bonuses
3962 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3964 setDeathState(ALIVE
);
3966 SetMovement(MOVE_LAND_WALK
);
3967 SetMovement(MOVE_UNROOT
);
3971 // set health/powers (0- will be set in caller)
3972 if(restore_percent
>0.0f
)
3974 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3975 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3976 SetPower(POWER_RAGE
, 0);
3977 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3980 // trigger update zone for alive state zone updates
3981 uint32 newzone
, newarea
;
3982 GetZoneAndAreaId(newzone
,newarea
);
3983 UpdateZone(newzone
,newarea
);
3985 // update visibility
3986 ObjectAccessor::UpdateVisibilityForPlayer(this);
3991 //Characters from level 1-10 are not affected by resurrection sickness.
3992 //Characters from level 11-19 will suffer from one minute of sickness
3993 //for each level they are above 10.
3994 //Characters level 20 and up suffer from ten minutes of sickness.
3995 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3997 if(int32(getLevel()) >= startLevel
)
3999 // set resurrection sickness
4000 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4002 // not full duration
4003 if(int32(getLevel()) < startLevel
+9)
4005 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4007 for(int i
=0; i
< 3; ++i
)
4009 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
4011 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
4012 Aur
->SendAuraUpdate(false);
4019 void Player::KillPlayer()
4021 SetMovement(MOVE_ROOT
);
4023 StopMirrorTimers(); //disable timers(bars)
4025 setDeathState(CORPSE
);
4026 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4028 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4029 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4031 // 6 minutes until repop at graveyard
4032 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4034 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4036 // don't create corpse at this moment, player might be falling
4038 // update visibility
4039 ObjectAccessor::UpdateObjectVisibility(this);
4042 void Player::CreateCorpse()
4044 // prevent existence 2 corpse for player
4047 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4049 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4052 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4058 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4059 _pb
= GetUInt32Value(PLAYER_BYTES
);
4060 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4062 uint8 race
= (uint8
)(_uf
);
4063 uint8 skin
= (uint8
)(_pb
);
4064 uint8 face
= (uint8
)(_pb
>> 8);
4065 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4066 uint8 haircolor
= (uint8
)(_pb
>> 24);
4067 uint8 facialhair
= (uint8
)(_pb2
);
4069 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4070 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4072 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4073 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4075 uint32 flags
= CORPSE_FLAG_UNK2
;
4076 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4077 flags
|= CORPSE_FLAG_HIDE_HELM
;
4078 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4079 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4080 if(InBattleGround() && !InArena())
4081 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4082 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4084 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4086 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4089 uint16 iIventoryType
;
4091 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
4095 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4096 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
4098 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
4099 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
4103 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4104 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4106 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4109 // register for player, but not show
4110 ObjectAccessor::Instance().AddCorpse(corpse
);
4113 void Player::SpawnCorpseBones()
4115 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4116 SaveToDB(); // prevent loading as ghost without corpse
4119 Corpse
* Player::GetCorpse() const
4121 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4124 void Player::DurabilityLossAll(double percent
, bool inventory
)
4126 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4127 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4128 DurabilityLoss(pItem
,percent
);
4132 // bags not have durability
4133 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4135 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4136 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4137 DurabilityLoss(pItem
,percent
);
4139 // keys not have durability
4140 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4142 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4143 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4144 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4145 if(Item
* pItem
= GetItemByPos( i
, j
))
4146 DurabilityLoss(pItem
,percent
);
4150 void Player::DurabilityLoss(Item
* item
, double percent
)
4155 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4160 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4162 if(pDurabilityLoss
< 1 )
4163 pDurabilityLoss
= 1;
4165 DurabilityPointsLoss(item
,pDurabilityLoss
);
4168 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4170 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4171 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4172 DurabilityPointsLoss(pItem
,points
);
4176 // bags not have durability
4177 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4179 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4180 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4181 DurabilityPointsLoss(pItem
,points
);
4183 // keys not have durability
4184 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4186 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4187 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4188 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4189 if(Item
* pItem
= GetItemByPos( i
, j
))
4190 DurabilityPointsLoss(pItem
,points
);
4194 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4196 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4197 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4198 int32 pNewDurability
= pOldDurability
- points
;
4200 if (pNewDurability
< 0)
4202 else if (pNewDurability
> pMaxDurability
)
4203 pNewDurability
= pMaxDurability
;
4205 if (pOldDurability
!= pNewDurability
)
4207 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4208 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4209 _ApplyItemMods(item
,item
->GetSlot(), false);
4211 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4213 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4214 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4215 _ApplyItemMods(item
,item
->GetSlot(), true);
4217 item
->SetState(ITEM_CHANGED
, this);
4221 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4223 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4224 DurabilityPointsLoss(pItem
,1);
4227 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4229 uint32 TotalCost
= 0;
4230 // equipped, backpack, bags itself
4231 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4232 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4234 // bank, buyback and keys not repaired
4236 // items in inventory bags
4237 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4238 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4239 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4243 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4245 Item
* item
= GetItemByPos(pos
);
4247 uint32 TotalCost
= 0;
4251 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4255 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4259 uint32 LostDurability
= maxDurability
- curDurability
;
4260 if(LostDurability
>0)
4262 ItemPrototype
const *ditemProto
= item
->GetProto();
4264 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4267 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4271 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4272 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4273 if(!dQualitymodEntry
)
4275 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4279 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4280 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4282 costs
= uint32(costs
* discountMod
);
4284 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4289 if (GetGuildId()==0)
4291 DEBUG_LOG("You are not member of a guild");
4295 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4299 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4301 DEBUG_LOG("You do not have rights to withdraw for repairs");
4305 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4307 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4311 if (pGuild
->GetGuildBankMoney() < costs
)
4313 DEBUG_LOG("There is not enough money in bank");
4317 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4320 else if (GetMoney() < costs
)
4322 DEBUG_LOG("You do not have enough money");
4326 ModifyMoney( -int32(costs
) );
4330 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4331 item
->SetState(ITEM_CHANGED
, this);
4333 // reapply mods for total broken and repaired item if equipped
4334 if(IsEquipmentPos(pos
) && !curDurability
)
4335 _ApplyItemMods(item
,pos
& 255, true);
4339 void Player::RepopAtGraveyard()
4341 // note: this can be called also when the player is alive
4342 // for example from WorldSession::HandleMovementOpcodes
4344 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4346 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4347 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4349 ResurrectPlayer(0.5f
);
4353 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4355 // Special handle for battleground maps
4356 if( BattleGround
*bg
= GetBattleGround() )
4357 ClosestGrave
= bg
->GetClosestGraveYard(this);
4359 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4361 // stop countdown until repop
4364 // if no grave found, stay at the current location
4365 // and don't show spirit healer location
4368 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4369 if(isDead()) // not send if alive, because it used in TeleportTo()
4371 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4372 data
<< ClosestGrave
->map_id
;
4373 data
<< ClosestGrave
->x
;
4374 data
<< ClosestGrave
->y
;
4375 data
<< ClosestGrave
->z
;
4376 GetSession()->SendPacket(&data
);
4381 void Player::JoinedChannel(Channel
*c
)
4383 m_channels
.push_back(c
);
4386 void Player::LeftChannel(Channel
*c
)
4388 m_channels
.remove(c
);
4391 void Player::CleanupChannels()
4393 while(!m_channels
.empty())
4395 Channel
* ch
= *m_channels
.begin();
4396 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4397 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4398 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4399 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4402 sLog
.outDebug("Player: channels cleaned up!");
4405 void Player::UpdateLocalChannels(uint32 newZone
)
4407 if(m_channels
.empty())
4410 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4414 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4418 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4420 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4424 // skip non built-in channels
4425 if(!(*i
)->IsConstant())
4428 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4432 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4436 char new_channel_name_buf
[100];
4437 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4438 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4440 if((*i
)!=new_channel
)
4442 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4444 // leave old channel
4445 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4446 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4447 LeftChannel(*i
); // remove from player's channel list
4448 cMgr
->LeftChannel(name
); // delete if empty
4451 sLog
.outDebug("Player: channels cleaned up!");
4454 void Player::LeaveLFGChannel()
4456 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4460 (*i
)->Leave(GetGUID());
4466 void Player::UpdateDefense()
4468 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4470 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4472 // update dependent from defense skill part
4473 UpdateDefenseBonusesMod();
4477 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4479 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4481 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4490 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4493 if(amount
<= -100.0f
)
4496 val
= (100.0f
+ amount
) / 100.0f
;
4497 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4501 if(!CanModifyStats())
4506 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4507 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4508 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4509 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4514 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4516 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4518 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4522 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4525 return m_auraBaseMod
[modGroup
][modType
];
4528 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4530 if(modGroup
>= BASEMOD_END
)
4532 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4536 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4539 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4542 uint32
Player::GetShieldBlockValue() const
4544 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4546 value
= (value
< 0) ? 0 : value
;
4548 return uint32(value
);
4551 float Player::GetMeleeCritFromAgility()
4553 uint32 level
= getLevel();
4554 uint32 pclass
= getClass();
4556 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4558 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4559 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4560 if (critBase
==NULL
|| critRatio
==NULL
)
4563 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4567 float Player::GetDodgeFromAgility()
4569 // Table for base dodge values
4570 float dodge_base
[MAX_CLASSES
] = {
4572 0.00652f
, // Paladin
4579 0.02011f
, // Warlock
4583 // Crit/agility to dodge/agility coefficient multipliers
4584 float crit_to_dodge
[MAX_CLASSES
] = {
4598 uint32 level
= getLevel();
4599 uint32 pclass
= getClass();
4601 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4603 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4604 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4605 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4608 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4609 return dodge
*100.0f
;
4612 float Player::GetSpellCritFromIntellect()
4614 uint32 level
= getLevel();
4615 uint32 pclass
= getClass();
4617 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4619 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4620 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4621 if (critBase
==NULL
|| critRatio
==NULL
)
4624 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4628 float Player::GetRatingCoefficient(CombatRating cr
) const
4630 uint32 level
= getLevel();
4632 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4634 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4636 return 1.0f
; // By default use minimum coefficient (not must be called)
4638 return Rating
->ratio
;
4641 float Player::GetRatingBonusValue(CombatRating cr
) const
4643 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4646 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4648 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.2f
;
4649 if (melee
>33.0f
) melee
= 33.0f
;
4650 return uint32 (melee
* damage
/100.0f
);
4653 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4655 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.2f
;
4656 if (ranged
>33.0f
) ranged
=33.0f
;
4657 return uint32 (ranged
* damage
/100.0f
);
4660 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4662 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.2f
;
4663 // In wow script resilience limited to 33%
4666 return uint32 (spell
* damage
/ 100.0f
);
4669 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4671 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4672 // Dot resilience not limited (limit it by 100%)
4673 if (spellDot
> 100.0f
)
4675 return uint32 (spellDot
* damage
/ 100.0f
);
4678 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4683 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4685 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4692 float Player::OCTRegenHPPerSpirit()
4694 uint32 level
= getLevel();
4695 uint32 pclass
= getClass();
4697 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4699 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4700 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4701 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4704 // Formula from PaperDollFrame script
4705 float spirit
= GetStat(STAT_SPIRIT
);
4706 float baseSpirit
= spirit
;
4707 if (baseSpirit
>50) baseSpirit
= 50;
4708 float moreSpirit
= spirit
- baseSpirit
;
4709 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4713 float Player::OCTRegenMPPerSpirit()
4715 uint32 level
= getLevel();
4716 uint32 pclass
= getClass();
4718 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4720 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4721 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4722 if (moreRatio
==NULL
)
4725 // Formula get from PaperDollFrame script
4726 float spirit
= GetStat(STAT_SPIRIT
);
4727 float regen
= spirit
* moreRatio
->ratio
;
4731 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4733 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4735 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4736 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4737 // stat used stored in miscValueB for this aura
4738 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4739 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4740 if ((*i
)->GetMiscValue() & (1<<cr
))
4741 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4744 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4746 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4747 float RatingChange
= 0.0f
;
4749 bool affectStats
= CanModifyStats();
4753 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4754 case CR_DEFENSE_SKILL
:
4755 UpdateDefenseBonusesMod();
4758 UpdateDodgePercentage();
4761 UpdateParryPercentage();
4764 UpdateBlockPercentage();
4767 UpdateMeleeHitChances();
4770 UpdateRangedHitChances();
4773 UpdateSpellHitChances();
4778 UpdateCritPercentage(BASE_ATTACK
);
4779 UpdateCritPercentage(OFF_ATTACK
);
4782 case CR_CRIT_RANGED
:
4784 UpdateCritPercentage(RANGED_ATTACK
);
4788 UpdateAllSpellCritChances();
4790 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4791 case CR_HIT_TAKEN_RANGED
:
4793 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4795 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4796 case CR_CRIT_TAKEN_RANGED
:
4798 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4800 case CR_HASTE_MELEE
:
4801 RatingChange
= value
/ RatingCoeffecient
;
4802 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4803 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4805 case CR_HASTE_RANGED
:
4806 RatingChange
= value
/ RatingCoeffecient
;
4807 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4809 case CR_HASTE_SPELL
:
4810 RatingChange
= value
/ RatingCoeffecient
;
4811 ApplyCastTimePercentMod(RatingChange
,apply
);
4813 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4814 case CR_WEAPON_SKILL_OFFHAND
:
4815 case CR_WEAPON_SKILL_RANGED
:
4820 UpdateExpertise(BASE_ATTACK
);
4821 UpdateExpertise(OFF_ATTACK
);
4827 void Player::SetRegularAttackTime()
4829 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4831 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4832 if(tmpitem
&& !tmpitem
->IsBroken())
4834 ItemPrototype
const *proto
= tmpitem
->GetProto();
4836 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4838 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4843 //skill+step, checking for max value
4844 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4850 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4851 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4854 if(i
>=PLAYER_MAX_SKILLS
)
4857 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4858 uint32 value
= SKILL_VALUE(data
);
4859 uint32 max
= SKILL_MAX(data
);
4861 if ((!max
) || (!value
) || (value
>= max
))
4864 if (value
*512 < max
*urand(0,512))
4866 uint32 new_value
= value
+step
;
4870 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4871 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
4878 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4880 if ( SkillValue
>= GrayLevel
)
4881 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4882 if ( SkillValue
>= GreenLevel
)
4883 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4884 if ( SkillValue
>= YellowLevel
)
4885 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4886 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4889 bool Player::UpdateCraftSkill(uint32 spellid
)
4891 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4893 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4894 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4896 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4898 if(_spell_idx
->second
->skillId
)
4900 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4902 // Alchemy Discoveries here
4903 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4904 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4906 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4907 learnSpell(discoveredSpell
,false);
4910 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4912 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4913 _spell_idx
->second
->max_value
,
4914 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4915 _spell_idx
->second
->min_value
),
4922 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4924 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4926 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4928 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4931 case SKILL_HERBALISM
:
4932 case SKILL_LOCKPICKING
:
4933 case SKILL_JEWELCRAFTING
:
4934 case SKILL_INSCRIPTION
:
4935 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4936 case SKILL_SKINNING
:
4937 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4938 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4940 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4942 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4943 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4945 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4950 bool Player::UpdateFishingSkill()
4952 sLog
.outDebug("UpdateFishingSkill");
4954 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4956 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4958 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4960 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4963 // levels sync. with spell requirement for skill levels to learn
4964 // bonus abilities in sSkillLineAbilityStore
4965 // Used only to avoid scan DBC at each skill grow
4966 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4968 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4970 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4974 if(Chance
<= 0) // speedup in 0 chance case
4976 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4981 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4982 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4983 if ( i
>= PLAYER_MAX_SKILLS
)
4986 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4987 uint16 SkillValue
= SKILL_VALUE(data
);
4988 uint16 MaxValue
= SKILL_MAX(data
);
4990 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4993 int32 Roll
= irand(1,1000);
4995 if ( Roll
<= Chance
)
4997 uint32 new_value
= SkillValue
+step
;
4998 if(new_value
> MaxValue
)
4999 new_value
= MaxValue
;
5001 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
5002 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5004 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5006 learnSkillRewardedSpells( SkillId
, new_value
);
5010 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5011 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5015 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5019 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5021 // no skill gain in pvp
5022 Unit
*pVictim
= getVictim();
5023 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
5027 return; // always maximized SKILL_FERAL_COMBAT in fact
5029 if(m_form
== FORM_TREE
)
5030 return; // use weapon but not skill up
5032 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5038 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5041 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5042 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5043 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5049 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5051 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5055 UpdateAllCritPercentages();
5058 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5060 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5061 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5062 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5063 if(moblevel
< greylevel
)
5066 if (moblevel
> plevel
+ 5)
5067 moblevel
= plevel
+ 5;
5069 uint32 lvldif
= moblevel
- greylevel
;
5073 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5077 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5080 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5081 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5084 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5086 if(roll_chance_f(chance
))
5091 UpdateWeaponSkill(attType
);
5097 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5099 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5100 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5102 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5103 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5104 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5106 if(talent
) // permanent bonus stored in high part
5107 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5108 else // temporary/item bonus stored in low part
5109 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5114 void Player::UpdateSkillsForLevel()
5116 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5117 uint32 maxSkill
= GetMaxSkillValueForLevel();
5119 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5121 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5122 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5124 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5126 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5130 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5133 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5134 uint32 max
= SKILL_MAX(data
);
5135 uint32 val
= SKILL_VALUE(data
);
5137 /// update only level dependent max skill values
5140 /// miximize skill always
5142 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5143 /// update max skill value if current max skill not maximized
5144 else if(max
!= maxconfskill
)
5145 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5150 void Player::UpdateSkillsToMaxSkillsForLevel()
5152 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5153 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5155 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5156 if( IsProfessionOrRidingSkill(pskill
))
5158 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5160 uint32 max
= SKILL_MAX(data
);
5163 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5165 if(pskill
== SKILL_DEFENSE
)
5166 UpdateDefenseBonusesMod();
5170 // This functions sets a skill line value (and adds if doesn't exist yet)
5171 // To "remove" a skill line, set it's values to zero
5172 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5178 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5179 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5181 if(i
<PLAYER_MAX_SKILLS
) //has skill
5185 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5186 learnSkillRewardedSpells(id
, currVal
);
5187 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5188 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5192 // clear skill fields
5193 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5194 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5195 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5197 // remove all spells that related to this skill
5198 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5199 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5200 if (pAbility
->skillId
==id
)
5201 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5204 else if(currVal
) //add
5206 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5207 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5209 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5212 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5215 // enable unlearn button for primary professions only
5216 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5217 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5219 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5220 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5221 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5222 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5224 // apply skill bonuses
5225 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5227 // temporary bonuses
5228 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5229 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5230 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5231 (*j
)->ApplyModifier(true);
5233 // permanent bonuses
5234 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5235 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5236 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5237 (*j
)->ApplyModifier(true);
5239 // Learn all spells for skill
5240 learnSkillRewardedSpells(id
, currVal
);
5246 bool Player::HasSkill(uint32 skill
) const
5248 if(!skill
)return false;
5249 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5251 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5259 uint16
Player::GetSkillValue(uint32 skill
) const
5264 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5266 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5268 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5270 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5271 result
+= SKILL_TEMP_BONUS(bonus
);
5272 result
+= SKILL_PERM_BONUS(bonus
);
5273 return result
< 0 ? 0 : result
;
5279 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5282 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5284 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5286 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5288 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5289 result
+= SKILL_TEMP_BONUS(bonus
);
5290 result
+= SKILL_PERM_BONUS(bonus
);
5291 return result
< 0 ? 0 : result
;
5297 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5300 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5302 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5304 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5310 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5313 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5315 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5317 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5318 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5319 return result
< 0 ? 0 : result
;
5325 uint16
Player::GetPureSkillValue(uint32 skill
) const
5328 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5330 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5332 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5338 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5343 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5345 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5347 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5354 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5359 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5361 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5363 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5370 void Player::SendInitialActionButtons()
5372 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5374 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5375 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5377 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5378 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5380 data
<< uint16(itr
->second
.action
);
5381 data
<< uint8(itr
->second
.misc
);
5382 data
<< uint8(itr
->second
.type
);
5390 GetSession()->SendPacket( &data
);
5391 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5394 bool Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5396 if(button
>= MAX_ACTION_BUTTONS
)
5398 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5402 // check cheating with adding non-known spells to action bar
5403 if(type
==ACTION_BUTTON_SPELL
)
5405 if(!sSpellStore
.LookupEntry(action
))
5407 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5411 if(!HasSpell(action
))
5413 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5418 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5420 if (buttonItr
==m_actionButtons
.end())
5421 { // just add new button
5422 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5425 { // change state of current button
5426 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5427 buttonItr
->second
= ActionButton(action
,type
,misc
);
5428 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5431 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5435 void Player::removeActionButton(uint8 button
)
5437 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5438 if (buttonItr
==m_actionButtons
.end())
5441 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5442 m_actionButtons
.erase(buttonItr
); // new and not saved
5444 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5446 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5449 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5451 // prevent crash when a bad coord is sent by the client
5452 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5454 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5460 const float old_x
= GetPositionX();
5461 const float old_y
= GetPositionY();
5462 const float old_z
= GetPositionZ();
5463 const float old_r
= GetOrientation();
5465 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5467 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5468 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5470 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5472 // move and update visible state if need
5473 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5475 // reread after Map::Relocation
5482 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5483 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5486 // code block for underwater state update
5487 UpdateUnderwaterState(m
, x
, y
, z
);
5489 CheckExploreSystem();
5494 void Player::SaveRecallPosition()
5496 m_recallMap
= GetMapId();
5497 m_recallX
= GetPositionX();
5498 m_recallY
= GetPositionY();
5499 m_recallZ
= GetPositionZ();
5500 m_recallO
= GetOrientation();
5503 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5505 GetMap()->MessageBroadcast(this, data
, self
);
5508 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5510 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5513 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5515 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5518 void Player::SendDirectMessage(WorldPacket
*data
)
5520 GetSession()->SendPacket(data
);
5523 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5525 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5526 data
<< uint32(CinematicSequenceId
);
5527 SendDirectMessage(&data
);
5530 void Player::SendMovieStart(uint32 MovieId
)
5532 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5533 data
<< uint32(MovieId
);
5534 SendDirectMessage(&data
);
5537 void Player::CheckExploreSystem()
5545 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5546 if(areaFlag
==0xffff)
5548 int offset
= areaFlag
/ 32;
5552 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
);
5556 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5557 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5559 if( !(currFields
& val
) )
5561 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5563 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5565 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5568 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5570 else if(p
->area_level
> 0)
5572 uint32 area
= p
->ID
;
5573 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5575 SendExplorationExperience(area
,0);
5579 int32 diff
= int32(getLevel()) - p
->area_level
;
5583 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5587 int32 exploration_percent
= (100-((diff
-5)*5));
5588 if (exploration_percent
> 100)
5589 exploration_percent
= 100;
5590 else if (exploration_percent
< 0)
5591 exploration_percent
= 0;
5593 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5597 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5601 SendExplorationExperience(area
,XP
);
5603 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5608 uint32
Player::TeamForRace(uint8 race
)
5610 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5613 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5617 switch(rEntry
->TeamID
)
5619 case 7: return ALLIANCE
;
5620 case 1: return HORDE
;
5623 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5627 uint32
Player::getFactionForRace(uint8 race
)
5629 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5632 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5636 return rEntry
->FactionID
;
5639 void Player::setFactionForRace(uint8 race
)
5641 m_team
= TeamForRace(race
);
5642 setFaction( getFactionForRace(race
) );
5645 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5647 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5648 return GetReputationMgr().GetRank(factionEntry
);
5651 //Calculate total reputation percent player gain with quest/creature level
5652 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5654 float percent
= 100.0f
;
5656 float rate
= for_quest
? sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_KILL
);
5658 if(rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
5661 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5663 percent
+= rep
> 0 ? repMod
: -repMod
;
5668 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5671 //Calculates how many reputation points player gains in victim's enemy factions
5672 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5674 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5677 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5682 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5684 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5685 donerep1
= int32(donerep1
*rate
);
5686 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5687 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
5688 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5689 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
5691 // Wiki: Team factions value divided by 2
5692 if (factionEntry1
&& Rep
->is_teamaward1
)
5694 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5695 if(team1_factionEntry
)
5696 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
5700 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5702 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5703 donerep2
= int32(donerep2
*rate
);
5704 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5705 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
5706 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5707 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
5709 // Wiki: Team factions value divided by 2
5710 if (factionEntry2
&& Rep
->is_teamaward2
)
5712 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5713 if(team2_factionEntry
)
5714 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
5719 //Calculate how many reputation points player gain with the quest
5720 void Player::RewardReputation(Quest
const *pQuest
)
5722 // quest reputation reward/loss
5723 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5725 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5727 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
),pQuest
->RewRepValue
[i
],true);
5728 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5730 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
5734 // TODO: implement reputation spillover
5737 void Player::UpdateArenaFields(void)
5739 /* arena calcs go here */
5742 void Player::UpdateHonorFields()
5744 /// called when rewarding honor and at each save
5745 uint64 now
= time(NULL
);
5746 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5748 if(m_lastHonorUpdateTime
< today
)
5750 uint64 yesterday
= today
- DAY
;
5752 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5754 // update yesterday's contribution
5755 if(m_lastHonorUpdateTime
>= yesterday
)
5757 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5759 // this is the first update today, reset today's contribution
5760 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5761 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5765 // no honor/kills yesterday or today, reset
5766 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5767 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5771 m_lastHonorUpdateTime
= now
;
5774 ///Calculate the amount of honor gained based on the victim
5775 ///and the size of the group for which the honor is divided
5776 ///An exact honor value can also be given (overriding the calcs)
5777 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5779 // do not reward honor in arenas, but enable onkill spellproc
5782 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5785 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5791 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5792 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5795 uint64 victim_guid
= 0;
5796 uint32 victim_rank
= 0;
5798 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5799 UpdateHonorFields();
5803 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5806 victim_guid
= uVictim
->GetGUID();
5808 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5810 Player
*pVictim
= (Player
*)uVictim
;
5812 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5815 float f
= 1; //need for total kills (?? need more info)
5817 uint32 k_level
= getLevel();
5818 uint32 v_level
= pVictim
->getLevel();
5821 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5823 // [1..14] Alliance honor titles and player name
5824 // [15..28] Horde honor titles and player name
5825 // [29..38] Other title and player name
5827 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5828 // Get Killer titles, CharTitlesEntry::bit_index
5830 // title[1..14] -> rank[5..18]
5831 // title[15..28] -> rank[5..18]
5832 // title[other] -> 0
5833 if (victim_title
== 0)
5834 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5835 else if (victim_title
< 15)
5836 victim_rank
= victim_title
+ 4;
5837 else if (victim_title
< 29)
5838 victim_rank
= victim_title
- 14 + 4;
5840 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5843 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
5848 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5850 int32 v_rank
=1; //need more info
5852 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5853 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5855 // count the number of playerkills in one day
5856 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5857 // and those in a lifetime
5858 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5859 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
5863 Creature
*cVictim
= (Creature
*)uVictim
;
5865 if (!cVictim
->isRacialLeader())
5868 honor
= 100; // ??? need more info
5869 victim_rank
= 19; // HK: Leader
5873 if (uVictim
!= NULL
)
5875 honor
*= sWorld
.getRate(RATE_HONOR
);
5880 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5883 // honor - for show honor points in log
5884 // victim_guid - for show victim name in log
5885 // victim_rank [1..4] HK: <dishonored rank>
5886 // victim_rank [5..19] HK: <alliance\horde rank>
5887 // victim_rank [0,20+] HK: <>
5888 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5889 data
<< (uint32
) honor
;
5890 data
<< (uint64
) victim_guid
;
5891 data
<< (uint32
) victim_rank
;
5893 GetSession()->SendPacket(&data
);
5896 ModifyHonorPoints(int32(honor
));
5898 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5902 void Player::ModifyHonorPoints( int32 value
)
5906 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5907 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5909 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5912 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5915 void Player::ModifyArenaPoints( int32 value
)
5919 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
5920 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
5922 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
5925 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
5928 uint32
Player::GetGuildIdFromDB(uint64 guid
)
5930 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
5934 uint32 id
= result
->Fetch()[0].GetUInt32();
5939 uint32
Player::GetRankFromDB(uint64 guid
)
5941 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
5944 uint32 v
= result
->Fetch()[0].GetUInt32();
5952 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
5954 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
);
5958 uint32 id
= (*result
)[0].GetUInt32();
5963 uint32
Player::GetZoneIdFromDB(uint64 guid
)
5965 uint32 guidLow
= GUID_LOPART(guid
);
5966 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
5969 Field
* fields
= result
->Fetch();
5970 uint32 zone
= fields
[0].GetUInt32();
5975 // stored zone is zero, use generic and slow zone detection
5976 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
5979 fields
= result
->Fetch();
5980 uint32 map
= fields
[0].GetUInt32();
5981 float posx
= fields
[1].GetFloat();
5982 float posy
= fields
[2].GetFloat();
5983 float posz
= fields
[3].GetFloat();
5986 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
5988 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
5994 void Player::UpdateArea(uint32 newArea
)
5996 // FFA_PVP flags are area and not zone id dependent
5997 // so apply them accordingly
5998 m_areaUpdateId
= newArea
;
6000 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6002 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6005 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6009 // remove ffa flag only if not ffapvp realm
6010 // removal in sanctuaries and capitals is handled in zone update
6011 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6012 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6015 UpdateAreaDependentAuras(newArea
);
6018 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6020 if(m_zoneUpdateId
!= newZone
)
6021 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6023 m_zoneUpdateId
= newZone
;
6024 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6026 // zone changed, so area changed as well, update it
6027 UpdateArea(newArea
);
6029 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6033 if (sWorld
.getConfig(CONFIG_WEATHER
))
6035 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6038 wth
->SendWeatherUpdateToPlayer(this);
6042 if(!sWorld
.AddWeather(zone
->ID
))
6044 // send fine weather packet to remove old zone's weather
6045 Weather::SendFineWeatherUpdateToPlayer(this);
6050 pvpInfo
.inHostileArea
=
6051 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6052 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6053 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6054 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6056 if(pvpInfo
.inHostileArea
) // in hostile area
6058 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6059 UpdatePvP(true, true);
6061 else // in friendly area
6063 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6064 pvpInfo
.endTimer
= time(0); // start toggle-off
6067 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6069 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6070 if(sWorld
.IsFFAPvPRealm())
6071 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6075 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6078 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6080 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6081 SetRestType(REST_TYPE_IN_CITY
);
6082 InnEnter(time(0),GetMapId(),0,0,0);
6084 if(sWorld
.IsFFAPvPRealm())
6085 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6087 else // anywhere else
6089 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6091 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6093 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6095 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6096 SetRestType(REST_TYPE_NO
);
6098 if(sWorld
.IsFFAPvPRealm())
6099 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6102 else // not in tavern (leave city then)
6104 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6105 SetRestType(REST_TYPE_NO
);
6107 // Set player to FFA PVP when not in rested environment.
6108 if(sWorld
.IsFFAPvPRealm())
6109 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6114 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6115 // if player resurrected at teleport this will be applied in resurrect code
6117 DestroyZoneLimitedItem( true, newZone
);
6119 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6120 AutoUnequipOffhandIfNeed();
6122 // recent client version not send leave/join channel packets for built-in local channels
6123 UpdateLocalChannels( newZone
);
6127 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6129 UpdateZoneDependentAuras(newZone
);
6132 //If players are too far way of duel flag... then player loose the duel
6133 void Player::CheckDuelDistance(time_t currTime
)
6138 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6139 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6143 if(duel
->outOfBound
== 0)
6145 if(!IsWithinDistInMap(obj
, 50))
6147 duel
->outOfBound
= currTime
;
6149 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6150 GetSession()->SendPacket(&data
);
6155 if(IsWithinDistInMap(obj
, 40))
6157 duel
->outOfBound
= 0;
6159 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6160 GetSession()->SendPacket(&data
);
6162 else if(currTime
>= (duel
->outOfBound
+10))
6164 DuelComplete(DUEL_FLED
);
6169 void Player::DuelComplete(DuelCompleteType type
)
6171 // duel not requested
6175 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6176 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6177 GetSession()->SendPacket(&data
);
6178 duel
->opponent
->GetSession()->SendPacket(&data
);
6180 if(type
!= DUEL_INTERUPTED
)
6182 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6183 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6184 data
<< duel
->opponent
->GetName();
6186 SendMessageToSet(&data
,true);
6189 // cool-down duel spell
6190 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6197 GetSession()->SendPacket(&data);
6198 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6199 data<<duel->opponent->GetGUID();
6203 duel->opponent->GetSession()->SendPacket(&data);*/
6205 //Remove Duel Flag object
6206 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6208 duel
->initiator
->RemoveGameObject(obj
,true);
6211 std::vector
<uint32
> auras2remove
;
6212 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6213 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6215 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6216 auras2remove
.push_back(i
->second
->GetId());
6219 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6220 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6222 auras2remove
.clear();
6223 AuraMap
const& auras
= GetAuras();
6224 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6226 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6227 auras2remove
.push_back(i
->second
->GetId());
6229 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6230 RemoveAurasDueToSpell(auras2remove
[i
]);
6232 // cleanup combo points
6233 if(GetComboTarget()==duel
->opponent
->GetGUID())
6235 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6238 if(duel
->opponent
->GetComboTarget()==GetGUID())
6239 duel
->opponent
->ClearComboPoints();
6240 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6241 duel
->opponent
->ClearComboPoints();
6244 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6245 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6246 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6247 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6249 delete duel
->opponent
->duel
;
6250 duel
->opponent
->duel
= NULL
;
6255 //---------------------------------------------------------//
6257 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6259 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6262 // not apply/remove mods for broken item
6263 if(item
->IsBroken())
6266 ItemPrototype
const *proto
= item
->GetProto();
6271 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6273 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6274 if(attacktype
< MAX_ATTACK
)
6275 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6277 _ApplyItemBonuses(proto
,slot
,apply
);
6279 if( slot
==EQUIPMENT_SLOT_RANGED
)
6280 _ApplyAmmoBonuses();
6282 ApplyItemEquipSpell(item
,apply
);
6283 ApplyEnchantment(item
, apply
);
6285 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6286 CorrectMetaGemEnchants(slot
, apply
);
6288 sLog
.outDebug("_ApplyItemMods complete.");
6291 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6293 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6296 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6298 uint32 statType
= 0;
6301 if(proto
->ScalingStatDistribution
)
6303 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6305 statType
= ssd
->StatMod
[i
];
6307 if(uint32 modifier
= ssd
->Modifier
[i
])
6309 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6310 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6312 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6313 val
= (multiplier
* modifier
) / 10000;
6320 statType
= proto
->ItemStat
[i
].ItemStatType
;
6321 val
= proto
->ItemStat
[i
].ItemStatValue
;
6330 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6332 case ITEM_MOD_HEALTH
: // modify HP
6333 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6335 case ITEM_MOD_AGILITY
: // modify agility
6336 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6337 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6339 case ITEM_MOD_STRENGTH
: //modify strength
6340 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6341 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6343 case ITEM_MOD_INTELLECT
: //modify intellect
6344 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6345 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6347 case ITEM_MOD_SPIRIT
: //modify spirit
6348 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6349 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6351 case ITEM_MOD_STAMINA
: //modify stamina
6352 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6353 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6355 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6356 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6358 case ITEM_MOD_DODGE_RATING
:
6359 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6361 case ITEM_MOD_PARRY_RATING
:
6362 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6364 case ITEM_MOD_BLOCK_RATING
:
6365 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6367 case ITEM_MOD_HIT_MELEE_RATING
:
6368 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6370 case ITEM_MOD_HIT_RANGED_RATING
:
6371 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6373 case ITEM_MOD_HIT_SPELL_RATING
:
6374 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6376 case ITEM_MOD_CRIT_MELEE_RATING
:
6377 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6379 case ITEM_MOD_CRIT_RANGED_RATING
:
6380 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6382 case ITEM_MOD_CRIT_SPELL_RATING
:
6383 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6385 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6386 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6388 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6389 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6391 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6392 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6394 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6395 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6397 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6398 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6400 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6401 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6403 case ITEM_MOD_HASTE_MELEE_RATING
:
6404 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6406 case ITEM_MOD_HASTE_RANGED_RATING
:
6407 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6409 case ITEM_MOD_HASTE_SPELL_RATING
:
6410 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6412 case ITEM_MOD_HIT_RATING
:
6413 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6414 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6415 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6417 case ITEM_MOD_CRIT_RATING
:
6418 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6419 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6420 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6422 case ITEM_MOD_HIT_TAKEN_RATING
:
6423 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6424 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6425 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6427 case ITEM_MOD_CRIT_TAKEN_RATING
:
6428 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6429 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6430 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6432 case ITEM_MOD_RESILIENCE_RATING
:
6433 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6434 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6435 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6437 case ITEM_MOD_HASTE_RATING
:
6438 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6439 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6440 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6442 case ITEM_MOD_EXPERTISE_RATING
:
6443 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6445 case ITEM_MOD_ATTACK_POWER
:
6446 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6447 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6449 case ITEM_MOD_RANGED_ATTACK_POWER
:
6450 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6452 case ITEM_MOD_FERAL_ATTACK_POWER
:
6453 ApplyFeralAPBonus(int32(val
), apply
);
6455 case ITEM_MOD_SPELL_HEALING_DONE
:
6456 ApplySpellHealingBonus(int32(val
), apply
);
6458 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6459 ApplySpellDamageBonus(int32(val
), apply
);
6461 case ITEM_MOD_MANA_REGENERATION
:
6462 ApplyManaRegenBonus(int32(val
), apply
);
6464 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6465 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6467 case ITEM_MOD_SPELL_POWER
:
6468 ApplySpellHealingBonus(int32(val
), apply
);
6469 ApplySpellDamageBonus(int32(val
), apply
);
6475 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6478 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6481 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6484 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6486 if (proto
->NatureRes
)
6487 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6489 if (proto
->FrostRes
)
6490 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6492 if (proto
->ShadowRes
)
6493 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6495 if (proto
->ArcaneRes
)
6496 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6498 WeaponAttackType attType
= BASE_ATTACK
;
6499 float damage
= 0.0f
;
6501 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6502 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6503 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6505 attType
= RANGED_ATTACK
;
6507 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6509 attType
= OFF_ATTACK
;
6512 if (proto
->Damage
[0].DamageMin
> 0 )
6514 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6515 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6516 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6519 if (proto
->Damage
[0].DamageMax
> 0 )
6521 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6522 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6525 // Druids get feral AP bonus from weapon dps
6526 if(getClass() == CLASS_DRUID
)
6528 int32 feral_bonus
= proto
->getFeralBonus();
6529 if (feral_bonus
> 0)
6530 ApplyFeralAPBonus(feral_bonus
, apply
);
6533 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6538 if(slot
== EQUIPMENT_SLOT_RANGED
)
6539 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6540 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6541 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6542 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6543 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6546 if(CanModifyStats() && (damage
|| proto
->Delay
))
6547 UpdateDamagePhysical(attType
);
6550 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6552 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6553 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6554 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6556 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6557 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6558 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6560 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6561 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6562 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6565 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6567 // generic not weapon specific case processes in aura code
6568 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6571 BaseModGroup mod
= BASEMOD_END
;
6574 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6575 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6576 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6580 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6582 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6586 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6588 // ignore spell mods for not wands
6589 Modifier
const* modifier
= aura
->GetModifier();
6590 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6593 // generic not weapon specific case processes in aura code
6594 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6597 UnitMods unitMod
= UNIT_MOD_END
;
6600 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6601 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6602 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6606 UnitModifierType unitModType
= TOTAL_VALUE
;
6607 switch(modifier
->m_auraname
)
6609 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6610 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6614 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6616 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6620 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6625 ItemPrototype
const *proto
= item
->GetProto();
6629 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6631 _Spell
const& spellData
= proto
->Spells
[i
];
6634 if(!spellData
.SpellId
)
6637 // wrong triggering type
6638 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6641 // check if it is valid spell
6642 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6646 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6650 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6654 // Cannot be used in this stance/form
6655 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
6658 if(form_change
) // check aura active state from other form
6661 for (int k
=0; k
< 3; ++k
)
6663 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6664 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6666 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6676 if(found
) // and skip re-cast already active aura at form change
6680 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6682 CastSpell(this,spellInfo
,true,item
);
6686 if(form_change
) // check aura compatibility
6688 // Cannot be used in this stance/form
6689 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
6690 return; // and remove only not compatible at form change
6694 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6696 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6700 void Player::UpdateEquipSpellsAtFormChange()
6702 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6704 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6706 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6707 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6711 // item set bonuses not dependent from item broken state
6712 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6714 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6718 for(uint32 y
=0;y
<8; ++y
)
6720 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6724 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6725 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6730 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6732 if(!item
|| item
->IsBroken())
6735 ItemPrototype
const *proto
= item
->GetProto();
6739 if (!Target
|| Target
== this )
6742 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6744 _Spell
const& spellData
= proto
->Spells
[i
];
6747 if(!spellData
.SpellId
)
6750 // wrong triggering type
6751 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6754 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6757 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6761 // not allow proc extra attack spell at extra attack
6762 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6765 float chance
= spellInfo
->procChance
;
6767 if(spellData
.SpellPPMRate
)
6769 uint32 WeaponSpeed
= GetAttackTime(attType
);
6770 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6772 else if(chance
> 100.0f
)
6774 chance
= GetWeaponProcChance();
6777 if (roll_chance_f(chance
))
6778 CastSpell(Target
, spellInfo
->Id
, true, item
);
6781 // item combat enchantments
6782 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6784 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6785 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6786 if(!pEnchant
) continue;
6787 for (int s
=0;s
<3;s
++)
6789 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6792 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6795 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6799 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6800 if (roll_chance_f(chance
))
6802 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6803 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6805 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6811 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
6813 ItemPrototype
const* proto
= item
->GetProto();
6814 // special learning case
6815 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
6817 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
6818 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
6820 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
6823 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
6824 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
6828 Spell
*spell
= new Spell(this, spellInfo
, false);
6829 spell
->m_CastItem
= item
;
6830 spell
->m_cast_count
= cast_count
; //set count of casts
6831 spell
->m_currentBasePoints
[0] = learning_spell_id
;
6832 spell
->prepare(&targets
);
6836 // use triggered flag only for items with many spell casts and for not first cast
6839 // item spells casted at use
6840 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6842 _Spell
const& spellData
= proto
->Spells
[i
];
6845 if(!spellData
.SpellId
)
6848 // wrong triggering type
6849 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
6852 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6855 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
6859 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6860 spell
->m_CastItem
= item
;
6861 spell
->m_cast_count
= cast_count
; // set count of casts
6862 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6863 spell
->prepare(&targets
);
6868 // Item enchantments spells casted at use
6869 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6871 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6872 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6873 if(!pEnchant
) continue;
6874 for (int s
=0;s
<3;s
++)
6876 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
6879 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6882 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6886 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6887 spell
->m_CastItem
= item
;
6888 spell
->m_cast_count
= cast_count
; // set count of casts
6889 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6890 spell
->prepare(&targets
);
6897 void Player::_RemoveAllItemMods()
6899 sLog
.outDebug("_RemoveAllItemMods start.");
6901 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6905 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6909 // item set bonuses not dependent from item broken state
6911 RemoveItemsSetItem(this,proto
);
6913 if(m_items
[i
]->IsBroken())
6916 ApplyItemEquipSpell(m_items
[i
],false);
6917 ApplyEnchantment(m_items
[i
], false);
6921 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6925 if(m_items
[i
]->IsBroken())
6927 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6931 uint32 attacktype
= Player::GetAttackBySlot(i
);
6932 if(attacktype
< MAX_ATTACK
)
6933 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6935 _ApplyItemBonuses(proto
,i
, false);
6937 if( i
== EQUIPMENT_SLOT_RANGED
)
6938 _ApplyAmmoBonuses();
6942 sLog
.outDebug("_RemoveAllItemMods complete.");
6945 void Player::_ApplyAllItemMods()
6947 sLog
.outDebug("_ApplyAllItemMods start.");
6949 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6953 if(m_items
[i
]->IsBroken())
6956 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6960 uint32 attacktype
= Player::GetAttackBySlot(i
);
6961 if(attacktype
< MAX_ATTACK
)
6962 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6964 _ApplyItemBonuses(proto
,i
, true);
6966 if( i
== EQUIPMENT_SLOT_RANGED
)
6967 _ApplyAmmoBonuses();
6971 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6975 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6979 // item set bonuses not dependent from item broken state
6981 AddItemsSetItem(this,m_items
[i
]);
6983 if(m_items
[i
]->IsBroken())
6986 ApplyItemEquipSpell(m_items
[i
],true);
6987 ApplyEnchantment(m_items
[i
], true);
6991 sLog
.outDebug("_ApplyAllItemMods complete.");
6994 void Player::_ApplyAmmoBonuses()
6997 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7001 float currentAmmoDPS
;
7003 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7004 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7005 currentAmmoDPS
= 0.0f
;
7007 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7009 if(currentAmmoDPS
== GetAmmoDPS())
7012 m_ammoDPS
= currentAmmoDPS
;
7014 if(CanModifyStats())
7015 UpdateDamagePhysical(RANGED_ATTACK
);
7018 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7023 // check ranged weapon
7024 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7025 if(!weapon
|| weapon
->IsBroken() )
7028 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7029 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7032 // check ammo ws. weapon compatibility
7033 switch(weapon_proto
->SubClass
)
7035 case ITEM_SUBCLASS_WEAPON_BOW
:
7036 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7037 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7040 case ITEM_SUBCLASS_WEAPON_GUN
:
7041 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7051 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7052 Called by remove insignia spell effect */
7053 void Player::RemovedInsignia(Player
* looterPlr
)
7055 if (!GetBattleGroundId())
7058 // If not released spirit, do it !
7059 if(m_deathTimer
> 0)
7066 Corpse
*corpse
= GetCorpse();
7070 // We have to convert player corpse to bones, not to be able to resurrect there
7071 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7072 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7076 // Now we must make bones lootable, and send player loot
7077 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7079 // We store the level of our player in the gold field
7080 // We retrieve this information at Player::SendLoot()
7081 bones
->loot
.gold
= getLevel();
7082 bones
->lootRecipient
= looterPlr
;
7083 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7092 void Player::SendLootRelease( uint64 guid
)
7094 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7095 data
<< uint64(guid
) << uint8(1);
7096 SendDirectMessage( &data
);
7099 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7101 if (uint64 lguid
= GetLootGUID())
7102 m_session
->DoLootRelease(lguid
);
7105 PermissionTypes permission
= ALL_PERMISSION
;
7107 sLog
.outDebug("Player::SendLoot");
7108 if (IS_GAMEOBJECT_GUID(guid
))
7110 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7111 GameObject
*go
= GetMap()->GetGameObject(guid
);
7113 // not check distance for GO in case owned GO (fishing bobber case, for example)
7114 // And permit out of range GO with no owner in case fishing hole
7115 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7117 SendLootRelease(guid
);
7123 if(go
->getLootState() == GO_READY
)
7125 uint32 lootid
= go
->GetLootId();
7129 sLog
.outDebug(" if(lootid)");
7131 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7134 if(loot_type
== LOOT_FISHING
)
7135 go
->getFishLoot(loot
,this);
7137 go
->SetLootState(GO_ACTIVATED
);
7140 else if (IS_ITEM_GUID(guid
))
7142 Item
*item
= GetItemByGuid( guid
);
7146 SendLootRelease(guid
);
7150 if(loot_type
== LOOT_DISENCHANTING
)
7154 if(!item
->m_lootGenerated
)
7156 item
->m_lootGenerated
= true;
7158 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7161 else if(loot_type
== LOOT_PROSPECTING
)
7165 if(!item
->m_lootGenerated
)
7167 item
->m_lootGenerated
= true;
7169 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7172 else if(loot_type
== LOOT_MILLING
)
7176 if(!item
->m_lootGenerated
)
7178 item
->m_lootGenerated
= true;
7180 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7187 if(!item
->m_lootGenerated
)
7189 item
->m_lootGenerated
= true;
7191 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7193 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_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7344 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7345 loot_type
= LOOT_SKINNING
;
7347 if(loot_type
== LOOT_FISHINGHOLE
)
7348 loot_type
= LOOT_FISHING
;
7350 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7352 data
<< uint64(guid
);
7353 data
<< uint8(loot_type
);
7354 data
<< LootView(*loot
, this, permission
);
7356 SendDirectMessage(&data
);
7358 // add 'this' player as one of the players that are looting 'loot'
7359 if (permission
!= NONE_PERMISSION
)
7360 loot
->AddLooter(GetGUID());
7362 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7363 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7366 void Player::SendNotifyLootMoneyRemoved()
7368 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7369 GetSession()->SendPacket( &data
);
7372 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7374 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7375 data
<< uint8(lootSlot
);
7376 GetSession()->SendPacket( &data
);
7379 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7381 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7384 GetSession()->SendPacket(&data
);
7387 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7389 // data depends on zoneid/mapid...
7390 BattleGround
* bg
= GetBattleGround();
7391 uint16 NumberOfFields
= 0;
7392 uint32 mapid
= GetMapId();
7394 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7396 // may be exist better way to do this...
7419 NumberOfFields
= 41;
7422 NumberOfFields
= 15;
7425 NumberOfFields
= 83;
7428 NumberOfFields
= 16;
7432 NumberOfFields
= 40;
7435 NumberOfFields
= 27;
7438 NumberOfFields
= 39;
7441 NumberOfFields
= 38;
7444 NumberOfFields
= 37;
7449 NumberOfFields
= 11;
7452 NumberOfFields
= 11;
7455 NumberOfFields
= 12;
7459 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7460 data
<< uint32(mapid
); // mapid
7461 data
<< uint32(zoneid
); // zone id
7462 data
<< uint32(areaid
); // area id, new 2.1.0
7463 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7464 data
<< uint32(0x8d8) << uint32(0x0); // 1
7465 data
<< uint32(0x8d7) << uint32(0x0); // 2
7466 data
<< uint32(0x8d6) << uint32(0x0); // 3
7467 data
<< uint32(0x8d5) << uint32(0x0); // 4
7468 data
<< uint32(0x8d4) << uint32(0x0); // 5
7469 data
<< uint32(0x8d3) << uint32(0x0); // 6
7470 // 7 1 - Arena season in progress, 0 - end of season
7471 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7472 // 8 Arena season id
7473 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7474 if(mapid
== 530) // Outland
7476 data
<< uint32(0x9bf) << uint32(0x0); // 7
7477 data
<< uint32(0x9bd) << uint32(0xF); // 8
7478 data
<< uint32(0x9bb) << uint32(0xF); // 9
7493 data
<< uint32(0x7ae) << uint32(0x1); // 7
7494 data
<< uint32(0x532) << uint32(0x1); // 8
7495 data
<< uint32(0x531) << uint32(0x0); // 9
7496 data
<< uint32(0x52e) << uint32(0x0); // 10
7497 data
<< uint32(0x571) << uint32(0x0); // 11
7498 data
<< uint32(0x570) << uint32(0x0); // 12
7499 data
<< uint32(0x567) << uint32(0x1); // 13
7500 data
<< uint32(0x566) << uint32(0x1); // 14
7501 data
<< uint32(0x550) << uint32(0x1); // 15
7502 data
<< uint32(0x544) << uint32(0x0); // 16
7503 data
<< uint32(0x536) << uint32(0x0); // 17
7504 data
<< uint32(0x535) << uint32(0x1); // 18
7505 data
<< uint32(0x518) << uint32(0x0); // 19
7506 data
<< uint32(0x517) << uint32(0x0); // 20
7507 data
<< uint32(0x574) << uint32(0x0); // 21
7508 data
<< uint32(0x573) << uint32(0x0); // 22
7509 data
<< uint32(0x572) << uint32(0x0); // 23
7510 data
<< uint32(0x56f) << uint32(0x0); // 24
7511 data
<< uint32(0x56e) << uint32(0x0); // 25
7512 data
<< uint32(0x56d) << uint32(0x0); // 26
7513 data
<< uint32(0x56c) << uint32(0x0); // 27
7514 data
<< uint32(0x56b) << uint32(0x0); // 28
7515 data
<< uint32(0x56a) << uint32(0x1); // 29
7516 data
<< uint32(0x569) << uint32(0x1); // 30
7517 data
<< uint32(0x568) << uint32(0x1); // 13
7518 data
<< uint32(0x565) << uint32(0x0); // 32
7519 data
<< uint32(0x564) << uint32(0x0); // 33
7520 data
<< uint32(0x563) << uint32(0x0); // 34
7521 data
<< uint32(0x562) << uint32(0x0); // 35
7522 data
<< uint32(0x561) << uint32(0x0); // 36
7523 data
<< uint32(0x560) << uint32(0x0); // 37
7524 data
<< uint32(0x55f) << uint32(0x0); // 38
7525 data
<< uint32(0x55e) << uint32(0x0); // 39
7526 data
<< uint32(0x55d) << uint32(0x0); // 40
7527 data
<< uint32(0x3c6) << uint32(0x4); // 41
7528 data
<< uint32(0x3c4) << uint32(0x6); // 42
7529 data
<< uint32(0x3c2) << uint32(0x4); // 43
7530 data
<< uint32(0x516) << uint32(0x1); // 44
7531 data
<< uint32(0x515) << uint32(0x0); // 45
7532 data
<< uint32(0x3b6) << uint32(0x6); // 46
7533 data
<< uint32(0x55c) << uint32(0x0); // 47
7534 data
<< uint32(0x55b) << uint32(0x0); // 48
7535 data
<< uint32(0x55a) << uint32(0x0); // 49
7536 data
<< uint32(0x559) << uint32(0x0); // 50
7537 data
<< uint32(0x558) << uint32(0x0); // 51
7538 data
<< uint32(0x557) << uint32(0x0); // 52
7539 data
<< uint32(0x556) << uint32(0x0); // 53
7540 data
<< uint32(0x555) << uint32(0x0); // 54
7541 data
<< uint32(0x554) << uint32(0x1); // 55
7542 data
<< uint32(0x553) << uint32(0x1); // 56
7543 data
<< uint32(0x552) << uint32(0x1); // 57
7544 data
<< uint32(0x551) << uint32(0x1); // 58
7545 data
<< uint32(0x54f) << uint32(0x0); // 59
7546 data
<< uint32(0x54e) << uint32(0x0); // 60
7547 data
<< uint32(0x54d) << uint32(0x1); // 61
7548 data
<< uint32(0x54c) << uint32(0x0); // 62
7549 data
<< uint32(0x54b) << uint32(0x0); // 63
7550 data
<< uint32(0x545) << uint32(0x0); // 64
7551 data
<< uint32(0x543) << uint32(0x1); // 65
7552 data
<< uint32(0x542) << uint32(0x0); // 66
7553 data
<< uint32(0x540) << uint32(0x0); // 67
7554 data
<< uint32(0x53f) << uint32(0x0); // 68
7555 data
<< uint32(0x53e) << uint32(0x0); // 69
7556 data
<< uint32(0x53d) << uint32(0x0); // 70
7557 data
<< uint32(0x53c) << uint32(0x0); // 71
7558 data
<< uint32(0x53b) << uint32(0x0); // 72
7559 data
<< uint32(0x53a) << uint32(0x1); // 73
7560 data
<< uint32(0x539) << uint32(0x0); // 74
7561 data
<< uint32(0x538) << uint32(0x0); // 75
7562 data
<< uint32(0x537) << uint32(0x0); // 76
7563 data
<< uint32(0x534) << uint32(0x0); // 77
7564 data
<< uint32(0x533) << uint32(0x0); // 78
7565 data
<< uint32(0x530) << uint32(0x0); // 79
7566 data
<< uint32(0x52f) << uint32(0x0); // 80
7567 data
<< uint32(0x52d) << uint32(0x1); // 81
7570 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7571 bg
->FillInitialWorldStates(data
);
7574 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7575 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7576 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7577 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7578 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7579 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7580 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7581 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7585 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7586 bg
->FillInitialWorldStates(data
);
7589 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7590 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7591 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7592 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7593 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7594 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7595 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7596 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7597 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7598 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7599 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7600 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7601 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7602 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7603 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7604 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7605 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7606 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7607 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7608 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7609 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7610 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7611 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7612 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7613 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7614 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7615 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7616 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7617 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7618 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7619 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7620 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7624 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7625 bg
->FillInitialWorldStates(data
);
7628 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7629 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7630 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7631 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7632 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7633 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7634 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7635 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7636 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7637 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7638 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7639 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7640 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7641 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7642 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7643 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7644 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7645 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7646 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7647 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7648 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7649 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7650 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7651 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7652 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7653 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7654 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7655 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7656 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7657 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7658 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7659 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7660 // and some more ... unknown
7663 case 3483: // Hellfire Peninsula
7664 data
<< uint32(0x9ba) << uint32(0x1); // 10
7665 data
<< uint32(0x9b9) << uint32(0x1); // 11
7666 data
<< uint32(0x9b5) << uint32(0x0); // 12
7667 data
<< uint32(0x9b4) << uint32(0x1); // 13
7668 data
<< uint32(0x9b3) << uint32(0x0); // 14
7669 data
<< uint32(0x9b2) << uint32(0x0); // 15
7670 data
<< uint32(0x9b1) << uint32(0x1); // 16
7671 data
<< uint32(0x9b0) << uint32(0x0); // 17
7672 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7673 data
<< uint32(0x9ac) << uint32(0x0); // 19
7674 data
<< uint32(0x9a8) << uint32(0x0); // 20
7675 data
<< uint32(0x9a7) << uint32(0x0); // 21
7676 data
<< uint32(0x9a6) << uint32(0x1); // 22
7678 case 3519: // Terokkar Forest
7679 data
<< uint32(0xa41) << uint32(0x0); // 10
7680 data
<< uint32(0xa40) << uint32(0x14); // 11
7681 data
<< uint32(0xa3f) << uint32(0x0); // 12
7682 data
<< uint32(0xa3e) << uint32(0x0); // 13
7683 data
<< uint32(0xa3d) << uint32(0x5); // 14
7684 data
<< uint32(0xa3c) << uint32(0x0); // 15
7685 data
<< uint32(0xa87) << uint32(0x0); // 16
7686 data
<< uint32(0xa86) << uint32(0x0); // 17
7687 data
<< uint32(0xa85) << uint32(0x0); // 18
7688 data
<< uint32(0xa84) << uint32(0x0); // 19
7689 data
<< uint32(0xa83) << uint32(0x0); // 20
7690 data
<< uint32(0xa82) << uint32(0x0); // 21
7691 data
<< uint32(0xa81) << uint32(0x0); // 22
7692 data
<< uint32(0xa80) << uint32(0x0); // 23
7693 data
<< uint32(0xa7e) << uint32(0x0); // 24
7694 data
<< uint32(0xa7d) << uint32(0x0); // 25
7695 data
<< uint32(0xa7c) << uint32(0x0); // 26
7696 data
<< uint32(0xa7b) << uint32(0x0); // 27
7697 data
<< uint32(0xa7a) << uint32(0x0); // 28
7698 data
<< uint32(0xa79) << uint32(0x0); // 29
7699 data
<< uint32(0x9d0) << uint32(0x5); // 30
7700 data
<< uint32(0x9ce) << uint32(0x0); // 31
7701 data
<< uint32(0x9cd) << uint32(0x0); // 32
7702 data
<< uint32(0x9cc) << uint32(0x0); // 33
7703 data
<< uint32(0xa88) << uint32(0x0); // 34
7704 data
<< uint32(0xad0) << uint32(0x0); // 35
7705 data
<< uint32(0xacf) << uint32(0x1); // 36
7707 case 3521: // Zangarmarsh
7708 data
<< uint32(0x9e1) << uint32(0x0); // 10
7709 data
<< uint32(0x9e0) << uint32(0x0); // 11
7710 data
<< uint32(0x9df) << uint32(0x0); // 12
7711 data
<< uint32(0xa5d) << uint32(0x1); // 13
7712 data
<< uint32(0xa5c) << uint32(0x0); // 14
7713 data
<< uint32(0xa5b) << uint32(0x1); // 15
7714 data
<< uint32(0xa5a) << uint32(0x0); // 16
7715 data
<< uint32(0xa59) << uint32(0x1); // 17
7716 data
<< uint32(0xa58) << uint32(0x0); // 18
7717 data
<< uint32(0xa57) << uint32(0x0); // 19
7718 data
<< uint32(0xa56) << uint32(0x0); // 20
7719 data
<< uint32(0xa55) << uint32(0x1); // 21
7720 data
<< uint32(0xa54) << uint32(0x0); // 22
7721 data
<< uint32(0x9e7) << uint32(0x0); // 23
7722 data
<< uint32(0x9e6) << uint32(0x0); // 24
7723 data
<< uint32(0x9e5) << uint32(0x0); // 25
7724 data
<< uint32(0xa00) << uint32(0x0); // 26
7725 data
<< uint32(0x9ff) << uint32(0x1); // 27
7726 data
<< uint32(0x9fe) << uint32(0x0); // 28
7727 data
<< uint32(0x9fd) << uint32(0x0); // 29
7728 data
<< uint32(0x9fc) << uint32(0x1); // 30
7729 data
<< uint32(0x9fb) << uint32(0x0); // 31
7730 data
<< uint32(0xa62) << uint32(0x0); // 32
7731 data
<< uint32(0xa61) << uint32(0x1); // 33
7732 data
<< uint32(0xa60) << uint32(0x1); // 34
7733 data
<< uint32(0xa5f) << uint32(0x0); // 35
7735 case 3698: // Nagrand Arena
7736 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
7737 bg
->FillInitialWorldStates(data
);
7740 data
<< uint32(0xa0f) << uint32(0x0); // 7
7741 data
<< uint32(0xa10) << uint32(0x0); // 8
7742 data
<< uint32(0xa11) << uint32(0x0); // 9 show
7745 case 3702: // Blade's Edge Arena
7746 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
7747 bg
->FillInitialWorldStates(data
);
7750 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
7751 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
7752 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
7755 case 3968: // Ruins of Lordaeron
7756 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
7757 bg
->FillInitialWorldStates(data
);
7760 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
7761 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
7762 data
<< uint32(0xbba) << uint32(0x0); // 9 show
7765 case 3703: // Shattrath City
7768 data
<< uint32(0x914) << uint32(0x0); // 7
7769 data
<< uint32(0x913) << uint32(0x0); // 8
7770 data
<< uint32(0x912) << uint32(0x0); // 9
7771 data
<< uint32(0x915) << uint32(0x0); // 10
7774 GetSession()->SendPacket(&data
);
7777 uint32
Player::GetXPRestBonus(uint32 xp
)
7779 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7781 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7784 SetRestBonus( GetRestBonus() - rested_bonus
);
7786 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7787 return rested_bonus
;
7790 void Player::SetBindPoint(uint64 guid
)
7792 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7793 data
<< uint64(guid
);
7794 GetSession()->SendPacket( &data
);
7797 void Player::SendTalentWipeConfirm(uint64 guid
)
7799 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7800 data
<< uint64(guid
);
7801 data
<< uint32(resetTalentsCost());
7802 GetSession()->SendPacket( &data
);
7805 void Player::SendPetSkillWipeConfirm()
7807 Pet
* pet
= GetPet();
7810 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7811 data
<< pet
->GetGUID();
7812 data
<< uint32(pet
->resetTalentsCost());
7813 GetSession()->SendPacket( &data
);
7816 /*********************************************************/
7817 /*** STORAGE SYSTEM ***/
7818 /*********************************************************/
7820 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7825 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7827 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7831 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7832 else if(charges
<= 1)
7834 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7835 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7840 void Player::SetSheath( uint32 sheathed
)
7844 case SHEATH_STATE_UNARMED
: // no prepared weapon
7845 SetVirtualItemSlot(0,NULL
);
7846 SetVirtualItemSlot(1,NULL
);
7847 SetVirtualItemSlot(2,NULL
);
7849 case SHEATH_STATE_MELEE
: // prepared melee weapon
7851 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7852 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7853 SetVirtualItemSlot(2,NULL
);
7855 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7856 SetVirtualItemSlot(0,NULL
);
7857 SetVirtualItemSlot(1,NULL
);
7858 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7861 SetVirtualItemSlot(0,NULL
);
7862 SetVirtualItemSlot(1,NULL
);
7863 SetVirtualItemSlot(2,NULL
);
7866 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7869 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7871 uint8 pClass
= getClass();
7874 slots
[0] = NULL_SLOT
;
7875 slots
[1] = NULL_SLOT
;
7876 slots
[2] = NULL_SLOT
;
7877 slots
[3] = NULL_SLOT
;
7878 switch( proto
->InventoryType
)
7881 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7884 slots
[0] = EQUIPMENT_SLOT_NECK
;
7886 case INVTYPE_SHOULDERS
:
7887 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7890 slots
[0] = EQUIPMENT_SLOT_BODY
;
7893 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7896 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7899 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7902 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7905 slots
[0] = EQUIPMENT_SLOT_FEET
;
7907 case INVTYPE_WRISTS
:
7908 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7911 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7913 case INVTYPE_FINGER
:
7914 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7915 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7917 case INVTYPE_TRINKET
:
7918 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7919 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7922 slots
[0] = EQUIPMENT_SLOT_BACK
;
7924 case INVTYPE_WEAPON
:
7926 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7928 // suggest offhand slot only if know dual wielding
7929 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7931 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7934 case INVTYPE_SHIELD
:
7935 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7937 case INVTYPE_RANGED
:
7938 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7940 case INVTYPE_2HWEAPON
:
7941 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7942 if (CanDualWield() && CanTitanGrip())
7943 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7945 case INVTYPE_TABARD
:
7946 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7948 case INVTYPE_WEAPONMAINHAND
:
7949 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7951 case INVTYPE_WEAPONOFFHAND
:
7952 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7954 case INVTYPE_HOLDABLE
:
7955 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7957 case INVTYPE_THROWN
:
7958 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7960 case INVTYPE_RANGEDRIGHT
:
7961 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7964 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
7965 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
7966 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
7967 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
7971 switch(proto
->SubClass
)
7973 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7974 if (pClass
== CLASS_PALADIN
)
7975 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7977 case ITEM_SUBCLASS_ARMOR_IDOL
:
7978 if (pClass
== CLASS_DRUID
)
7979 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7981 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7982 if (pClass
== CLASS_SHAMAN
)
7983 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7985 case ITEM_SUBCLASS_ARMOR_MISC
:
7986 if (pClass
== CLASS_WARLOCK
)
7987 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7989 case ITEM_SUBCLASS_ARMOR_SIGIL
:
7990 if (pClass
== CLASS_DEATH_KNIGHT
)
7991 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8000 if( slot
!= NULL_SLOT
)
8002 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8004 for (int i
= 0; i
< 4; i
++)
8006 if ( slots
[i
] == slot
)
8013 // search free slot at first
8014 for (int i
= 0; i
< 4; i
++)
8016 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8018 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8019 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8024 // if not found free and can swap return first appropriate from used
8025 for (int i
= 0; i
< 4; i
++)
8027 if ( slots
[i
] != NULL_SLOT
&& swap
)
8036 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8039 uint32 tempcount
= 0;
8041 uint8 res
= EQUIP_ERR_OK
;
8043 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8045 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8046 if( pItem
&& pItem
->GetEntry() == item
)
8048 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8049 if(ires
==EQUIP_ERR_OK
)
8051 tempcount
+= pItem
->GetCount();
8052 if( tempcount
>= count
)
8053 return EQUIP_ERR_OK
;
8059 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8061 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8062 if( pItem
&& pItem
->GetEntry() == item
)
8064 tempcount
+= pItem
->GetCount();
8065 if( tempcount
>= count
)
8066 return EQUIP_ERR_OK
;
8069 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8071 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8072 if( pItem
&& pItem
->GetEntry() == item
)
8074 tempcount
+= pItem
->GetCount();
8075 if( tempcount
>= count
)
8076 return EQUIP_ERR_OK
;
8080 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8082 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8085 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8087 pItem
= GetItemByPos( i
, j
);
8088 if( pItem
&& pItem
->GetEntry() == item
)
8090 tempcount
+= pItem
->GetCount();
8091 if( tempcount
>= count
)
8092 return EQUIP_ERR_OK
;
8098 // not found req. item count and have unequippable items
8102 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8105 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8107 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8108 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8109 count
+= pItem
->GetCount();
8111 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8113 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8114 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8115 count
+= pItem
->GetCount();
8117 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8119 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8121 count
+= pBag
->GetItemCount(item
,skipItem
);
8124 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8126 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8128 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8129 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8130 count
+= pItem
->GetGemCountWithID(item
);
8136 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8138 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8139 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8140 count
+= pItem
->GetCount();
8142 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8144 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8146 count
+= pBag
->GetItemCount(item
,skipItem
);
8149 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8151 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8153 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8154 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8155 count
+= pItem
->GetGemCountWithID(item
);
8163 Item
* Player::GetItemByGuid( uint64 guid
) const
8165 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8167 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8168 if( pItem
&& pItem
->GetGUID() == guid
)
8171 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8173 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8174 if( pItem
&& pItem
->GetGUID() == guid
)
8178 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8180 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8183 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8185 Item
* pItem
= pBag
->GetItemByPos( j
);
8186 if( pItem
&& pItem
->GetGUID() == guid
)
8191 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8193 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8196 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8198 Item
* pItem
= pBag
->GetItemByPos( j
);
8199 if( pItem
&& pItem
->GetGUID() == guid
)
8208 Item
* Player::GetItemByPos( uint16 pos
) const
8210 uint8 bag
= pos
>> 8;
8211 uint8 slot
= pos
& 255;
8212 return GetItemByPos( bag
, slot
);
8215 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8217 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8218 return m_items
[slot
];
8219 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8220 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8222 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8224 return pBag
->GetItemByPos(slot
);
8229 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8234 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8235 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8236 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8237 default: return NULL
;
8240 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8241 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8247 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8253 Item
* Player::GetShield(bool useable
) const
8255 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8256 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8262 if( item
->IsBroken())
8268 uint32
Player::GetAttackBySlot( uint8 slot
)
8272 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8273 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8274 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8275 default: return MAX_ATTACK
;
8279 bool Player::HasBankBagSlot( uint8 slot
) const
8281 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8282 if( slot
< maxslot
)
8287 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8289 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8291 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8293 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8295 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8300 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8302 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8304 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8309 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8311 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8313 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8315 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8320 bool Player::IsBagPos( uint16 pos
)
8322 uint8 bag
= pos
>> 8;
8323 uint8 slot
= pos
& 255;
8324 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8326 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8331 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8337 if (bag
== INVENTORY_SLOT_BAG_0
)
8339 // any post selected
8340 if (slot
== NULL_SLOT
)
8344 if (slot
< EQUIPMENT_SLOT_END
)
8348 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8352 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8356 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8360 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8364 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8370 // bag content slots
8371 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8373 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8377 // any post selected
8378 if (slot
== NULL_SLOT
)
8381 return slot
< pBag
->GetBagSize();
8384 // bank bag content slots
8385 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8387 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8391 // any post selected
8392 if (slot
== NULL_SLOT
)
8395 return slot
< pBag
->GetBagSize();
8403 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8405 uint32 tempcount
= 0;
8406 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8408 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8409 if( pItem
&& pItem
->GetEntry() == item
)
8411 tempcount
+= pItem
->GetCount();
8412 if( tempcount
>= count
)
8416 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8418 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8419 if( pItem
&& pItem
->GetEntry() == item
)
8421 tempcount
+= pItem
->GetCount();
8422 if( tempcount
>= count
)
8426 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8428 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8430 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8432 Item
* pItem
= GetItemByPos( i
, j
);
8433 if( pItem
&& pItem
->GetEntry() == item
)
8435 tempcount
+= pItem
->GetCount();
8436 if( tempcount
>= count
)
8445 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8447 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8448 if( pItem
&& pItem
->GetEntry() == item
)
8450 tempcount
+= pItem
->GetCount();
8451 if( tempcount
>= count
)
8455 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8457 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8459 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8461 Item
* pItem
= GetItemByPos( i
, j
);
8462 if( pItem
&& pItem
->GetEntry() == item
)
8464 tempcount
+= pItem
->GetCount();
8465 if( tempcount
>= count
)
8476 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8478 uint32 tempcount
= 0;
8479 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8481 if(i
==int(except_slot
))
8484 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8485 if( pItem
&& pItem
->GetEntry() == item
)
8487 tempcount
+= pItem
->GetCount();
8488 if( tempcount
>= count
)
8493 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8494 if (pProto
&& pProto
->GemProperties
)
8496 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8498 if(i
==int(except_slot
))
8501 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8502 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8504 tempcount
+= pItem
->GetGemCountWithID(item
);
8505 if( tempcount
>= count
)
8514 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8516 uint32 tempcount
= 0;
8517 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8519 if(i
==int(except_slot
))
8522 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8526 ItemPrototype
const *pProto
= pItem
->GetProto();
8530 if (pProto
->ItemLimitCategory
== limitCategory
)
8532 tempcount
+= pItem
->GetCount();
8533 if( tempcount
>= count
)
8537 if( pProto
->Socket
[0].Color
)
8539 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8540 if( tempcount
>= count
)
8548 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8550 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8554 *no_space_count
= count
;
8555 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8559 if(pProto
->MaxCount
<= 0)
8560 return EQUIP_ERR_OK
;
8562 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8564 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8567 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8568 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8571 return EQUIP_ERR_OK
;
8574 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8577 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8579 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8580 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8583 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8585 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8586 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8589 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8591 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8593 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8595 pItem
= GetItemByPos( i
, j
);
8596 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8604 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8606 Item
* pItem2
= GetItemByPos( bag
, slot
);
8608 // ignore move item (this slot will be empty at move)
8609 if(pItem2
==pSrcItem
)
8614 // empty specific slot - check item fit to slot
8615 if( !pItem2
|| swap
)
8617 if( bag
== INVENTORY_SLOT_BAG_0
)
8620 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8621 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8623 // vanitypet case (not use, vanity pets stored as spells)
8624 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8625 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8627 // currencytoken case (disabled until proper implement)
8628 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8629 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8631 // guestbag case (not use)
8632 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
)
8633 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8636 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8637 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8641 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8643 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8645 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8647 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8649 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8650 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8653 // non empty stack with space
8654 need_space
= pProto
->GetMaxStackSize();
8656 // non empty slot, check item type
8660 if(pItem2
->GetEntry() != pProto
->ItemId
)
8661 return EQUIP_ERR_ITEM_CANT_STACK
;
8664 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8665 return EQUIP_ERR_ITEM_CANT_STACK
;
8667 // free stack space or infinity
8668 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8671 if(need_space
> count
)
8674 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8675 if(!newPosition
.isContainedIn(dest
))
8677 dest
.push_back(newPosition
);
8678 count
-= need_space
;
8680 return EQUIP_ERR_OK
;
8683 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
8685 // skip specific bag already processed in first called _CanStoreItem_InBag
8687 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8689 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8691 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8693 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8695 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8697 // specialized bag mode or non-specilized
8698 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8699 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8701 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8702 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8704 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8706 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8710 Item
* pItem2
= GetItemByPos( bag
, j
);
8712 // ignore move item (this slot will be empty at move)
8713 if(pItem2
==pSrcItem
)
8716 // if merge skip empty, if !merge skip non-empty
8717 if((pItem2
!=NULL
)!=merge
)
8722 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8724 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8725 if(need_space
> count
)
8728 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8729 if(!newPosition
.isContainedIn(dest
))
8731 dest
.push_back(newPosition
);
8732 count
-= need_space
;
8735 return EQUIP_ERR_OK
;
8741 uint32 need_space
= pProto
->GetMaxStackSize();
8742 if(need_space
> count
)
8745 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8746 if(!newPosition
.isContainedIn(dest
))
8748 dest
.push_back(newPosition
);
8749 count
-= need_space
;
8752 return EQUIP_ERR_OK
;
8756 return EQUIP_ERR_OK
;
8759 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
8761 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8763 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8764 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8767 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8769 // ignore move item (this slot will be empty at move)
8770 if(pItem2
==pSrcItem
)
8773 // if merge skip empty, if !merge skip non-empty
8774 if((pItem2
!=NULL
)!=merge
)
8779 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8781 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8782 if(need_space
> count
)
8784 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8785 if(!newPosition
.isContainedIn(dest
))
8787 dest
.push_back(newPosition
);
8788 count
-= need_space
;
8791 return EQUIP_ERR_OK
;
8797 uint32 need_space
= pProto
->GetMaxStackSize();
8798 if(need_space
> count
)
8801 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8802 if(!newPosition
.isContainedIn(dest
))
8804 dest
.push_back(newPosition
);
8805 count
-= need_space
;
8808 return EQUIP_ERR_OK
;
8812 return EQUIP_ERR_OK
;
8815 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8817 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8819 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8823 *no_space_count
= count
;
8824 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8827 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8830 *no_space_count
= count
;
8831 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8834 // check count of items (skip for auto move for same player from bank)
8835 uint32 no_similar_count
= 0; // can't store this amount similar items
8836 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8837 if(res
!=EQUIP_ERR_OK
)
8839 if(count
==no_similar_count
)
8842 *no_space_count
= no_similar_count
;
8845 count
-= no_similar_count
;
8849 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8851 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8852 if(res
!=EQUIP_ERR_OK
)
8855 *no_space_count
= count
+ no_similar_count
;
8861 if(no_similar_count
==0)
8862 return EQUIP_ERR_OK
;
8865 *no_space_count
= count
+ no_similar_count
;
8866 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8870 // not specific slot or have space for partly store only in specific slot
8873 if( bag
!= NULL_BAG
)
8875 // search stack in bag for merge to
8876 if( pProto
->Stackable
!= 1 )
8878 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8880 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8881 if(res
!=EQUIP_ERR_OK
)
8884 *no_space_count
= count
+ no_similar_count
;
8890 if(no_similar_count
==0)
8891 return EQUIP_ERR_OK
;
8894 *no_space_count
= count
+ no_similar_count
;
8895 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8898 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8899 if(res
!=EQUIP_ERR_OK
)
8902 *no_space_count
= count
+ no_similar_count
;
8908 if(no_similar_count
==0)
8909 return EQUIP_ERR_OK
;
8912 *no_space_count
= count
+ no_similar_count
;
8913 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8916 else // equipped bag
8918 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8919 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8920 if(res
!=EQUIP_ERR_OK
)
8921 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8923 if(res
!=EQUIP_ERR_OK
)
8926 *no_space_count
= count
+ no_similar_count
;
8932 if(no_similar_count
==0)
8933 return EQUIP_ERR_OK
;
8936 *no_space_count
= count
+ no_similar_count
;
8937 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8942 // search free slot in bag for place to
8943 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8945 // search free slot - keyring case
8946 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8948 uint32 keyringSize
= GetMaxKeyringSize();
8949 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8950 if(res
!=EQUIP_ERR_OK
)
8953 *no_space_count
= count
+ no_similar_count
;
8959 if(no_similar_count
==0)
8960 return EQUIP_ERR_OK
;
8963 *no_space_count
= count
+ no_similar_count
;
8964 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8967 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8968 if(res
!=EQUIP_ERR_OK
)
8971 *no_space_count
= count
+ no_similar_count
;
8977 if(no_similar_count
==0)
8978 return EQUIP_ERR_OK
;
8981 *no_space_count
= count
+ no_similar_count
;
8982 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8985 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
8987 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8988 if(res
!=EQUIP_ERR_OK
)
8991 *no_space_count
= count
+ no_similar_count
;
8997 if(no_similar_count
==0)
8998 return EQUIP_ERR_OK
;
9001 *no_space_count
= count
+ no_similar_count
;
9002 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9006 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9007 if(res
!=EQUIP_ERR_OK
)
9010 *no_space_count
= count
+ no_similar_count
;
9016 if(no_similar_count
==0)
9017 return EQUIP_ERR_OK
;
9020 *no_space_count
= count
+ no_similar_count
;
9021 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9024 else // equipped bag
9026 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9027 if(res
!=EQUIP_ERR_OK
)
9028 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9030 if(res
!=EQUIP_ERR_OK
)
9033 *no_space_count
= count
+ no_similar_count
;
9039 if(no_similar_count
==0)
9040 return EQUIP_ERR_OK
;
9043 *no_space_count
= count
+ no_similar_count
;
9044 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9049 // not specific bag or have space for partly store only in specific bag
9051 // search stack for merge to
9052 if( pProto
->Stackable
!= 1 )
9054 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9055 if(res
!=EQUIP_ERR_OK
)
9058 *no_space_count
= count
+ no_similar_count
;
9064 if(no_similar_count
==0)
9065 return EQUIP_ERR_OK
;
9068 *no_space_count
= count
+ no_similar_count
;
9069 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9072 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9073 if(res
!=EQUIP_ERR_OK
)
9076 *no_space_count
= count
+ no_similar_count
;
9082 if(no_similar_count
==0)
9083 return EQUIP_ERR_OK
;
9086 *no_space_count
= count
+ no_similar_count
;
9087 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9090 if( pProto
->BagFamily
)
9092 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9094 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9095 if(res
!=EQUIP_ERR_OK
)
9100 if(no_similar_count
==0)
9101 return EQUIP_ERR_OK
;
9104 *no_space_count
= count
+ no_similar_count
;
9105 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9110 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9112 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9113 if(res
!=EQUIP_ERR_OK
)
9118 if(no_similar_count
==0)
9119 return EQUIP_ERR_OK
;
9122 *no_space_count
= count
+ no_similar_count
;
9123 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9128 // search free slot - special bag case
9129 if( pProto
->BagFamily
)
9131 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9133 uint32 keyringSize
= GetMaxKeyringSize();
9134 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9135 if(res
!=EQUIP_ERR_OK
)
9138 *no_space_count
= count
+ no_similar_count
;
9144 if(no_similar_count
==0)
9145 return EQUIP_ERR_OK
;
9148 *no_space_count
= count
+ no_similar_count
;
9149 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9152 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9154 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9155 if(res
!=EQUIP_ERR_OK
)
9158 *no_space_count
= count
+ no_similar_count
;
9164 if(no_similar_count
==0)
9165 return EQUIP_ERR_OK
;
9168 *no_space_count
= count
+ no_similar_count
;
9169 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9173 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9175 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9176 if(res
!=EQUIP_ERR_OK
)
9181 if(no_similar_count
==0)
9182 return EQUIP_ERR_OK
;
9185 *no_space_count
= count
+ no_similar_count
;
9186 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9192 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9193 if(res
!=EQUIP_ERR_OK
)
9196 *no_space_count
= count
+ no_similar_count
;
9202 if(no_similar_count
==0)
9203 return EQUIP_ERR_OK
;
9206 *no_space_count
= count
+ no_similar_count
;
9207 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9210 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9212 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9213 if(res
!=EQUIP_ERR_OK
)
9218 if(no_similar_count
==0)
9219 return EQUIP_ERR_OK
;
9222 *no_space_count
= count
+ no_similar_count
;
9223 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9228 *no_space_count
= count
+ no_similar_count
;
9230 return EQUIP_ERR_INVENTORY_FULL
;
9233 //////////////////////////////////////////////////////////////////////////
9234 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9239 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9240 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9241 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9242 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9244 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9245 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9246 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9247 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9249 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9251 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9253 if (pItem2
&& !pItem2
->IsInTrade())
9255 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9259 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9261 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9263 if (pItem2
&& !pItem2
->IsInTrade())
9265 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9269 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9271 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9273 if (pItem2
&& !pItem2
->IsInTrade())
9275 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9279 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9281 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9283 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9285 pItem2
= GetItemByPos( i
, j
);
9286 if (pItem2
&& !pItem2
->IsInTrade())
9288 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9294 // check free space for all items
9295 for (int k
=0;k
<count
;k
++)
9297 Item
*pItem
= pItems
[k
];
9300 if (!pItem
) continue;
9302 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9303 ItemPrototype
const *pProto
= pItem
->GetProto();
9307 return EQUIP_ERR_ITEM_NOT_FOUND
;
9310 if(pItem
->IsBindedNotWith(GetGUID()))
9311 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9314 ItemPrototype
const *pBagProto
;
9316 // item is 'one item only'
9317 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9318 if(res
!= EQUIP_ERR_OK
)
9321 // search stack for merge to
9322 if( pProto
->Stackable
!= 1 )
9324 bool b_found
= false;
9326 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9328 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9329 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9331 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9336 if (b_found
) continue;
9338 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9340 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9341 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9343 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9348 if (b_found
) continue;
9350 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9352 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9353 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9355 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9360 if (b_found
) continue;
9362 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9364 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9367 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9369 pItem2
= GetItemByPos( t
, j
);
9370 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9372 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9379 if (b_found
) continue;
9383 if( pProto
->BagFamily
)
9385 bool b_found
= false;
9386 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9388 uint32 keyringSize
= GetMaxKeyringSize();
9389 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9391 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9393 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9400 if (b_found
) continue;
9402 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9404 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9406 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9408 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9415 if (b_found
) continue;
9417 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9419 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9422 pBagProto
= pBag
->GetProto();
9424 // not plain container check
9425 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9426 ItemCanGoIntoBag(pProto
,pBagProto
) )
9428 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9430 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9432 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9440 if (b_found
) continue;
9444 bool b_found
= false;
9445 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9447 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9449 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9454 if (b_found
) continue;
9456 // search free slot in bags
9457 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9459 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9462 pBagProto
= pBag
->GetProto();
9464 // special bag already checked
9465 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9468 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9470 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9472 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9480 // no free slot found?
9482 return EQUIP_ERR_INVENTORY_FULL
;
9485 return EQUIP_ERR_OK
;
9488 //////////////////////////////////////////////////////////////////////////
9489 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9492 Item
*pItem
= Item::CreateItem( item
, 1, this );
9495 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9500 return EQUIP_ERR_ITEM_NOT_FOUND
;
9503 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9508 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9509 ItemPrototype
const *pProto
= pItem
->GetProto();
9512 if(pItem
->IsBindedNotWith(GetGUID()))
9513 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9515 // check count of items (skip for auto move for same player from bank)
9516 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9517 if(res
!= EQUIP_ERR_OK
)
9520 // check this only in game
9523 // May be here should be more stronger checks; STUNNED checked
9524 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9525 if (hasUnitState(UNIT_STAT_STUNNED
))
9526 return EQUIP_ERR_YOU_ARE_STUNNED
;
9528 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9530 // - in-progress arenas
9531 if( !pProto
->CanChangeEquipStateInCombat() )
9534 return EQUIP_ERR_NOT_IN_COMBAT
;
9536 if(BattleGround
* bg
= GetBattleGround())
9537 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9538 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9541 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9542 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9544 if(IsNonMeleeSpellCasted(false))
9545 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9548 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9549 if( eslot
== NULL_SLOT
)
9550 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9552 uint8 msg
= CanUseItem( pItem
, not_loading
);
9553 if( msg
!= EQUIP_ERR_OK
)
9555 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9556 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9558 // if swap ignore item (equipped also)
9559 if(uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9562 // check unique-equipped special item classes
9563 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9565 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9567 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9569 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9571 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
9573 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9574 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9576 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9583 uint32 type
= pProto
->InventoryType
;
9585 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9587 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9590 return EQUIP_ERR_CANT_DUAL_WIELD
;
9592 else if (type
== INVTYPE_2HWEAPON
)
9594 if(!CanDualWield() || !CanTitanGrip())
9595 return EQUIP_ERR_CANT_DUAL_WIELD
;
9599 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9602 // equip two-hand weapon case (with possible unequip 2 items)
9603 if( type
== INVTYPE_2HWEAPON
)
9605 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9607 if (!CanTitanGrip())
9608 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9610 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9611 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9613 if (!CanTitanGrip())
9615 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9616 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9617 ItemPosCountVec off_dest
;
9618 if( offItem
&& (!not_loading
||
9619 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9620 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9621 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9624 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9625 return EQUIP_ERR_OK
;
9629 return EQUIP_ERR_ITEM_NOT_FOUND
;
9631 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9634 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9636 // Applied only to equipped items and bank bags
9637 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9638 return EQUIP_ERR_OK
;
9640 Item
* pItem
= GetItemByPos(pos
);
9642 // Applied only to existed equipped item
9644 return EQUIP_ERR_OK
;
9646 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9648 ItemPrototype
const *pProto
= pItem
->GetProto();
9650 return EQUIP_ERR_ITEM_NOT_FOUND
;
9652 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9654 // - in-progress arenas
9655 if( !pProto
->CanChangeEquipStateInCombat() )
9658 return EQUIP_ERR_NOT_IN_COMBAT
;
9660 if(BattleGround
* bg
= GetBattleGround())
9661 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9662 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9665 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9666 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9668 return EQUIP_ERR_OK
;
9671 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9674 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9676 uint32 count
= pItem
->GetCount();
9678 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9679 ItemPrototype
const *pProto
= pItem
->GetProto();
9681 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9683 if( pItem
->IsBindedNotWith(GetGUID()) )
9684 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9686 // check count of items (skip for auto move for same player from bank)
9687 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9688 if(res
!= EQUIP_ERR_OK
)
9692 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9694 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9696 if (!pItem
->IsBag())
9697 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9699 Bag
*pBag
= (Bag
*)pItem
;
9700 if( !HasBankBagSlot( slot
) )
9701 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9703 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9707 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9708 if(res
!=EQUIP_ERR_OK
)
9712 return EQUIP_ERR_OK
;
9715 // not specific slot or have space for partly store only in specific slot
9718 if( bag
!= NULL_BAG
)
9720 if( pProto
->InventoryType
== INVTYPE_BAG
)
9722 Bag
*pBag
= (Bag
*)pItem
;
9723 if( pBag
&& !pBag
->IsEmpty() )
9724 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9727 // search stack in bag for merge to
9728 if( pProto
->Stackable
!= 1 )
9730 if( bag
== INVENTORY_SLOT_BAG_0
)
9732 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9733 if(res
!=EQUIP_ERR_OK
)
9737 return EQUIP_ERR_OK
;
9741 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9742 if(res
!=EQUIP_ERR_OK
)
9743 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9745 if(res
!=EQUIP_ERR_OK
)
9749 return EQUIP_ERR_OK
;
9753 // search free slot in bag
9754 if( bag
== INVENTORY_SLOT_BAG_0
)
9756 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9757 if(res
!=EQUIP_ERR_OK
)
9761 return EQUIP_ERR_OK
;
9765 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9766 if(res
!=EQUIP_ERR_OK
)
9767 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9769 if(res
!=EQUIP_ERR_OK
)
9773 return EQUIP_ERR_OK
;
9777 // not specific bag or have space for partly store only in specific bag
9779 // search stack for merge to
9780 if( pProto
->Stackable
!= 1 )
9783 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9784 if(res
!=EQUIP_ERR_OK
)
9788 return EQUIP_ERR_OK
;
9791 if( pProto
->BagFamily
)
9793 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9795 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9796 if(res
!=EQUIP_ERR_OK
)
9800 return EQUIP_ERR_OK
;
9804 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9806 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9807 if(res
!=EQUIP_ERR_OK
)
9811 return EQUIP_ERR_OK
;
9815 // search free place in special bag
9816 if( pProto
->BagFamily
)
9818 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9820 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9821 if(res
!=EQUIP_ERR_OK
)
9825 return EQUIP_ERR_OK
;
9829 // search free space
9830 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9831 if(res
!=EQUIP_ERR_OK
)
9835 return EQUIP_ERR_OK
;
9837 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9839 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9840 if(res
!=EQUIP_ERR_OK
)
9844 return EQUIP_ERR_OK
;
9846 return EQUIP_ERR_BANK_FULL
;
9849 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9853 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9854 if( !isAlive() && not_loading
)
9855 return EQUIP_ERR_YOU_ARE_DEAD
;
9857 // return EQUIP_ERR_YOU_ARE_STUNNED;
9858 ItemPrototype
const *pProto
= pItem
->GetProto();
9861 if( pItem
->IsBindedNotWith(GetGUID()) )
9862 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9863 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9864 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9865 if( pItem
->GetSkill() != 0 )
9867 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9868 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9870 if( pProto
->RequiredSkill
!= 0 )
9872 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9873 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9874 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9875 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9877 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9878 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9879 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9880 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9881 if( getLevel() < pProto
->RequiredLevel
)
9882 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9883 return EQUIP_ERR_OK
;
9886 return EQUIP_ERR_ITEM_NOT_FOUND
;
9889 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9891 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9895 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9897 if( pProto
->RequiredSkill
!= 0 )
9899 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9901 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9904 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9906 if( getLevel() < pProto
->RequiredLevel
)
9913 uint8
Player::CanUseAmmo( uint32 item
) const
9915 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9917 return EQUIP_ERR_YOU_ARE_DEAD
;
9919 // return EQUIP_ERR_YOU_ARE_STUNNED;
9920 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9923 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9924 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9925 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9926 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9927 if( pProto
->RequiredSkill
!= 0 )
9929 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9930 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9931 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9932 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9934 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9935 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9936 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9937 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9939 if( getLevel() < pProto
->RequiredLevel
)
9940 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9943 if(GetDummyAura(46699))
9944 return EQUIP_ERR_BAG_FULL6
;
9946 return EQUIP_ERR_OK
;
9948 return EQUIP_ERR_ITEM_NOT_FOUND
;
9951 void Player::SetAmmo( uint32 item
)
9957 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9963 uint8 msg
= CanUseAmmo( item
);
9964 if( msg
!= EQUIP_ERR_OK
)
9966 SendEquipError( msg
, NULL
, NULL
);
9971 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9973 _ApplyAmmoBonuses();
9976 void Player::RemoveAmmo()
9978 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9982 if(CanModifyStats())
9983 UpdateDamagePhysical(RANGED_ATTACK
);
9986 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9987 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9990 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9991 count
+= itr
->count
;
9993 Item
*pItem
= Item::CreateItem( item
, count
, this );
9996 ItemAddedQuestCheck( item
, count
);
9997 if(randomPropertyId
)
9998 pItem
->SetItemRandomProperties(randomPropertyId
);
9999 pItem
= StoreItem( dest
, pItem
, update
);
10004 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10009 Item
* lastItem
= pItem
;
10010 uint32 entry
= pItem
->GetEntry();
10011 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10013 uint16 pos
= itr
->pos
;
10014 uint32 count
= itr
->count
;
10018 if(itr
== dest
.end())
10020 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10024 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10026 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10030 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10031 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10036 uint8 bag
= pos
>> 8;
10037 uint8 slot
= pos
& 255;
10039 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10041 Item
*pItem2
= GetItemByPos( bag
, slot
);
10046 pItem
= pItem
->CloneItem(count
,this);
10048 pItem
->SetCount(count
);
10053 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10054 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10055 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10056 pItem
->SetBinding( true );
10058 if( bag
== INVENTORY_SLOT_BAG_0
)
10060 m_items
[slot
] = pItem
;
10061 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10062 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10063 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10065 pItem
->SetSlot( slot
);
10066 pItem
->SetContainer( NULL
);
10068 // need update known currency
10069 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10070 UpdateKnownCurrencies(pItem
->GetEntry(),true);
10072 if( IsInWorld() && update
)
10074 pItem
->AddToWorld();
10075 pItem
->SendUpdateToPlayer( this );
10078 pItem
->SetState(ITEM_CHANGED
, this);
10082 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10085 pBag
->StoreItem( slot
, pItem
, update
);
10086 if( IsInWorld() && update
)
10088 pItem
->AddToWorld();
10089 pItem
->SendUpdateToPlayer( this );
10091 pItem
->SetState(ITEM_CHANGED
, this);
10092 pBag
->SetState(ITEM_CHANGED
, this);
10096 AddEnchantmentDurations(pItem
);
10097 AddItemDurations(pItem
);
10103 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10104 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10105 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10106 pItem2
->SetBinding( true );
10108 pItem2
->SetCount( pItem2
->GetCount() + count
);
10109 if( IsInWorld() && update
)
10110 pItem2
->SendUpdateToPlayer( this );
10114 // delete item (it not in any slot currently)
10115 if( IsInWorld() && update
)
10117 pItem
->RemoveFromWorld();
10118 pItem
->DestroyForPlayer( this );
10121 RemoveEnchantmentDurations(pItem
);
10122 RemoveItemDurations(pItem
);
10124 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10125 pItem
->SetState(ITEM_REMOVED
, this);
10127 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10128 AddEnchantmentDurations(pItem2
);
10130 pItem2
->SetState(ITEM_CHANGED
, this);
10136 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10138 Item
*pItem
= Item::CreateItem( item
, 1, this );
10141 ItemAddedQuestCheck( item
, 1 );
10142 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10149 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10152 AddEnchantmentDurations(pItem
);
10153 AddItemDurations(pItem
);
10155 uint8 bag
= pos
>> 8;
10156 uint8 slot
= pos
& 255;
10158 Item
*pItem2
= GetItemByPos( bag
, slot
);
10162 VisualizeItem( slot
, pItem
);
10166 ItemPrototype
const *pProto
= pItem
->GetProto();
10168 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10169 if(pProto
&& pProto
->ItemSet
)
10170 AddItemsSetItem(this,pItem
);
10172 _ApplyItemMods(pItem
, slot
, true);
10174 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10176 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10178 if (getClass() == CLASS_ROGUE
)
10179 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10181 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10184 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10187 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10189 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10190 data
<< uint64(GetGUID());
10192 data
<< uint32(cooldownSpell
);
10194 GetSession()->SendPacket(&data
);
10199 if( IsInWorld() && update
)
10201 pItem
->AddToWorld();
10202 pItem
->SendUpdateToPlayer( this );
10205 ApplyEquipCooldown(pItem
);
10207 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10208 UpdateExpertise(BASE_ATTACK
);
10209 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10210 UpdateExpertise(OFF_ATTACK
);
10214 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10215 if( IsInWorld() && update
)
10216 pItem2
->SendUpdateToPlayer( this );
10218 // delete item (it not in any slot currently)
10219 //pItem->DeleteFromDB();
10220 if( IsInWorld() && update
)
10222 pItem
->RemoveFromWorld();
10223 pItem
->DestroyForPlayer( this );
10226 RemoveEnchantmentDurations(pItem
);
10227 RemoveItemDurations(pItem
);
10229 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10230 pItem
->SetState(ITEM_REMOVED
, this);
10231 pItem2
->SetState(ITEM_CHANGED
, this);
10233 ApplyEquipCooldown(pItem2
);
10238 // only for full equip instead adding to stack
10239 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10244 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10248 AddEnchantmentDurations(pItem
);
10249 AddItemDurations(pItem
);
10251 uint8 slot
= pos
& 255;
10252 VisualizeItem( slot
, pItem
);
10256 pItem
->AddToWorld();
10257 pItem
->SendUpdateToPlayer( this );
10262 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10264 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10265 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10266 // entry // Size: 1
10267 // inspected enchantments // Size: 6
10269 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10270 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10275 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10277 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10278 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10280 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10281 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10283 // Use SetInt16Value to prevent set high part to FFFF for negative value
10284 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10285 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10289 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10291 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10292 SetUInt32Value(VisibleBase
+ 0, 0);
10294 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10295 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10297 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10298 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10302 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10307 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10308 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10309 pItem
->SetBinding( true );
10311 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10313 m_items
[slot
] = pItem
;
10314 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10315 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10316 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10317 pItem
->SetSlot( slot
);
10318 pItem
->SetContainer( NULL
);
10320 if( slot
< EQUIPMENT_SLOT_END
)
10321 SetVisibleItemSlot(slot
,pItem
);
10323 pItem
->SetState(ITEM_CHANGED
, this);
10326 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10328 // note: removeitem does not actually change the item
10329 // it only takes the item out of storage temporarily
10330 // note2: if removeitem is to be used for delinking
10331 // the item must be removed from the player's updatequeue
10333 Item
*pItem
= GetItemByPos( bag
, slot
);
10336 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10338 RemoveEnchantmentDurations(pItem
);
10339 RemoveItemDurations(pItem
);
10341 if( bag
== INVENTORY_SLOT_BAG_0
)
10343 if ( slot
< INVENTORY_SLOT_BAG_END
)
10345 ItemPrototype
const *pProto
= pItem
->GetProto();
10346 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10348 if(pProto
&& pProto
->ItemSet
)
10349 RemoveItemsSetItem(this,pProto
);
10351 _ApplyItemMods(pItem
, slot
, false);
10353 // remove item dependent auras and casts (only weapon and armor slots)
10354 if(slot
< EQUIPMENT_SLOT_END
)
10356 RemoveItemDependentAurasAndCasts(pItem
);
10358 // remove held enchantments, update expertise
10359 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10361 if (pItem
->GetItemSuffixFactor())
10363 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10364 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10368 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10369 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10372 UpdateExpertise(BASE_ATTACK
);
10374 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10375 UpdateExpertise(OFF_ATTACK
);
10378 // need update known currency
10379 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10380 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10382 m_items
[slot
] = NULL
;
10383 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10385 if ( slot
< EQUIPMENT_SLOT_END
)
10386 SetVisibleItemSlot(slot
,NULL
);
10390 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10392 pBag
->RemoveItem(slot
, update
);
10394 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10395 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10396 pItem
->SetSlot( NULL_SLOT
);
10397 if( IsInWorld() && update
)
10398 pItem
->SendUpdateToPlayer( this );
10402 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10403 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10405 if(Item
* it
= GetItemByPos(bag
,slot
))
10407 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10408 RemoveItem( bag
,slot
,update
);
10409 it
->RemoveFromUpdateQueueOf(this);
10410 if(it
->IsInWorld())
10412 it
->RemoveFromWorld();
10413 it
->DestroyForPlayer( this );
10418 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10419 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10421 // update quest counters
10422 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10425 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10427 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10428 if(pLastItem
==pItem
)
10430 // update owner for last item (this can be original item with wrong owner
10431 if(pLastItem
->GetOwnerGUID() != GetGUID())
10432 pLastItem
->SetOwnerGUID(GetGUID());
10434 // if this original item then it need create record in inventory
10435 // in case trade we already have item in other player inventory
10436 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10440 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10442 Item
*pItem
= GetItemByPos( bag
, slot
);
10445 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10447 // start from destroy contained items (only equipped bag can have its)
10448 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10450 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10451 DestroyItem(slot
,i
,update
);
10454 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10455 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10457 RemoveEnchantmentDurations(pItem
);
10458 RemoveItemDurations(pItem
);
10460 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10462 if( bag
== INVENTORY_SLOT_BAG_0
)
10464 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10466 // equipment and equipped bags can have applied bonuses
10467 if ( slot
< INVENTORY_SLOT_BAG_END
)
10469 ItemPrototype
const *pProto
= pItem
->GetProto();
10471 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10472 if(pProto
&& pProto
->ItemSet
)
10473 RemoveItemsSetItem(this,pProto
);
10475 _ApplyItemMods(pItem
, slot
, false);
10478 if ( slot
< EQUIPMENT_SLOT_END
)
10480 // remove item dependent auras and casts (only weapon and armor slots)
10481 RemoveItemDependentAurasAndCasts(pItem
);
10483 // update expertise
10484 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10485 UpdateExpertise(BASE_ATTACK
);
10486 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10487 UpdateExpertise(OFF_ATTACK
);
10489 // equipment visual show
10490 SetVisibleItemSlot(slot
,NULL
);
10492 // need update known currency
10493 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10494 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10496 m_items
[slot
] = NULL
;
10498 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10499 pBag
->RemoveItem(slot
, update
);
10501 if( IsInWorld() && update
)
10503 pItem
->RemoveFromWorld();
10504 pItem
->DestroyForPlayer(this);
10507 //pItem->SetOwnerGUID(0);
10508 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10509 pItem
->SetSlot( NULL_SLOT
);
10510 pItem
->SetState(ITEM_REMOVED
, this);
10514 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10516 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10517 uint32 remcount
= 0;
10520 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10522 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10524 if (pItem
->GetEntry() == item
)
10526 if (pItem
->GetCount() + remcount
<= count
)
10528 // all items in inventory can unequipped
10529 remcount
+= pItem
->GetCount();
10530 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10532 if (remcount
>=count
)
10537 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10538 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10539 if (IsInWorld() & update
)
10540 pItem
->SendUpdateToPlayer( this );
10541 pItem
->SetState(ITEM_CHANGED
, this);
10548 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10550 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10552 if (pItem
->GetEntry() == item
)
10554 if (pItem
->GetCount() + remcount
<= count
)
10556 // all keys can be unequipped
10557 remcount
+= pItem
->GetCount();
10558 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10560 if (remcount
>=count
)
10565 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10566 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10567 if (IsInWorld() & update
)
10568 pItem
->SendUpdateToPlayer( this );
10569 pItem
->SetState(ITEM_CHANGED
, this);
10576 // in inventory bags
10577 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10579 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10581 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10583 if(Item
* pItem
= pBag
->GetItemByPos(j
))
10585 if (pItem
->GetEntry() == item
)
10587 // all items in bags can be unequipped
10588 if (pItem
->GetCount() + remcount
<= count
)
10590 remcount
+= pItem
->GetCount();
10591 DestroyItem( i
, j
, update
);
10593 if (remcount
>=count
)
10598 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10599 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10600 if (IsInWorld() && update
)
10601 pItem
->SendUpdateToPlayer( this );
10602 pItem
->SetState(ITEM_CHANGED
, this);
10611 // in equipment and bag list
10612 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10614 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10616 if (pItem
&& pItem
->GetEntry() == item
)
10618 if (pItem
->GetCount() + remcount
<= count
)
10620 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10622 remcount
+= pItem
->GetCount();
10623 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10625 if (remcount
>=count
)
10631 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10632 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10633 if (IsInWorld() & update
)
10634 pItem
->SendUpdateToPlayer( this );
10635 pItem
->SetState(ITEM_CHANGED
, this);
10643 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10645 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10648 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10649 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10650 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10651 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10653 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10654 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10655 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10656 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10658 // in inventory bags
10659 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10660 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10661 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10662 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10663 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10664 DestroyItem( i
, j
, update
);
10666 // in equipment and bag list
10667 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10668 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10669 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10670 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10673 void Player::DestroyConjuredItems( bool update
)
10675 // used when entering arena
10676 // destroys all conjured items
10677 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10680 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10681 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10682 if (pItem
->IsConjuredConsumable())
10683 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10685 // in inventory bags
10686 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10687 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10688 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10689 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10690 if (pItem
->IsConjuredConsumable())
10691 DestroyItem( i
, j
, update
);
10693 // in equipment and bag list
10694 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10695 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10696 if (pItem
->IsConjuredConsumable())
10697 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10700 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10705 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10707 if( pItem
->GetCount() <= count
)
10709 count
-= pItem
->GetCount();
10711 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10715 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10716 pItem
->SetCount( pItem
->GetCount() - count
);
10718 if( IsInWorld() & update
)
10719 pItem
->SendUpdateToPlayer( this );
10720 pItem
->SetState(ITEM_CHANGED
, this);
10724 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10726 uint8 srcbag
= src
>> 8;
10727 uint8 srcslot
= src
& 255;
10729 uint8 dstbag
= dst
>> 8;
10730 uint8 dstslot
= dst
& 255;
10732 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10735 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10739 // not let split all items (can be only at cheating)
10740 if(pSrcItem
->GetCount() == count
)
10742 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10746 // not let split more existed items (can be only at cheating)
10747 if(pSrcItem
->GetCount() < count
)
10749 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10753 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10755 //best error message found for attempting to split while looting
10756 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10760 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10761 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10764 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10768 if( IsInventoryPos( dst
) )
10770 // change item amount before check (for unique max count check)
10771 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10773 ItemPosCountVec dest
;
10774 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10775 if( msg
!= EQUIP_ERR_OK
)
10778 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10779 SendEquipError( msg
, pSrcItem
, NULL
);
10784 pSrcItem
->SendUpdateToPlayer( this );
10785 pSrcItem
->SetState(ITEM_CHANGED
, this);
10786 StoreItem( dest
, pNewItem
, true);
10788 else if( IsBankPos ( dst
) )
10790 // change item amount before check (for unique max count check)
10791 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10793 ItemPosCountVec dest
;
10794 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10795 if( msg
!= EQUIP_ERR_OK
)
10798 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10799 SendEquipError( msg
, pSrcItem
, NULL
);
10804 pSrcItem
->SendUpdateToPlayer( this );
10805 pSrcItem
->SetState(ITEM_CHANGED
, this);
10806 BankItem( dest
, pNewItem
, true);
10808 else if( IsEquipmentPos ( dst
) )
10810 // change item amount before check (for unique max count check), provide space for splitted items
10811 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10814 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10815 if( msg
!= EQUIP_ERR_OK
)
10818 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10819 SendEquipError( msg
, pSrcItem
, NULL
);
10824 pSrcItem
->SendUpdateToPlayer( this );
10825 pSrcItem
->SetState(ITEM_CHANGED
, this);
10826 EquipItem( dest
, pNewItem
, true);
10827 AutoUnequipOffhandIfNeed();
10831 void Player::SwapItem( uint16 src
, uint16 dst
)
10833 uint8 srcbag
= src
>> 8;
10834 uint8 srcslot
= src
& 255;
10836 uint8 dstbag
= dst
>> 8;
10837 uint8 dstslot
= dst
& 255;
10839 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10840 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10845 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10849 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10855 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10857 //best error message found for attempting to swap while looting
10858 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10862 // check unequip potability for equipped items and bank bags
10863 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10865 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10866 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
10867 if(msg
!= EQUIP_ERR_OK
)
10869 SendEquipError( msg
, pSrcItem
, pDstItem
);
10874 // prevent put equipped/bank bag in self
10875 if( IsBagPos ( src
) && srcslot
== dstbag
)
10877 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10885 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10887 //best error message found for attempting to swap while looting
10888 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10892 // check unequip potability for equipped items and bank bags
10893 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10895 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10896 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
10897 if(msg
!= EQUIP_ERR_OK
)
10899 SendEquipError( msg
, pSrcItem
, pDstItem
);
10905 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10906 // or swap empty bag with another empty or not empty bag (with items exchange)
10911 if( IsInventoryPos( dst
) )
10913 ItemPosCountVec dest
;
10914 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10915 if( msg
!= EQUIP_ERR_OK
)
10917 SendEquipError( msg
, pSrcItem
, NULL
);
10921 RemoveItem(srcbag
, srcslot
, true);
10922 StoreItem( dest
, pSrcItem
, true);
10924 else if( IsBankPos ( dst
) )
10926 ItemPosCountVec dest
;
10927 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10928 if( msg
!= EQUIP_ERR_OK
)
10930 SendEquipError( msg
, pSrcItem
, NULL
);
10934 RemoveItem(srcbag
, srcslot
, true);
10935 BankItem( dest
, pSrcItem
, true);
10937 else if( IsEquipmentPos ( dst
) )
10940 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10941 if( msg
!= EQUIP_ERR_OK
)
10943 SendEquipError( msg
, pSrcItem
, NULL
);
10947 RemoveItem(srcbag
, srcslot
, true);
10948 EquipItem( dest
, pSrcItem
, true);
10949 AutoUnequipOffhandIfNeed();
10955 // attempt merge to / fill target item
10956 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
10959 ItemPosCountVec sDest
;
10961 if( IsInventoryPos( dst
) )
10962 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10963 else if( IsBankPos ( dst
) )
10964 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10965 else if( IsEquipmentPos ( dst
) )
10966 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10970 // can be merge/fill
10971 if(msg
== EQUIP_ERR_OK
)
10973 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
10975 RemoveItem(srcbag
, srcslot
, true);
10977 if( IsInventoryPos( dst
) )
10978 StoreItem( sDest
, pSrcItem
, true);
10979 else if( IsBankPos ( dst
) )
10980 BankItem( sDest
, pSrcItem
, true);
10981 else if( IsEquipmentPos ( dst
) )
10983 EquipItem( eDest
, pSrcItem
, true);
10984 AutoUnequipOffhandIfNeed();
10989 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
10990 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
10991 pSrcItem
->SetState(ITEM_CHANGED
, this);
10992 pDstItem
->SetState(ITEM_CHANGED
, this);
10995 pSrcItem
->SendUpdateToPlayer( this );
10996 pDstItem
->SendUpdateToPlayer( this );
11003 // impossible merge/fill, do real swap
11006 // check src->dest move possibility
11007 ItemPosCountVec sDest
;
11009 if( IsInventoryPos( dst
) )
11010 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11011 else if( IsBankPos( dst
) )
11012 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11013 else if( IsEquipmentPos( dst
) )
11015 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11016 if( msg
== EQUIP_ERR_OK
)
11017 msg
= CanUnequipItem( eDest
, true );
11020 if( msg
!= EQUIP_ERR_OK
)
11022 SendEquipError( msg
, pSrcItem
, pDstItem
);
11026 // check dest->src move possibility
11027 ItemPosCountVec sDest2
;
11029 if( IsInventoryPos( src
) )
11030 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11031 else if( IsBankPos( src
) )
11032 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11033 else if( IsEquipmentPos( src
) )
11035 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11036 if( msg
== EQUIP_ERR_OK
)
11037 msg
= CanUnequipItem( eDest2
, true);
11040 if( msg
!= EQUIP_ERR_OK
)
11042 SendEquipError( msg
, pDstItem
, pSrcItem
);
11046 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11047 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11049 Bag
* emptyBag
= NULL
;
11050 Bag
* fullBag
= NULL
;
11051 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11053 emptyBag
= (Bag
*)pSrcItem
;
11054 fullBag
= (Bag
*)pDstItem
;
11056 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11058 emptyBag
= (Bag
*)pDstItem
;
11059 fullBag
= (Bag
*)pSrcItem
;
11062 // bag swap (with items exchange) case
11063 if(emptyBag
&& fullBag
)
11065 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11069 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11071 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11075 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11076 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11078 // one from items not go to empry target bag
11079 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11087 if (count
> emptyBag
->GetBagSize())
11089 // too small targeted bag
11090 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11095 count
= 0; // will pos in new bag
11096 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11098 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11102 fullBag
->RemoveItem(i
, true);
11103 emptyBag
->StoreItem(count
, bagItem
, true);
11104 bagItem
->SetState(ITEM_CHANGED
, this);
11111 // now do moves, remove...
11112 RemoveItem(dstbag
, dstslot
, false);
11113 RemoveItem(srcbag
, srcslot
, false);
11116 if( IsInventoryPos( dst
) )
11117 StoreItem(sDest
, pSrcItem
, true);
11118 else if( IsBankPos( dst
) )
11119 BankItem(sDest
, pSrcItem
, true);
11120 else if( IsEquipmentPos( dst
) )
11121 EquipItem(eDest
, pSrcItem
, true);
11124 if( IsInventoryPos( src
) )
11125 StoreItem(sDest2
, pDstItem
, true);
11126 else if( IsBankPos( src
) )
11127 BankItem(sDest2
, pDstItem
, true);
11128 else if( IsEquipmentPos( src
) )
11129 EquipItem(eDest2
, pDstItem
, true);
11131 AutoUnequipOffhandIfNeed();
11134 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11138 uint32 slot
= m_currentBuybackSlot
;
11139 // if current back slot non-empty search oldest or free
11142 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11143 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11145 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11154 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11156 if(oldest_time
> i_time
)
11158 oldest_time
= i_time
;
11164 slot
= oldest_slot
;
11167 RemoveItemFromBuyBackSlot( slot
, true );
11168 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11170 m_items
[slot
] = pItem
;
11171 time_t base
= time(NULL
);
11172 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11173 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11175 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11176 ItemPrototype
const *pProto
= pItem
->GetProto();
11178 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11180 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11181 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11183 // move to next (for non filled list is move most optimized choice)
11184 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11185 ++m_currentBuybackSlot
;
11189 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11191 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11192 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11193 return m_items
[slot
];
11197 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11199 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11200 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11202 Item
*pItem
= m_items
[slot
];
11205 pItem
->RemoveFromWorld();
11206 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11209 m_items
[slot
] = NULL
;
11211 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11212 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11213 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11214 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11216 // if current backslot is filled set to now free slot
11217 if(m_items
[m_currentBuybackSlot
])
11218 m_currentBuybackSlot
= slot
;
11222 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11224 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11225 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11226 data
<< uint8(msg
);
11230 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11231 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11232 data
<< uint8(0); // not 0 there...
11234 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11239 if(ItemPrototype
const* proto
= pItem
->GetProto())
11240 level
= proto
->RequiredLevel
;
11242 data
<< uint32(level
); // new 2.4.0
11245 GetSession()->SendPacket(&data
);
11248 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11250 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11251 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11252 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11253 data
<< uint32(item
);
11255 data
<< uint32(param
);
11256 data
<< uint8(msg
);
11257 GetSession()->SendPacket(&data
);
11260 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11262 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11263 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11264 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11265 data
<< uint64(guid
);
11267 data
<< uint32(param
);
11268 data
<< uint8(msg
);
11269 GetSession()->SendPacket(&data
);
11272 void Player::ClearTrade()
11275 acceptTrade
= false;
11276 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11277 tradeItems
[i
] = NULL_SLOT
;
11280 void Player::TradeCancel(bool sendback
)
11284 // send yellow "Trade canceled" message to both traders
11288 ws
->SendCancelTrade();
11289 ws
= pTrader
->GetSession();
11290 if(!ws
->PlayerLogout())
11291 ws
->SendCancelTrade();
11295 pTrader
->ClearTrade();
11296 // prevent loss of reference
11297 pTrader
->pTrader
= NULL
;
11302 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11304 if(m_itemDuration
.empty())
11307 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11309 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11312 ++itr
; // current element can be erased in UpdateDuration
11314 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11315 item
->UpdateDuration(this,time
);
11319 void Player::UpdateEnchantTime(uint32 time
)
11321 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11325 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11327 next
= m_enchantDuration
.erase(itr
);
11329 else if(itr
->leftduration
<= time
)
11331 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11332 itr
->item
->ClearEnchantment(itr
->slot
);
11333 next
= m_enchantDuration
.erase(itr
);
11335 else if(itr
->leftduration
> time
)
11337 itr
->leftduration
-= time
;
11343 void Player::AddEnchantmentDurations(Item
*item
)
11345 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11347 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11350 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11352 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11356 void Player::RemoveEnchantmentDurations(Item
*item
)
11358 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11360 if(itr
->item
== item
)
11362 // save duration in item
11363 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11364 itr
= m_enchantDuration
.erase(itr
);
11371 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11373 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11374 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11377 if(itr
->slot
==slot
)
11379 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11381 // remove from stats
11382 ApplyEnchantment(itr
->item
,slot
,false,false);
11384 itr
->item
->ClearEnchantment(slot
);
11386 // remove from update list
11387 next
= m_enchantDuration
.erase(itr
);
11393 // remove enchants from inventory items
11394 // NOTE: no need to remove these from stats, since these aren't equipped
11396 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11398 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11399 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11400 pItem
->ClearEnchantment(slot
);
11403 // in inventory bags
11404 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11406 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11409 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11411 Item
* pItem
= pBag
->GetItemByPos(j
);
11412 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11413 pItem
->ClearEnchantment(slot
);
11419 // duration == 0 will remove item enchant
11420 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11425 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11428 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11430 if(itr
->item
== item
&& itr
->slot
== slot
)
11432 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11433 m_enchantDuration
.erase(itr
);
11437 if(item
&& duration
> 0 )
11439 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11440 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11444 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11446 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11447 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11450 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11455 if(!item
->IsEquipped())
11458 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11461 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11465 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11469 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11472 for (int s
=0; s
<3; s
++)
11474 uint32 enchant_display_type
= pEnchant
->type
[s
];
11475 uint32 enchant_amount
= pEnchant
->amount
[s
];
11476 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11478 switch(enchant_display_type
)
11480 case ITEM_ENCHANTMENT_TYPE_NONE
:
11482 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11483 // processed in Player::CastItemCombatSpell
11485 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11486 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11487 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11488 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11489 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11490 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11491 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11493 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11494 if(enchant_spell_id
)
11498 int32 basepoints
= 0;
11499 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11500 if (item
->GetItemRandomPropertyId())
11502 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11505 // Search enchant_amount
11506 for (int k
=0; k
<3; k
++)
11508 if(item_rand
->enchant_id
[k
] == enchant_id
)
11510 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11516 // Cast custom spell vs all equal basepoints getted from enchant_amount
11518 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11520 CastSpell(this,enchant_spell_id
,true,item
);
11523 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11526 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11527 if (!enchant_amount
)
11529 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11532 for (int k
=0; k
<3; k
++)
11534 if(item_rand
->enchant_id
[k
] == enchant_id
)
11536 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11543 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11545 case ITEM_ENCHANTMENT_TYPE_STAT
:
11547 if (!enchant_amount
)
11549 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11550 if(item_rand_suffix
)
11552 for (int k
=0; k
<3; k
++)
11554 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11556 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11563 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11564 switch (enchant_spell_id
)
11566 case ITEM_MOD_AGILITY
:
11567 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11568 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11569 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11571 case ITEM_MOD_STRENGTH
:
11572 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11573 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11574 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11576 case ITEM_MOD_INTELLECT
:
11577 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11578 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11579 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11581 case ITEM_MOD_SPIRIT
:
11582 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11583 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11584 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11586 case ITEM_MOD_STAMINA
:
11587 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11588 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11589 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11591 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11592 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11593 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11595 case ITEM_MOD_DODGE_RATING
:
11596 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11597 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11599 case ITEM_MOD_PARRY_RATING
:
11600 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11601 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11603 case ITEM_MOD_BLOCK_RATING
:
11604 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11605 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11607 case ITEM_MOD_HIT_MELEE_RATING
:
11608 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11609 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11611 case ITEM_MOD_HIT_RANGED_RATING
:
11612 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11613 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11615 case ITEM_MOD_HIT_SPELL_RATING
:
11616 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11617 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11619 case ITEM_MOD_CRIT_MELEE_RATING
:
11620 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11621 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11623 case ITEM_MOD_CRIT_RANGED_RATING
:
11624 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11625 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11627 case ITEM_MOD_CRIT_SPELL_RATING
:
11628 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11629 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11631 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11633 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11634 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11636 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11637 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11639 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11640 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11642 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11643 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11645 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11646 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11648 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11649 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11651 // case ITEM_MOD_HASTE_MELEE_RATING:
11652 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11654 // case ITEM_MOD_HASTE_RANGED_RATING:
11655 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11657 case ITEM_MOD_HASTE_SPELL_RATING
:
11658 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11660 case ITEM_MOD_HIT_RATING
:
11661 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11662 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11663 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11664 sLog
.outDebug("+ %u HIT", enchant_amount
);
11666 case ITEM_MOD_CRIT_RATING
:
11667 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11668 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11669 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11670 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11672 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11673 // case ITEM_MOD_HIT_TAKEN_RATING:
11674 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11675 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11676 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11678 // case ITEM_MOD_CRIT_TAKEN_RATING:
11679 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11680 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11681 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11683 case ITEM_MOD_RESILIENCE_RATING
:
11684 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11685 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11686 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11687 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11689 case ITEM_MOD_HASTE_RATING
:
11690 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11691 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11692 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11693 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11695 case ITEM_MOD_EXPERTISE_RATING
:
11696 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11697 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11699 case ITEM_MOD_ATTACK_POWER
:
11700 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11701 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11702 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11704 case ITEM_MOD_RANGED_ATTACK_POWER
:
11705 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11706 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11708 case ITEM_MOD_FERAL_ATTACK_POWER
:
11709 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11710 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
11712 case ITEM_MOD_SPELL_HEALING_DONE
:
11713 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11714 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
11716 case ITEM_MOD_SPELL_DAMAGE_DONE
:
11717 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11718 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
11720 case ITEM_MOD_MANA_REGENERATION
:
11721 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
11722 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
11724 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11725 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11726 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11728 case ITEM_MOD_SPELL_POWER
:
11729 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11730 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11731 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
11738 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11740 if(getClass() == CLASS_SHAMAN
)
11742 float addValue
= 0.0f
;
11743 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11745 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11746 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11748 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11750 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11751 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11756 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
11757 // processed in Player::CastItemUseSpell
11759 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
11763 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
11765 } /*switch(enchant_display_type)*/
11768 // visualize enchantment at player and equipped items
11769 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11771 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11772 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11780 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11782 AddEnchantmentDuration(item
,slot
,duration
);
11786 // duration == 0 will remove EnchantDuration
11787 AddEnchantmentDuration(item
,slot
,0);
11792 void Player::SendEnchantmentDurations()
11794 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11796 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11800 void Player::SendItemDurations()
11802 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11804 (*itr
)->SendTimeUpdate(this);
11808 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11810 if(!item
) // prevent crash
11813 // last check 2.0.10
11814 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11815 data
<< GetGUID(); // player GUID
11816 data
<< uint32(received
); // 0=looted, 1=from npc
11817 data
<< uint32(created
); // 0=received, 1=created
11818 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11819 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11820 // item slot, but when added to stack: 0xFFFFFFFF
11821 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11822 data
<< uint32(item
->GetEntry()); // item id
11823 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11824 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11825 data
<< uint32(count
); // count of items
11826 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11828 if (broadcast
&& GetGroup())
11829 GetGroup()->BroadcastPacket(&data
, true);
11831 GetSession()->SendPacket(&data
);
11834 /*********************************************************/
11835 /*** QUEST SYSTEM ***/
11836 /*********************************************************/
11838 void Player::PrepareQuestMenu( uint64 guid
)
11841 QuestRelations
* pObjectQR
;
11842 QuestRelations
* pObjectQIR
;
11843 Creature
*pCreature
= GetMap()->GetCreature(guid
);
11846 pObject
= (Object
*)pCreature
;
11847 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11848 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11852 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
11855 pObject
= (Object
*)pGameObject
;
11856 pObjectQR
= &objmgr
.mGOQuestRelations
;
11857 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11863 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11866 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11868 uint32 quest_id
= i
->second
;
11869 QuestStatus status
= GetQuestStatus( quest_id
);
11870 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11871 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11872 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11873 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11874 else if (status
== QUEST_STATUS_AVAILABLE
)
11875 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11878 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11880 uint32 quest_id
= i
->second
;
11881 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11882 if(!pQuest
) continue;
11884 QuestStatus status
= GetQuestStatus( quest_id
);
11886 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11887 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11888 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11889 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11893 void Player::SendPreparedQuest( uint64 guid
)
11895 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11896 if( questMenu
.Empty() )
11899 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11901 uint32 status
= qmi0
.m_qIcon
;
11903 // single element case
11904 if ( questMenu
.MenuItemCount() == 1 )
11906 // Auto open -- maybe also should verify there is no greeting
11907 uint32 quest_id
= qmi0
.m_qId
;
11908 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11911 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11912 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11913 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11914 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11915 // Send completable on repeatable quest if player don't have quest
11916 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
11917 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11919 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11922 // multiply entries
11928 std::string title
= "";
11929 Creature
*pCreature
= GetMap()->GetCreature(guid
);
11932 uint32 textid
= pCreature
->GetNpcTextId();
11933 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
11936 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11937 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11942 qe
= gossiptext
->Options
[0].Emotes
[0];
11944 if(!gossiptext
->Options
[0].Text_0
.empty())
11946 title
= gossiptext
->Options
[0].Text_0
;
11948 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11951 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11954 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11955 title
= nl
->Text_0
[0][loc_idx
];
11961 title
= gossiptext
->Options
[0].Text_1
;
11963 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11966 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11969 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11970 title
= nl
->Text_1
[0][loc_idx
];
11976 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11980 bool Player::IsActiveQuest( uint32 quest_id
) const
11982 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11984 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11987 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11990 QuestRelations
* pObjectQR
;
11991 QuestRelations
* pObjectQIR
;
11993 Creature
*pCreature
= GetMap()->GetCreature(guid
);
11996 pObject
= (Object
*)pCreature
;
11997 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11998 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12002 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
12005 pObject
= (Object
*)pGameObject
;
12006 pObjectQR
= &objmgr
.mGOQuestRelations
;
12007 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12013 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12014 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12016 if (itr
->second
== nextQuestID
)
12017 return objmgr
.GetQuestTemplate(nextQuestID
);
12023 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12025 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12026 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12027 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12028 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12030 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12036 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12038 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12039 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12040 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12041 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12042 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12043 && SatisfyQuestDay( pQuest
, msg
);
12046 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12048 if( !SatisfyQuestLog( msg
) )
12051 uint32 srcitem
= pQuest
->GetSrcItemId();
12054 uint32 count
= pQuest
->GetSrcItemCount();
12055 ItemPosCountVec dest
;
12056 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12058 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12059 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12061 else if( msg2
!= EQUIP_ERR_OK
)
12063 SendEquipError( msg2
, NULL
, NULL
);
12070 bool Player::CanCompleteQuest( uint32 quest_id
)
12074 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12075 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12076 return false; // not allow re-complete quest
12078 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12083 // auto complete quest
12084 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12087 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12090 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12092 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12094 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12099 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12101 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12103 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12106 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12111 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12114 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12117 if ( qInfo
->GetRewOrReqMoney() < 0 )
12119 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12123 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12124 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12133 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12135 // Solve problem that player don't have the quest and try complete it.
12136 // if repeatable she must be able to complete event if player don't have it.
12137 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12138 if( !CanTakeQuest(pQuest
, false) )
12141 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12142 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12143 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12146 if( !CanRewardQuest(pQuest
, false) )
12152 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12154 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12155 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12158 // daily quest can't be rewarded (25 daily quest already completed)
12159 if(!SatisfyQuestDay(pQuest
,true))
12162 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12163 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12166 // prevent receive reward with quest items in bank
12167 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12169 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12171 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12172 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12175 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12181 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12182 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12188 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12190 // prevent receive reward with quest items in bank or for not completed quest
12191 if(!CanRewardQuest(pQuest
,msg
))
12194 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12196 if( pQuest
->RewChoiceItemId
[reward
] )
12198 ItemPosCountVec dest
;
12199 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12200 if( res
!= EQUIP_ERR_OK
)
12202 SendEquipError( res
, NULL
, NULL
);
12208 if ( pQuest
->GetRewItemsCount() > 0 )
12210 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12212 if( pQuest
->RewItemId
[i
] )
12214 ItemPosCountVec dest
;
12215 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12216 if( res
!= EQUIP_ERR_OK
)
12218 SendEquipError( res
, NULL
, NULL
);
12228 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12230 uint16 log_slot
= FindQuestSlot( 0 );
12231 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12233 uint32 quest_id
= pQuest
->GetQuestId();
12235 // if not exist then created with set uState==NEW and rewarded=false
12236 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12238 // check for repeatable quests status reset
12239 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12240 questStatusData
.m_explored
= false;
12242 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12244 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12245 questStatusData
.m_itemcount
[i
] = 0;
12248 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12250 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12251 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12254 GiveQuestSourceItem( pQuest
);
12255 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12257 if( pQuest
->GetRepObjectiveFaction() )
12258 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
12259 GetReputationMgr().SetVisible(factionEntry
);
12262 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12264 uint32 limittime
= pQuest
->GetLimitTime();
12266 // shared timed quest
12267 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12268 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12270 AddTimedQuest( quest_id
);
12271 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12272 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12275 questStatusData
.m_timer
= 0;
12277 SetQuestSlot(log_slot
, quest_id
, qtime
);
12279 if (questStatusData
.uState
!= QUEST_NEW
)
12280 questStatusData
.uState
= QUEST_CHANGED
;
12282 //starting initial quest script
12283 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12284 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12286 // Some spells applied at quest activation
12287 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12288 if(saBounds
.first
!= saBounds
.second
)
12291 GetZoneAndAreaId(zone
,area
);
12293 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12294 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12295 if( !HasAura(itr
->second
->spellId
,0) )
12296 CastSpell(this,itr
->second
->spellId
,true);
12299 UpdateForQuestsGO();
12302 void Player::CompleteQuest( uint32 quest_id
)
12306 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12308 uint16 log_slot
= FindQuestSlot( quest_id
);
12309 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12310 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12312 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12314 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12315 RewardQuest(qInfo
,0,this,false);
12317 SendQuestComplete( quest_id
);
12322 void Player::IncompleteQuest( uint32 quest_id
)
12326 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12328 uint16 log_slot
= FindQuestSlot( quest_id
);
12329 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12330 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12334 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12336 uint32 quest_id
= pQuest
->GetQuestId();
12338 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12340 if ( pQuest
->ReqItemId
[i
] )
12341 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12344 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12345 // SetTimedQuest( 0 );
12346 m_timedquests
.erase(pQuest
->GetQuestId());
12348 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12350 if( pQuest
->RewChoiceItemId
[reward
] )
12352 ItemPosCountVec dest
;
12353 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12355 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12356 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12361 if ( pQuest
->GetRewItemsCount() > 0 )
12363 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12365 if( pQuest
->RewItemId
[i
] )
12367 ItemPosCountVec dest
;
12368 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12370 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12371 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12377 RewardReputation( pQuest
);
12379 if( pQuest
->GetRewSpellCast() > 0 )
12380 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12381 else if( pQuest
->GetRewSpell() > 0)
12382 CastSpell( this, pQuest
->GetRewSpell(), true);
12384 uint16 log_slot
= FindQuestSlot( quest_id
);
12385 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12386 SetQuestSlot(log_slot
,0);
12388 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12390 // Not give XP in case already completed once repeatable quest
12391 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12393 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12394 GiveXP( XP
, NULL
);
12397 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12398 ModifyMoney( money
);
12399 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12402 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12403 if(pQuest
->GetRewOrReqMoney())
12405 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12407 if(pQuest
->GetRewOrReqMoney() > 0)
12408 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12412 if(pQuest
->GetRewHonorableKills())
12413 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12416 if(pQuest
->GetCharTitleId())
12418 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12419 SetTitle(titleEntry
);
12422 if(pQuest
->GetBonusTalents())
12424 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12425 InitTalentForLevel();
12428 // Send reward mail
12429 if(pQuest
->GetRewMailTemplateId())
12431 MailMessageType mailType
;
12432 uint32 senderGuidOrEntry
;
12433 switch(questGiver
->GetTypeId())
12436 mailType
= MAIL_CREATURE
;
12437 senderGuidOrEntry
= questGiver
->GetEntry();
12439 case TYPEID_GAMEOBJECT
:
12440 mailType
= MAIL_GAMEOBJECT
;
12441 senderGuidOrEntry
= questGiver
->GetEntry();
12444 mailType
= MAIL_ITEM
;
12445 senderGuidOrEntry
= questGiver
->GetEntry();
12447 case TYPEID_PLAYER
:
12448 mailType
= MAIL_NORMAL
;
12449 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12452 mailType
= MAIL_NORMAL
;
12453 senderGuidOrEntry
= GetGUIDLow();
12457 Loot questMailLoot
;
12459 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12462 MailItemsInfo mi
; // item list preparing
12464 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12465 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12467 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12469 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12471 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12472 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12477 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12480 if(pQuest
->IsDaily())
12482 SetDailyQuestStatus(quest_id
);
12483 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12486 if ( !pQuest
->IsRepeatable() )
12487 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12489 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12491 q_status
.m_rewarded
= true;
12494 SendQuestReward( pQuest
, XP
, questGiver
);
12496 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12497 if (pQuest
->GetZoneOrSort() > 0)
12498 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
12499 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12500 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
12505 // remove auras from spells with quest reward state limitations
12506 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12507 if(saEndBounds
.first
!= saEndBounds
.second
)
12509 GetZoneAndAreaId(zone
,area
);
12511 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12512 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12513 RemoveAurasDueToSpell(itr
->second
->spellId
);
12516 // Some spells applied at quest reward
12517 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12518 if(saBounds
.first
!= saBounds
.second
)
12521 GetZoneAndAreaId(zone
,area
);
12523 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12524 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12525 if( !HasAura(itr
->second
->spellId
,0) )
12526 CastSpell(this,itr
->second
->spellId
,true);
12530 void Player::FailQuest( uint32 quest_id
)
12534 IncompleteQuest( quest_id
);
12536 uint16 log_slot
= FindQuestSlot( quest_id
);
12537 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12539 SetQuestSlotTimer(log_slot
, 1 );
12540 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12542 SendQuestFailed( quest_id
);
12546 void Player::FailTimedQuest( uint32 quest_id
)
12550 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12552 q_status
.m_timer
= 0;
12553 if (q_status
.uState
!= QUEST_NEW
)
12554 q_status
.uState
= QUEST_CHANGED
;
12556 IncompleteQuest( quest_id
);
12558 uint16 log_slot
= FindQuestSlot( quest_id
);
12559 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12561 SetQuestSlotTimer(log_slot
, 1 );
12562 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12564 SendQuestTimerFailed( quest_id
);
12568 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12570 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12571 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12573 // skip zone zoneOrSort and 0 case skillOrClass
12574 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12577 int32 questSort
= -zoneOrSort
;
12578 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12580 // check class sort cases in zoneOrSort
12581 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12584 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12589 if( skillOrClass
< 0 )
12591 uint8 reqClass
= -int32(skillOrClass
);
12592 if(getClass() != reqClass
)
12595 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12600 else if( skillOrClass
> 0 )
12602 uint32 reqSkill
= skillOrClass
;
12603 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12606 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12614 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12616 if( getLevel() < qInfo
->GetMinLevel() )
12619 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12625 bool Player::SatisfyQuestLog( bool msg
)
12628 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12633 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12634 GetSession()->SendPacket( &data
);
12635 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12640 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12642 // No previous quest (might be first quest in a series)
12643 if( qInfo
->prevQuests
.empty())
12646 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12648 uint32 prevId
= abs(*iter
);
12650 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12651 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12653 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12655 // If any of the positive previous quests completed, return true
12656 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12658 // skip one-from-all exclusive group
12659 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12662 // each-from-all exclusive group ( < 0)
12663 // can be start if only all quests in prev quest exclusive group completed and rewarded
12664 ObjectMgr::ExclusiveQuestGroups::iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12665 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12667 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12669 for(; iter2
!= end
; ++iter2
)
12671 uint32 exclude_Id
= iter2
->second
;
12673 // skip checked quest id, only state of other quests in group is interesting
12674 if(exclude_Id
== prevId
)
12677 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12679 // alternative quest from group also must be completed and rewarded(reported)
12680 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12683 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12689 // If any of the negative previous quests active, return true
12690 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12691 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12693 // skip one-from-all exclusive group
12694 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12697 // each-from-all exclusive group ( < 0)
12698 // can be start if only all quests in prev quest exclusive group active
12699 ObjectMgr::ExclusiveQuestGroups::iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12700 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12702 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12704 for(; iter2
!= end
; ++iter2
)
12706 uint32 exclude_Id
= iter2
->second
;
12708 // skip checked quest id, only state of other quests in group is interesting
12709 if(exclude_Id
== prevId
)
12712 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12714 // alternative quest from group also must be active
12715 if( i_exstatus
== mQuestStatus
.end() ||
12716 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12717 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12720 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12729 // Has only positive prev. quests in non-rewarded state
12730 // and negative prev. quests in non-active state
12732 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12737 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12739 uint32 reqraces
= qInfo
->GetRequiredRaces();
12740 if ( reqraces
== 0 )
12742 if( (reqraces
& getRaceMask()) == 0 )
12745 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12751 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12753 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12754 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12757 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12761 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12762 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12765 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12772 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12774 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12775 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12778 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12784 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12786 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12789 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12795 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12797 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12798 if(qInfo
->GetExclusiveGroup() <= 0)
12801 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12802 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12804 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12806 for(; iter
!= end
; ++iter
)
12808 uint32 exclude_Id
= iter
->second
;
12810 // skip checked quest id, only state of other quests in group is interesting
12811 if(exclude_Id
== qInfo
->GetQuestId())
12814 // not allow have daily quest if daily quest from exclusive group already recently completed
12815 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12816 if( !SatisfyQuestDay(Nquest
, false) )
12819 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12823 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12825 // alternative quest already started or completed
12826 if( i_exstatus
!= mQuestStatus
.end()
12827 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12830 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12837 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12839 if(!qInfo
->GetNextQuestInChain())
12842 // next quest in chain already started or completed
12843 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12844 if( itr
!= mQuestStatus
.end()
12845 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12848 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12852 // check for all quests further up the chain
12853 // only necessary if there are quest chains with more than one quest that can be skipped
12854 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12858 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12860 // No previous quest in chain
12861 if( qInfo
->prevChainQuests
.empty())
12864 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12866 uint32 prevId
= *iter
;
12868 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12870 if( i_prevstatus
!= mQuestStatus
.end() )
12872 // If any of the previous quests in chain active, return false
12873 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12874 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12877 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12882 // check for all quests further down the chain
12883 // only necessary if there are quest chains with more than one quest that can be skipped
12884 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12888 // No previous quest in chain active
12892 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12894 if(!qInfo
->IsDaily())
12897 bool have_slot
= false;
12898 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12900 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12901 if(qInfo
->GetQuestId()==id
)
12911 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12918 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12920 uint32 srcitem
= pQuest
->GetSrcItemId();
12923 uint32 count
= pQuest
->GetSrcItemCount();
12927 ItemPosCountVec dest
;
12928 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12929 if( msg
== EQUIP_ERR_OK
)
12931 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12932 SendNewItem(item
, count
, true, false);
12935 // player already have max amount required item, just report success
12936 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12939 SendEquipError( msg
, NULL
, NULL
);
12946 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12948 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12951 uint32 srcitem
= qInfo
->GetSrcItemId();
12954 uint32 count
= qInfo
->GetSrcItemCount();
12958 // exist one case when destroy source quest item not possible:
12959 // non un-equippable item (equipped non-empty bag, for example)
12960 uint8 res
= CanUnequipItems(srcitem
,count
);
12961 if(res
!= EQUIP_ERR_OK
)
12964 SendEquipError( res
, NULL
, NULL
);
12968 DestroyItemCount(srcitem
, count
, true, true);
12974 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12976 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12979 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12980 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12981 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12982 && !qInfo
->IsRepeatable() )
12983 return itr
->second
.m_rewarded
;
12990 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12994 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12995 if( itr
!= mQuestStatus
.end() )
12996 return itr
->second
.m_status
;
12998 return QUEST_STATUS_NONE
;
13001 bool Player::CanShareQuest(uint32 quest_id
) const
13003 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13004 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13006 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13007 if( itr
!= mQuestStatus
.end() )
13008 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13013 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13015 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13018 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13020 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13021 m_timedquests
.erase(qInfo
->GetQuestId());
13024 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13026 q_status
.m_status
= status
;
13027 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13030 UpdateForQuestsGO();
13033 // not used in MaNGOS, but used in scripting code
13034 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13036 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13040 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13041 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13042 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13047 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13049 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13051 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13053 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13054 if( reqitemcount
!= 0 )
13056 uint32 quest_id
= pQuest
->GetQuestId();
13057 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13059 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13060 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13066 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13068 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13069 if ( GetQuestSlotQuestId(i
) == quest_id
)
13072 return MAX_QUEST_LOG_SIZE
;
13075 void Player::AreaExploredOrEventHappens( uint32 questId
)
13079 uint16 log_slot
= FindQuestSlot( questId
);
13080 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13082 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13084 if(!q_status
.m_explored
)
13086 q_status
.m_explored
= true;
13087 if (q_status
.uState
!= QUEST_NEW
)
13088 q_status
.uState
= QUEST_CHANGED
;
13091 if( CanCompleteQuest( questId
) )
13092 CompleteQuest( questId
);
13096 //not used in mangosd, function for external script library
13097 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13099 if( Group
*pGroup
= GetGroup() )
13101 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13103 Player
*pGroupGuy
= itr
->getSource();
13105 // for any leave or dead (with not released body) group member at appropriate distance
13106 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13107 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13111 AreaExploredOrEventHappens(questId
);
13114 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13116 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13118 uint32 questid
= GetQuestSlotQuestId(i
);
13119 if ( questid
== 0 )
13122 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13124 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13127 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13128 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13131 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13133 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13134 if ( reqitem
== entry
)
13136 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13137 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13138 if ( curitemcount
< reqitemcount
)
13140 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13141 q_status
.m_itemcount
[j
] += additemcount
;
13142 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13144 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13146 if ( CanCompleteQuest( questid
) )
13147 CompleteQuest( questid
);
13152 UpdateForQuestsGO();
13155 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13157 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13159 uint32 questid
= GetQuestSlotQuestId(i
);
13162 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13165 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13168 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13170 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13171 if ( reqitem
== entry
)
13173 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13175 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13176 uint32 curitemcount
;
13177 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13178 curitemcount
= q_status
.m_itemcount
[j
];
13180 curitemcount
= GetItemCount(entry
,true);
13181 if ( curitemcount
< reqitemcount
+ count
)
13183 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13184 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13185 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13187 IncompleteQuest( questid
);
13193 UpdateForQuestsGO();
13196 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13198 uint32 addkillcount
= 1;
13199 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13200 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13202 uint32 questid
= GetQuestSlotQuestId(i
);
13206 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13209 // just if !ingroup || !noraidgroup || raidgroup
13210 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13211 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13213 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13215 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13217 // skip GO activate objective or none
13218 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13221 // skip Cast at creature objective
13222 if(qInfo
->ReqSpell
[j
] !=0 )
13225 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13227 if ( reqkill
== entry
)
13229 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13230 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13231 if ( curkillcount
< reqkillcount
)
13233 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13234 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13236 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13238 if ( CanCompleteQuest( questid
) )
13239 CompleteQuest( questid
);
13241 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13250 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13252 bool isCreature
= IS_CREATURE_GUID(guid
);
13254 uint32 addCastCount
= 1;
13255 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13257 uint32 questid
= GetQuestSlotQuestId(i
);
13261 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13265 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13267 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13269 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13271 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13273 // skip kill creature objective (0) or wrong spell casts
13274 if(qInfo
->ReqSpell
[j
] != spell_id
)
13277 uint32 reqTarget
= 0;
13281 // creature activate objectives
13282 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13283 // checked at quest_template loading
13284 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13288 // GO activate objective
13289 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13290 // checked at quest_template loading
13291 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13294 // other not this creature/GO related objectives
13295 if( reqTarget
!= entry
)
13298 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13299 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13300 if ( curCastCount
< reqCastCount
)
13302 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13303 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13305 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13308 if ( CanCompleteQuest( questid
) )
13309 CompleteQuest( questid
);
13311 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13319 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13321 uint32 addTalkCount
= 1;
13322 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13324 uint32 questid
= GetQuestSlotQuestId(i
);
13328 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13332 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13334 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13336 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13338 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13340 // skip spell casts and Gameobject objectives
13341 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13344 uint32 reqTarget
= 0;
13346 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13347 // checked at quest_template loading
13348 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13352 if ( reqTarget
== entry
)
13354 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13355 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13356 if ( curTalkCount
< reqTalkCount
)
13358 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13359 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13361 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13363 if ( CanCompleteQuest( questid
) )
13364 CompleteQuest( questid
);
13366 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13375 void Player::MoneyChanged( uint32 count
)
13377 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13379 uint32 questid
= GetQuestSlotQuestId(i
);
13383 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13384 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13386 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13388 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13390 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13392 if ( CanCompleteQuest( questid
) )
13393 CompleteQuest( questid
);
13396 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13398 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13399 IncompleteQuest( questid
);
13405 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
13407 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13409 if(uint32 questid
= GetQuestSlotQuestId(i
))
13411 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
))
13413 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
13415 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13416 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13418 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
13419 if ( CanCompleteQuest( questid
) )
13420 CompleteQuest( questid
);
13422 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13424 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
13425 IncompleteQuest( questid
);
13433 bool Player::HasQuestForItem( uint32 itemid
) const
13435 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13437 uint32 questid
= GetQuestSlotQuestId(i
);
13438 if ( questid
== 0 )
13441 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13442 if(qs_itr
== mQuestStatus
.end())
13445 QuestStatusData
const& q_status
= qs_itr
->second
;
13447 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13449 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13453 // hide quest if player is in raid-group and quest is no raid quest
13454 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13457 // There should be no mixed ReqItem/ReqSource drop
13458 // This part for ReqItem drop
13459 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13461 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13464 // This part - for ReqSource
13465 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13467 // examined item is a source item
13468 if (qinfo
->ReqSourceId
[j
] == itemid
)
13470 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13473 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13476 // allows custom amount drop when not 0
13477 if (qinfo
->ReqSourceCount
[j
])
13479 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13481 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13490 void Player::SendQuestComplete( uint32 quest_id
)
13494 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13495 data
<< uint32(quest_id
);
13496 GetSession()->SendPacket( &data
);
13497 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13501 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13503 uint32 questid
= pQuest
->GetQuestId();
13504 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13505 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13506 data
<< uint32(questid
);
13508 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13510 data
<< uint32(XP
);
13511 data
<< uint32(pQuest
->GetRewOrReqMoney());
13516 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13519 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13520 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13521 GetSession()->SendPacket( &data
);
13523 if (pQuest
->GetQuestCompleteScript() != 0)
13524 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13527 void Player::SendQuestFailed( uint32 quest_id
)
13531 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13533 data
<< uint32(0); // failed reason (4 for inventory is full)
13534 GetSession()->SendPacket( &data
);
13535 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13539 void Player::SendQuestTimerFailed( uint32 quest_id
)
13543 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13545 GetSession()->SendPacket( &data
);
13546 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13550 void Player::SendCanTakeQuestResponse( uint32 msg
)
13552 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13553 data
<< uint32(msg
);
13554 GetSession()->SendPacket( &data
);
13555 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13558 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13562 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13563 data
<< uint64(pPlayer
->GetGUID());
13564 data
<< uint8(msg
); // valid values: 0-8
13565 GetSession()->SendPacket( &data
);
13566 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13570 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13572 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13573 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13574 //data << pQuest->ReqItemId[item_idx];
13576 GetSession()->SendPacket( &data
);
13579 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13581 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13583 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13585 // client expected gameobject template id in form (id|0x80000000)
13586 entry
= (-entry
) | 0x80000000;
13588 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13589 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13590 data
<< uint32(pQuest
->GetQuestId());
13591 data
<< uint32(entry
);
13592 data
<< uint32(old_count
+ add_count
);
13593 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13594 data
<< uint64(guid
);
13595 GetSession()->SendPacket(&data
);
13597 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13598 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13599 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13602 /*********************************************************/
13603 /*** LOAD SYSTEM ***/
13604 /*********************************************************/
13606 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13608 bool delete_result
= true;
13611 // 0 1 2 3 4 5 6 7 8 9
13612 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13613 if(!result
) return false;
13615 else delete_result
= false;
13617 Field
*fields
= result
->Fetch();
13619 if(!LoadValues( fields
[1].GetString()))
13621 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13622 if(delete_result
) delete result
;
13626 // overwrite possible wrong/corrupted guid
13627 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13629 m_name
= fields
[2].GetCppString();
13631 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13632 SetMapId(fields
[6].GetUInt32());
13633 // the instance id is not needed at character enum
13635 m_Played_time
[0] = fields
[7].GetUInt32();
13636 m_Played_time
[1] = fields
[8].GetUInt32();
13638 m_atLoginFlags
= fields
[9].GetUInt32();
13640 // I don't see these used anywhere ..
13643 _LoadBoundInstances();*/
13645 if (delete_result
) delete result
;
13647 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13650 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13651 m_deathState
= DEAD
;
13656 void Player::_LoadDeclinedNames(QueryResult
* result
)
13662 delete m_declinedname
;
13664 m_declinedname
= new DeclinedName
;
13665 Field
*fields
= result
->Fetch();
13666 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13667 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13672 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13674 // arenateamid, played_week, played_season, personal_rating
13675 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13681 Field
*fields
= result
->Fetch();
13683 uint32 arenateamid
= fields
[0].GetUInt32();
13684 uint32 played_week
= fields
[1].GetUInt32();
13685 uint32 played_season
= fields
[2].GetUInt32();
13686 uint32 personal_rating
= fields
[3].GetUInt32();
13688 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13691 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13694 uint8 arenaSlot
= aTeam
->GetSlot();
13696 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13697 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13698 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13699 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13700 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13701 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13703 }while (result
->NextRow());
13707 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13709 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13713 Field
*fields
= result
->Fetch();
13715 x
= fields
[0].GetFloat();
13716 y
= fields
[1].GetFloat();
13717 z
= fields
[2].GetFloat();
13718 o
= fields
[3].GetFloat();
13719 mapid
= fields
[4].GetUInt32();
13720 in_flight
= !fields
[5].GetCppString().empty();
13726 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13728 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13732 Field
*fields
= result
->Fetch();
13734 data
= StrSplit(fields
[0].GetCppString(), " ");
13741 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13743 if(index
>= data
.size())
13746 return (uint32
)atoi(data
[index
].c_str());
13749 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13752 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13753 memcpy(&result
, &temp
, sizeof(result
));
13758 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13761 if(!LoadValuesArrayFromDB(data
,guid
))
13764 return GetUInt32ValueFromArray(data
,index
);
13767 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13770 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13771 memcpy(&result
, &temp
, sizeof(result
));
13776 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13778 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13779 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13780 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13784 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13788 Field
*fields
= result
->Fetch();
13790 uint32 dbAccountId
= fields
[1].GetUInt32();
13792 // check if the character's account in the db and the logged in account match.
13793 // player should be able to load/delete character only with correct account!
13794 if( dbAccountId
!= GetSession()->GetAccountId() )
13796 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13801 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13803 m_name
= fields
[3].GetCppString();
13805 // check name limitations
13806 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13809 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13813 if(!LoadValues( fields
[2].GetString()))
13815 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13820 // overwrite possible wrong/corrupted guid
13821 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13823 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13824 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13826 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13827 SetVisibleItemSlot(slot
,NULL
);
13831 delete m_items
[slot
];
13832 m_items
[slot
] = NULL
;
13836 // update money limits
13837 if(GetMoney() > MAX_MONEY_AMOUNT
)
13838 SetMoney(MAX_MONEY_AMOUNT
);
13840 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13843 m_race
= fields
[4].GetUInt8();
13844 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13845 //Other way is to saves m_team into characters table.
13846 setFactionForRace(m_race
);
13849 m_class
= fields
[5].GetUInt8();
13851 // load home bind and check in same time class/race pair, it used later for restore broken positions
13852 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13855 InitPrimaryProffesions(); // to max set before any spell loaded
13857 // init saved position, and fix it later if problematic
13858 uint32 transGUID
= fields
[24].GetUInt32();
13859 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13860 SetMapId(fields
[9].GetUInt32());
13861 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13863 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13865 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
13867 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
13868 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
13869 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
13871 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
13873 // check arena teams integrity
13874 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13876 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13880 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13881 if(at
->HaveMember(GetGUID()))
13884 // arena team not exist or not member, cleanup fields
13885 for(int j
=0; j
< 6; ++j
)
13886 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13889 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13891 if(!IsPositionValid())
13893 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());
13894 RelocateToHomebind();
13898 m_movementInfo
.t_x
= 0.0f
;
13899 m_movementInfo
.t_y
= 0.0f
;
13900 m_movementInfo
.t_z
= 0.0f
;
13901 m_movementInfo
.t_o
= 0.0f
;
13904 uint32 bgid
= fields
[34].GetUInt32();
13905 uint32 bgteam
= fields
[35].GetUInt32();
13907 if(bgid
) //saved in BattleGround
13909 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13911 // check entry point and fix to homebind if need
13912 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
13913 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
13914 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
13916 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
, BATTLEGROUND_TYPE_NONE
);
13918 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
13920 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
13921 uint32 queueSlot
= AddBattleGroundQueueId(bgQueueTypeId
);
13923 SetBattleGroundId(currentBg
->GetInstanceID(), currentBg
->GetTypeID());
13926 //join player to battleground group
13927 currentBg
->EventPlayerLoggedIn(this, GetGUID());
13928 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
13930 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
13934 Relocate(GetBattleGroundEntryPoint());
13935 //RemoveArenaAuras(true);
13940 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
13941 // if server restart after player save in BG or area
13942 // player can have current coordinates in to BG/Arean map, fix this
13943 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
13945 // return to BG master
13946 SetMapId(fields
[36].GetUInt32());
13947 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13949 // check entry point and fix to homebind if need
13950 mapEntry
= sMapStore
.LookupEntry(GetMapId());
13951 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
13952 RelocateToHomebind();
13956 if (transGUID
!= 0)
13958 m_movementInfo
.t_x
= fields
[20].GetFloat();
13959 m_movementInfo
.t_y
= fields
[21].GetFloat();
13960 m_movementInfo
.t_z
= fields
[22].GetFloat();
13961 m_movementInfo
.t_o
= fields
[23].GetFloat();
13963 if( !MaNGOS::IsValidMapCoord(
13964 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13965 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13966 // transport size limited
13967 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13969 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13970 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13971 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13973 RelocateToHomebind();
13975 m_movementInfo
.t_x
= 0.0f
;
13976 m_movementInfo
.t_y
= 0.0f
;
13977 m_movementInfo
.t_z
= 0.0f
;
13978 m_movementInfo
.t_o
= 0.0f
;
13984 if (transGUID
!= 0)
13986 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13988 if( (*iter
)->GetGUIDLow() == transGUID
)
13990 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
13991 // client without expansion support
13992 if(GetSession()->Expansion() < transMapEntry
->Expansion())
13994 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
13998 m_transport
= *iter
;
13999 m_transport
->AddPassenger(this);
14000 SetMapId(m_transport
->GetMapId());
14007 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14010 RelocateToHomebind();
14012 m_movementInfo
.t_x
= 0.0f
;
14013 m_movementInfo
.t_y
= 0.0f
;
14014 m_movementInfo
.t_z
= 0.0f
;
14015 m_movementInfo
.t_o
= 0.0f
;
14020 else // not transport case
14022 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14023 // client without expansion support
14024 if(GetSession()->Expansion() < mapEntry
->Expansion())
14026 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14027 RelocateToHomebind();
14031 // NOW player must have valid map
14032 // load the player's map here if it's not already loaded
14033 Map
*map
= GetMap();
14035 // since the player may not be bound to the map yet, make sure subsequent
14036 // getmap calls won't create new maps
14037 SetInstanceId(map
->GetInstanceId());
14039 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14040 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14042 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14044 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14046 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());
14049 SaveRecallPosition();
14051 time_t now
= time(NULL
);
14052 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14054 // since last logout (in seconds)
14055 uint64 time_diff
= uint64(now
- logoutTime
);
14057 // set value, including drunk invisibility detection
14058 // calculate sobering. after 15 minutes logged out, the player will be sober again
14060 if(time_diff
> 15*MINUTE
)
14063 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14064 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14065 SetDrunkValue(newDrunkenValue
);
14067 m_rest_bonus
= fields
[15].GetFloat();
14068 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14069 float bubble0
= 0.031;
14070 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14071 float bubble1
= 0.125;
14073 if((int32
)fields
[16].GetUInt32() > 0)
14075 float bubble
= fields
[17].GetUInt32() > 0
14076 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14077 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14079 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14082 m_cinematic
= fields
[12].GetUInt32();
14083 m_Played_time
[0]= fields
[13].GetUInt32();
14084 m_Played_time
[1]= fields
[14].GetUInt32();
14086 m_resetTalentsCost
= fields
[18].GetUInt32();
14087 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14089 // reserve some flags
14090 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14092 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14093 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14095 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14097 uint32 extraflags
= fields
[25].GetUInt32();
14099 m_stableSlots
= fields
[26].GetUInt32();
14100 if(m_stableSlots
> MAX_PET_STABLES
)
14102 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
14103 m_stableSlots
= MAX_PET_STABLES
;
14106 m_atLoginFlags
= fields
[27].GetUInt32();
14109 // Update Honor kills data
14110 m_lastHonorUpdateTime
= logoutTime
;
14111 UpdateHonorFields();
14113 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14114 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14115 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14117 std::string taxi_nodes
= fields
[31].GetCppString();
14121 // clear channel spell data (if saved at channel spell casting)
14122 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14123 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14125 // clear charm/summon related fields
14132 // reset some aura modifiers before aura apply
14133 SetFarSightGUID(0);
14134 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14135 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14139 // make sure the unit is considered out of combat for proper loading
14142 // make sure the unit is considered not in duel for proper loading
14143 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14144 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14146 // remember loaded power/health values to restore after stats initialization and modifier applying
14147 uint32 savedHealth
= GetHealth();
14148 uint32 savedPower
[MAX_POWERS
];
14149 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14150 savedPower
[i
] = GetPower(Powers(i
));
14152 // reset stats before loading any modifiers
14153 InitStatsForLevel();
14154 InitTaxiNodesForLevel();
14155 InitGlyphsForLevel();
14158 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14160 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14163 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14166 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14167 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14168 m_deathState
= DEAD
;
14170 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14172 // after spell load, learn rewarded spell if need also
14173 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14174 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14176 // after spell and quest load
14177 InitTalentForLevel();
14178 learnDefaultSpells();
14180 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14182 // must be before inventory (some items required reputation check)
14183 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14185 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14187 // update items with duration and realtime
14188 UpdateItemDuration(time_diff
, true);
14190 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14192 // unread mails and next delivery time, actual mails not loaded
14193 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14195 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14197 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14198 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14199 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14201 if(!HasTitle(curTitle
))
14202 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14205 // Not finish taxi flight path
14206 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14208 // problems with taxi path loading
14209 TaxiNodesEntry
const* nodeEntry
= NULL
;
14210 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14211 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14213 if(!nodeEntry
) // don't know taxi start node, to homebind
14215 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14216 RelocateToHomebind();
14217 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14219 else // have start node, to it
14221 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14222 SetMapId(nodeEntry
->map_id
);
14223 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14224 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14226 m_taxi
.ClearTaxiDestinations();
14228 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14230 // save source node as recall coord to prevent recall and fall from sky
14231 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14232 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14233 m_recallMap
= nodeEntry
->map_id
;
14234 m_recallX
= nodeEntry
->x
;
14235 m_recallY
= nodeEntry
->y
;
14236 m_recallZ
= nodeEntry
->z
;
14238 // flight will started later
14241 // has to be called after last Relocate() in Player::LoadFromDB
14242 SetFallInformation(0, GetPositionZ());
14244 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14246 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14247 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14249 RemoveAllAurasOnDeath();
14251 //apply all stat bonuses from items and auras
14252 SetCanModifyStats(true);
14255 // restore remembered power/health values (but not more max values)
14256 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14257 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14258 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14260 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14264 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14266 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14269 case 0: break; // disable
14270 case 1: SetGameMaster(true); break; // enable
14271 case 2: // save state
14272 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14273 SetGameMaster(true);
14277 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14280 case 0: SetGMVisible(false); break; // invisible
14281 case 1: break; // visible
14282 case 2: // save state
14283 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14284 SetGMVisible(false);
14288 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14291 case 0: break; // disable
14292 case 1: SetAcceptTicket(true); break; // enable
14293 case 2: // save state
14294 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14295 SetAcceptTicket(true);
14299 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14302 case 0: break; // disable
14303 case 1: SetGMChat(true); break; // enable
14304 case 2: // save state
14305 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14310 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14313 case 0: break; // disable
14314 case 1: SetAcceptWhispers(true); break; // enable
14315 case 2: // save state
14316 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14317 SetAcceptWhispers(true);
14322 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14324 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14325 m_achievementMgr
.CheckAllAchievementCriteria();
14329 bool Player::isAllowedToLoot(Creature
* creature
)
14331 if(Player
* recipient
= creature
->GetLootRecipient())
14333 if (recipient
== this)
14335 if( Group
* otherGroup
= recipient
->GetGroup())
14337 Group
* thisGroup
= GetGroup();
14340 return thisGroup
== otherGroup
;
14345 // prevent other players from looting if the recipient got disconnected
14346 return !creature
->hasLootRecipient();
14349 void Player::_LoadActions(QueryResult
*result
)
14351 m_actionButtons
.clear();
14353 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14359 Field
*fields
= result
->Fetch();
14361 uint8 button
= fields
[0].GetUInt8();
14363 if(addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8()))
14364 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14367 sLog
.outError( " ...at loading, and will deleted in DB also");
14369 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14370 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14373 while( result
->NextRow() );
14379 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14382 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14383 m_modAuras
[i
].clear();
14385 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14391 Field
*fields
= result
->Fetch();
14392 uint64 caster_guid
= fields
[0].GetUInt64();
14393 uint32 spellid
= fields
[1].GetUInt32();
14394 uint32 effindex
= fields
[2].GetUInt32();
14395 uint32 stackcount
= fields
[3].GetUInt32();
14396 int32 damage
= (int32
)fields
[4].GetUInt32();
14397 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14398 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14399 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14401 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14404 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14410 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14414 // negative effects should continue counting down after logout
14415 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14417 if(remaintime
<= int32(timediff
))
14420 remaintime
-= timediff
;
14423 // prevent wrong values of remaincharges
14424 if(spellproto
->procCharges
)
14426 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14427 remaincharges
= spellproto
->procCharges
;
14433 for(uint32 i
=0; i
<stackcount
; i
++)
14435 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14437 damage
= aura
->GetModifier()->m_amount
;
14439 // reset stolen single target auras
14440 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
14441 aura
->SetIsSingleTarget(false);
14443 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14445 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14448 while( result
->NextRow() );
14453 if(m_class
== CLASS_WARRIOR
)
14454 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14457 void Player::_LoadGlyphAuras()
14459 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
14461 if (uint32 glyph
= GetGlyph(i
))
14463 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14465 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14467 if(gp
->TypeFlags
== gs
->TypeFlags
)
14469 CastSpell(this, gp
->SpellId
, true);
14473 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14476 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14479 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14481 // On any error remove glyph
14487 void Player::LoadCorpse()
14491 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14495 if(Corpse
*corpse
= GetCorpse())
14497 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14501 //Prevent Dead Player login without corpse
14502 ResurrectPlayer(0.5f
);
14507 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14509 //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());
14510 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14511 //NOTE: the "order by `bag`" is important because it makes sure
14512 //the bagMap is filled before items in the bags are loaded
14513 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14514 //expected to be equipped before offhand items (TODO: fixme)
14516 uint32 zone
= GetZoneId();
14520 std::list
<Item
*> problematicItems
;
14522 // prevent items from being added to the queue when stored
14523 m_itemUpdateQueueBlocked
= true;
14526 Field
*fields
= result
->Fetch();
14527 uint32 bag_guid
= fields
[1].GetUInt32();
14528 uint8 slot
= fields
[2].GetUInt8();
14529 uint32 item_guid
= fields
[3].GetUInt32();
14530 uint32 item_id
= fields
[4].GetUInt32();
14532 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14536 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14537 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14538 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14542 Item
*item
= NewItemOrBag(proto
);
14544 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14546 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14547 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14548 item
->FSetState(ITEM_REMOVED
);
14549 item
->SaveToDB(); // it also deletes item object !
14553 // not allow have in alive state item limited to another map/zone
14554 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14556 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14557 item
->FSetState(ITEM_REMOVED
);
14558 item
->SaveToDB(); // it also deletes item object !
14562 // "Conjured items disappear if you are logged out for more than 15 minutes"
14563 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14565 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14566 item
->FSetState(ITEM_REMOVED
);
14567 item
->SaveToDB(); // it also deletes item object !
14571 bool success
= true;
14575 // the item is not in a bag
14576 item
->SetContainer( NULL
);
14577 item
->SetSlot(slot
);
14579 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14581 ItemPosCountVec dest
;
14582 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14583 item
= StoreItem(dest
, item
, true);
14587 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14590 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14591 QuickEquipItem(dest
, item
);
14595 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14597 ItemPosCountVec dest
;
14598 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14599 item
= BankItem(dest
, item
, true);
14606 // store bags that may contain items in them
14607 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14608 bagMap
[item_guid
] = (Bag
*)item
;
14613 item
->SetSlot(NULL_SLOT
);
14614 // the item is in a bag, find the bag
14615 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14616 if(itr
!= bagMap
.end())
14617 itr
->second
->StoreItem(slot
, item
, true );
14622 // item's state may have changed after stored
14624 item
->SetState(ITEM_UNCHANGED
, this);
14627 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
);
14628 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14629 problematicItems
.push_back(item
);
14631 } while (result
->NextRow());
14634 m_itemUpdateQueueBlocked
= false;
14636 // send by mail problematic items
14637 while(!problematicItems
.empty())
14640 MailItemsInfo mi
; // item list preparing
14642 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14644 Item
* item
= problematicItems
.front();
14645 problematicItems
.pop_front();
14647 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14650 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14652 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14656 _ApplyAllItemMods();
14659 // load mailed item which should receive current player
14660 void Player::_LoadMailedItems(Mail
*mail
)
14662 // data needs to be at first place for Item::LoadFromDB
14663 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
);
14669 Field
*fields
= result
->Fetch();
14670 uint32 item_guid_low
= fields
[1].GetUInt32();
14671 uint32 item_template
= fields
[2].GetUInt32();
14673 mail
->AddItem(item_guid_low
, item_template
);
14675 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14679 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
);
14680 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14681 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14685 Item
*item
= NewItemOrBag(proto
);
14687 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14689 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14690 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14691 item
->FSetState(ITEM_REMOVED
);
14692 item
->SaveToDB(); // it also deletes item object !
14697 } while (result
->NextRow());
14702 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14704 //set a count of unread mails
14705 //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);
14708 Field
*fieldMail
= resultUnread
->Fetch();
14709 unReadMails
= fieldMail
[0].GetUInt8();
14710 delete resultUnread
;
14713 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14714 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14715 if (resultDelivery
)
14717 Field
*fieldMail
= resultDelivery
->Fetch();
14718 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14719 delete resultDelivery
;
14723 void Player::_LoadMail()
14726 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14727 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());
14732 Field
*fields
= result
->Fetch();
14733 Mail
*m
= new Mail
;
14734 m
->messageID
= fields
[0].GetUInt32();
14735 m
->messageType
= fields
[1].GetUInt8();
14736 m
->sender
= fields
[2].GetUInt32();
14737 m
->receiver
= fields
[3].GetUInt32();
14738 m
->subject
= fields
[4].GetCppString();
14739 m
->itemTextId
= fields
[5].GetUInt32();
14740 bool has_items
= fields
[6].GetBool();
14741 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14742 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14743 m
->money
= fields
[9].GetUInt32();
14744 m
->COD
= fields
[10].GetUInt32();
14745 m
->checked
= fields
[11].GetUInt32();
14746 m
->stationery
= fields
[12].GetUInt8();
14747 m
->mailTemplateId
= fields
[13].GetInt16();
14749 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14751 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14752 m
->mailTemplateId
= 0;
14755 m
->state
= MAIL_STATE_UNCHANGED
;
14758 _LoadMailedItems(m
);
14760 m_mail
.push_back(m
);
14761 } while( result
->NextRow() );
14764 m_mailsLoaded
= true;
14767 void Player::LoadPet()
14769 //fixme: the pet should still be loaded if the player is not in world
14770 // just not added to the map
14773 Pet
*pet
= new Pet
;
14774 if(!pet
->LoadPetFromDB(this,0,0,true))
14779 void Player::_LoadQuestStatus(QueryResult
*result
)
14781 mQuestStatus
.clear();
14785 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14786 //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());
14792 Field
*fields
= result
->Fetch();
14794 uint32 quest_id
= fields
[0].GetUInt32();
14795 // used to be new, no delete?
14796 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14800 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14802 uint32 qstatus
= fields
[1].GetUInt32();
14803 if(qstatus
< MAX_QUEST_STATUS
)
14804 questStatusData
.m_status
= QuestStatus(qstatus
);
14807 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14808 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14811 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14812 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14814 time_t quest_time
= time_t(fields
[4].GetUInt64());
14816 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14818 AddTimedQuest( quest_id
);
14820 if (quest_time
<= sWorld
.GetGameTime())
14821 questStatusData
.m_timer
= 1;
14823 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
14828 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14829 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14830 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14831 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14832 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14833 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14834 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14835 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14837 questStatusData
.uState
= QUEST_UNCHANGED
;
14839 // add to quest log
14840 if( slot
< MAX_QUEST_LOG_SIZE
&&
14841 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14842 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14843 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14845 SetQuestSlot(slot
,quest_id
,quest_time
);
14847 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14848 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14850 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14851 if(questStatusData
.m_creatureOrGOcount
[idx
])
14852 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14857 if(questStatusData
.m_rewarded
)
14859 // learn rewarded spell if unknown
14860 learnQuestRewardedSpells(pQuest
);
14862 // set rewarded title if any
14863 if(pQuest
->GetCharTitleId())
14865 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14866 SetTitle(titleEntry
);
14869 if(pQuest
->GetBonusTalents())
14870 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
14873 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14876 while( result
->NextRow() );
14881 // clear quest log tail
14882 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14886 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14888 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14889 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14891 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14895 uint32 quest_daily_idx
= 0;
14899 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14901 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14905 Field
*fields
= result
->Fetch();
14907 uint32 quest_id
= fields
[0].GetUInt32();
14909 // save _any_ from daily quest times (it must be after last reset anyway)
14910 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14912 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14916 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14919 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14921 while( result
->NextRow() );
14926 m_DailyQuestChanged
= false;
14929 void Player::_LoadSpells(QueryResult
*result
)
14931 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14937 Field
*fields
= result
->Fetch();
14939 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
14941 while( result
->NextRow() );
14947 void Player::_LoadTutorials(QueryResult
*result
)
14949 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14955 Field
*fields
= result
->Fetch();
14957 for (int iI
=0; iI
<8; iI
++)
14958 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14960 while( result
->NextRow() );
14965 m_TutorialsChanged
= false;
14968 void Player::_LoadGroup(QueryResult
*result
)
14970 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14973 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14975 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14978 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14979 SetGroup(group
, subgroup
);
14980 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14982 // the group leader may change the instance difficulty while the player is offline
14983 SetDifficulty(group
->GetDifficulty());
14989 void Player::_LoadBoundInstances(QueryResult
*result
)
14991 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14992 m_boundInstances
[i
].clear();
14994 Group
*group
= GetGroup();
14996 //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));
15001 Field
*fields
= result
->Fetch();
15002 bool perm
= fields
[1].GetBool();
15003 uint32 mapId
= fields
[2].GetUInt32();
15004 uint32 instanceId
= fields
[0].GetUInt32();
15005 uint8 difficulty
= fields
[3].GetUInt8();
15006 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15007 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15008 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15009 // and in that case it is not used
15011 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
15012 if(!mapEntry
|| !mapEntry
->IsDungeon())
15014 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
15015 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15021 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
);
15022 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15026 // since non permanent binds are always solo bind, they can always be reset
15027 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15028 if(save
) BindToInstance(save
, perm
, true);
15029 } while(result
->NextRow());
15034 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15036 // some instances only have one difficulty
15037 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15038 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15040 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15041 if(itr
!= m_boundInstances
[difficulty
].end())
15042 return &itr
->second
;
15047 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15049 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15050 UnbindInstance(itr
, difficulty
, unload
);
15053 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15055 if(itr
!= m_boundInstances
[difficulty
].end())
15057 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15058 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15059 m_boundInstances
[difficulty
].erase(itr
++);
15063 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15067 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15070 // update the save when the group kills a boss
15071 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15072 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());
15075 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15077 if(bind
.save
!= save
)
15079 if(bind
.save
) bind
.save
->RemovePlayer(this);
15080 save
->AddPlayer(this);
15083 if(permanent
) save
->SetCanReset(false);
15086 bind
.perm
= permanent
;
15087 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());
15094 void Player::SendRaidInfo()
15096 uint32 counter
= 0;
15098 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15100 size_t p_counter
= data
.wpos();
15101 data
<< uint32(counter
); // placeholder
15103 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15105 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15107 if(itr
->second
.perm
)
15109 InstanceSave
*save
= itr
->second
.save
;
15110 data
<< uint32(save
->GetMapId());
15111 data
<< uint32(save
->GetResetTime() - time(NULL
));
15112 data
<< uint32(save
->GetInstanceId());
15113 data
<< uint32(save
->GetDifficulty());
15118 data
.put
<uint32
>(p_counter
,counter
);
15119 GetSession()->SendPacket(&data
);
15123 - called on every successful teleportation to a map
15125 void Player::SendSavedInstances()
15127 bool hasBeenSaved
= false;
15130 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15132 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15134 if(itr
->second
.perm
) // only permanent binds are sent
15136 hasBeenSaved
= true;
15142 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15143 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15144 data
<< uint32(hasBeenSaved
);
15145 GetSession()->SendPacket(&data
);
15150 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15152 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15154 if(itr
->second
.perm
)
15156 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15157 data
<< uint32(itr
->second
.save
->GetMapId());
15158 GetSession()->SendPacket(&data
);
15164 /// convert the player's binds to the group
15165 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15167 bool has_binds
= false;
15168 bool has_solo
= false;
15170 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15171 assert(player_guid
);
15173 // copy all binds to the group, when changing leader it's assumed the character
15174 // will not have any solo binds
15178 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15180 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15183 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15184 // permanent binds are not removed
15185 if(!itr
->second
.perm
)
15187 player
->UnbindInstance(itr
, i
, true); // increments itr
15196 // if the player's not online we don't know what binds it has
15197 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
));
15198 // the following should not get executed when changing leaders
15199 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15202 bool Player::_LoadHomeBind(QueryResult
*result
)
15204 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15207 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15212 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15215 Field
*fields
= result
->Fetch();
15216 m_homebindMapId
= fields
[0].GetUInt32();
15217 m_homebindZoneId
= fields
[1].GetUInt16();
15218 m_homebindX
= fields
[2].GetFloat();
15219 m_homebindY
= fields
[3].GetFloat();
15220 m_homebindZ
= fields
[4].GetFloat();
15223 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15225 // accept saved data only for valid position (and non instanceable), and accessable
15226 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15227 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15232 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15237 m_homebindMapId
= info
->mapId
;
15238 m_homebindZoneId
= info
->zoneId
;
15239 m_homebindX
= info
->positionX
;
15240 m_homebindY
= info
->positionY
;
15241 m_homebindZ
= info
->positionZ
;
15243 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
);
15246 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15247 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15252 /*********************************************************/
15253 /*** SAVE SYSTEM ***/
15254 /*********************************************************/
15256 void Player::SaveToDB()
15258 // delay auto save at any saves (manual, in code, or autosave)
15259 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15261 // first save/honor gain after midnight will also update the player's honor fields
15262 UpdateHonorFields();
15264 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15265 //save, far from tavern/city
15266 //save, but in tavern/city
15267 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15270 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15271 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15272 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15273 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15274 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15275 uint32 tmp_displayid
= GetDisplayId();
15277 // Set player sit state to standing on save, also stealth and shifted form
15278 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15279 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15280 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15281 SetDisplayId(GetNativeDisplayId());
15283 bool inworld
= IsInWorld();
15285 CharacterDatabase
.BeginTransaction();
15287 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15289 std::string sql_name
= m_name
;
15290 CharacterDatabase
.escape_string(sql_name
);
15292 std::ostringstream ss
;
15293 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15294 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15295 "taximask, online, cinematic, "
15296 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15297 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15298 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15299 << GetGUIDLow() << ", "
15300 << GetSession()->GetAccountId() << ", '"
15301 << sql_name
<< "', "
15303 << m_class
<< ", ";
15305 if(!IsBeingTeleported())
15307 ss
<< GetMapId() << ", "
15308 << (uint32
)GetDifficulty() << ", "
15309 << finiteAlways(GetPositionX()) << ", "
15310 << finiteAlways(GetPositionY()) << ", "
15311 << finiteAlways(GetPositionZ()) << ", "
15312 << finiteAlways(GetOrientation()) << ", '";
15316 ss
<< GetTeleportDest().mapid
<< ", "
15317 << (uint32
)GetDifficulty() << ", "
15318 << finiteAlways(GetTeleportDest().x
) << ", "
15319 << finiteAlways(GetTeleportDest().y
) << ", "
15320 << finiteAlways(GetTeleportDest().z
) << ", "
15321 << finiteAlways(GetTeleportDest().o
) << ", '";
15325 for( i
= 0; i
< m_valuesCount
; i
++ )
15327 ss
<< GetUInt32Value(i
) << " ";
15332 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15335 ss
<< (inworld
? 1 : 0);
15341 ss
<< m_Played_time
[0];
15343 ss
<< m_Played_time
[1];
15346 ss
<< finiteAlways(m_rest_bonus
);
15348 ss
<< (uint64
)time(NULL
);
15350 ss
<< is_save_resting
;
15352 ss
<< m_resetTalentsCost
;
15354 ss
<< (uint64
)m_resetTalentsTime
;
15357 ss
<< finiteAlways(m_movementInfo
.t_x
);
15359 ss
<< finiteAlways(m_movementInfo
.t_y
);
15361 ss
<< finiteAlways(m_movementInfo
.t_z
);
15363 ss
<< finiteAlways(m_movementInfo
.t_o
);
15366 ss
<< m_transport
->GetGUIDLow();
15371 ss
<< m_ExtraFlags
;
15374 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15377 ss
<< uint32(m_atLoginFlags
);
15383 ss
<< (uint64
)m_deathExpireTime
;
15386 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15388 ss
<< GetBattleGroundId();
15392 ss
<< m_bgEntryPoint
.mapid
<< ", "
15393 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15394 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15395 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15396 << finiteAlways(m_bgEntryPoint
.o
);
15399 CharacterDatabase
.Execute( ss
.str().c_str() );
15401 if(m_mailsUpdated
) //save mails only when needed
15405 _SaveQuestStatus();
15406 _SaveDailyQuestStatus();
15409 _SaveSpellCooldowns();
15412 m_achievementMgr
.SaveToDB();
15413 m_reputationMgr
.SaveToDB();
15415 CharacterDatabase
.CommitTransaction();
15417 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15418 SetDisplayId(tmp_displayid
);
15419 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15420 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15421 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15422 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15424 // save pet (hunter pet level and experience and all type pets health/mana).
15425 if(Pet
* pet
= GetPet())
15426 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15429 // fast save function for item/money cheating preventing - save only inventory and money state
15430 void Player::SaveInventoryAndGoldToDB()
15433 //money is in data field
15434 SaveDataFieldToDB();
15437 void Player::_SaveActions()
15439 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15441 switch (itr
->second
.uState
)
15443 case ACTIONBUTTON_NEW
:
15444 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15445 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15446 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15449 case ACTIONBUTTON_CHANGED
:
15450 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15451 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15452 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15455 case ACTIONBUTTON_DELETED
:
15456 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15457 m_actionButtons
.erase(itr
++);
15466 void Player::_SaveAuras()
15468 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15470 AuraMap
const& auras
= GetAuras();
15475 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15476 uint32 stackCounter
= 1;
15478 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15480 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15482 AuraMap::const_iterator itr2
= itr
;
15483 // save previous spellEffectPair to db
15486 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15488 //skip all auras from spells that are passive or need a shapeshift
15489 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15491 //do not save single target auras (unless they were cast by the player)
15492 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && itr2
->second
->IsSingleTarget()))
15495 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15496 for (i
= 0; i
< 3; i
++)
15497 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15498 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15503 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15504 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15505 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()));
15510 if(itr
== auras
.end())
15514 if (lastEffectPair
== itr
->first
)
15518 lastEffectPair
= itr
->first
;
15524 void Player::_SaveInventory()
15526 // force items in buyback slots to new state
15527 // and remove those that aren't already
15528 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15530 Item
*item
= m_items
[i
];
15531 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15532 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15533 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15534 m_items
[i
]->FSetState(ITEM_NEW
);
15537 // update enchantment durations
15538 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15540 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15544 if (m_itemUpdateQueue
.empty()) return;
15546 // do not save if the update queue is corrupt
15547 bool error
= false;
15548 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15550 Item
*item
= m_itemUpdateQueue
[i
];
15551 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15552 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15556 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());
15559 else if (test
!= item
)
15561 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());
15568 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15569 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15573 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15575 Item
*item
= m_itemUpdateQueue
[i
];
15576 if(!item
) continue;
15578 Bag
*container
= item
->GetContainer();
15579 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15581 switch(item
->GetState())
15584 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());
15587 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());
15590 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15592 case ITEM_UNCHANGED
:
15596 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15598 m_itemUpdateQueue
.clear();
15601 void Player::_SaveMail()
15603 if (!m_mailsLoaded
)
15606 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15609 if (m
->state
== MAIL_STATE_CHANGED
)
15611 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'",
15612 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15613 if(m
->removedItems
.size())
15615 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15616 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15617 m
->removedItems
.clear();
15619 m
->state
= MAIL_STATE_UNCHANGED
;
15621 else if (m
->state
== MAIL_STATE_DELETED
)
15624 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15625 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15627 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15628 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15629 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15633 //deallocate deleted mails...
15634 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15636 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15641 itr
= m_mail
.begin();
15647 m_mailsUpdated
= false;
15650 void Player::_SaveQuestStatus()
15652 // we don't need transactions here.
15653 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15655 switch (i
->second
.uState
)
15658 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15659 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15660 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]);
15662 case QUEST_CHANGED
:
15663 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' ",
15664 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
);
15666 case QUEST_UNCHANGED
:
15669 i
->second
.uState
= QUEST_UNCHANGED
;
15673 void Player::_SaveDailyQuestStatus()
15675 if(!m_DailyQuestChanged
)
15678 m_DailyQuestChanged
= false;
15680 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15682 // we don't need transactions here.
15683 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15684 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15685 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15686 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15687 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15690 void Player::_SaveSpells()
15692 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15694 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15695 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15697 // add only changed/new not dependent spells
15698 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15699 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);
15701 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15703 delete itr
->second
;
15704 m_spells
.erase(itr
++);
15708 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15715 void Player::_SaveTutorials()
15717 if(!m_TutorialsChanged
)
15721 // it's better than rebuilding indexes multiple times
15722 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15725 Rows
= result
->Fetch()[0].GetUInt32();
15731 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'",
15732 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
);
15736 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]);
15739 m_TutorialsChanged
= false;
15742 void Player::outDebugValues() const
15744 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15747 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15748 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15749 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15750 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15751 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15752 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15753 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15754 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15755 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15756 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15757 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15758 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15761 /*********************************************************/
15762 /*** FLOOD FILTER SYSTEM ***/
15763 /*********************************************************/
15765 void Player::UpdateSpeakTime()
15767 // ignore chat spam protection for GMs in any mode
15768 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15771 time_t current
= time (NULL
);
15772 if(m_speakTime
> current
)
15774 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15779 if(m_speakCount
>= max_count
)
15781 // prevent overwrite mute time, if message send just before mutes set, for example.
15782 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15783 if(GetSession()->m_muteTime
< new_mute
)
15784 GetSession()->m_muteTime
= new_mute
;
15792 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15795 bool Player::CanSpeak() const
15797 return GetSession()->m_muteTime
<= time (NULL
);
15800 /*********************************************************/
15801 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15802 /*********************************************************/
15804 void Player::SendAttackSwingNotInRange()
15806 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15807 GetSession()->SendPacket( &data
);
15810 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15812 std::ostringstream ss
;
15813 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15814 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15815 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15816 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15817 sLog
.outDebug(ss
.str().c_str());
15818 CharacterDatabase
.Execute(ss
.str().c_str());
15821 void Player::SaveDataFieldToDB()
15823 std::ostringstream ss
;
15824 ss
<<"UPDATE characters SET data='";
15826 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
15828 ss
<< GetUInt32Value(i
) << " ";
15830 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15832 CharacterDatabase
.Execute(ss
.str().c_str());
15835 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15837 std::ostringstream ss2
;
15838 ss2
<<"UPDATE characters SET data='";
15840 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15842 ss2
<<tokens
[i
]<<" ";
15844 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15846 return CharacterDatabase
.Execute(ss2
.str().c_str());
15849 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15852 snprintf(buf
,11,"%u",value
);
15854 if(index
>= tokens
.size())
15857 tokens
[index
] = buf
;
15860 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15863 if(!LoadValuesArrayFromDB(tokens
,guid
))
15866 if(index
>= tokens
.size())
15870 snprintf(buf
,11,"%u",value
);
15871 tokens
[index
] = buf
;
15873 SaveValuesArrayInDB(tokens
,guid
);
15876 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15879 memcpy(&temp
, &value
, sizeof(value
));
15880 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15883 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
15886 if(!LoadValuesArrayFromDB(tokens
, guid
))
15889 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
15890 uint8 race
= unit_bytes0
& 0xFF;
15891 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
15893 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
15897 unit_bytes0
&= ~(0xFF << 16);
15898 unit_bytes0
|= (gender
<< 16);
15899 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
15901 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15902 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15904 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
15906 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
15907 player_bytes2
&= ~0xFF;
15908 player_bytes2
|= facialHair
;
15909 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
15911 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
15912 player_bytes3
&= ~0xFF;
15913 player_bytes3
|= gender
;
15914 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
15916 SaveValuesArrayInDB(tokens
, guid
);
15919 void Player::SendAttackSwingNotStanding()
15921 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15922 GetSession()->SendPacket( &data
);
15925 void Player::SendAttackSwingDeadTarget()
15927 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15928 GetSession()->SendPacket( &data
);
15931 void Player::SendAttackSwingCantAttack()
15933 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15934 GetSession()->SendPacket( &data
);
15937 void Player::SendAttackSwingCancelAttack()
15939 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15940 GetSession()->SendPacket( &data
);
15943 void Player::SendAttackSwingBadFacingAttack()
15945 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15946 GetSession()->SendPacket( &data
);
15949 void Player::SendAutoRepeatCancel()
15951 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15952 data
.append(GetPackGUID()); // may be it's target guid
15953 GetSession()->SendPacket( &data
);
15956 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15958 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15960 data
<< Experience
;
15961 GetSession()->SendPacket(&data
);
15964 void Player::SendDungeonDifficulty(bool IsInGroup
)
15966 uint8 val
= 0x00000001;
15967 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15968 data
<< (uint32
)GetDifficulty();
15969 data
<< uint32(val
);
15970 data
<< uint32(IsInGroup
);
15971 GetSession()->SendPacket(&data
);
15974 void Player::SendResetFailedNotify(uint32 mapid
)
15976 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15977 data
<< uint32(mapid
);
15978 GetSession()->SendPacket(&data
);
15981 /// Reset all solo instances and optionally send a message on success for each
15982 void Player::ResetInstances(uint8 method
)
15984 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15986 // we assume that when the difficulty changes, all instances that can be reset will be
15987 uint8 dif
= GetDifficulty();
15989 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15991 InstanceSave
*p
= itr
->second
.save
;
15992 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15993 if(!entry
|| !p
->CanReset())
15999 if(method
== INSTANCE_RESET_ALL
)
16001 // the "reset all instances" method can only reset normal maps
16002 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16009 // if the map is loaded, reset it
16010 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16011 if(map
&& map
->IsDungeon())
16012 ((InstanceMap
*)map
)->Reset(method
);
16014 // since this is a solo instance there should not be any players inside
16015 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16016 SendResetInstanceSuccess(p
->GetMapId());
16019 m_boundInstances
[dif
].erase(itr
++);
16021 // the following should remove the instance save from the manager and delete it as well
16022 p
->RemovePlayer(this);
16026 void Player::SendResetInstanceSuccess(uint32 MapId
)
16028 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16030 GetSession()->SendPacket(&data
);
16033 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16035 // TODO: find what other fail reasons there are besides players in the instance
16036 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16039 GetSession()->SendPacket(&data
);
16042 /*********************************************************/
16043 /*** Update timers ***/
16044 /*********************************************************/
16046 ///checks the 15 afk reports per 5 minutes limit
16047 void Player::UpdateAfkReport(time_t currTime
)
16049 if(m_bgAfkReportedTimer
<= currTime
)
16051 m_bgAfkReportedCount
= 0;
16052 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16056 void Player::UpdateContestedPvP(uint32 diff
)
16058 if(!m_contestedPvPTimer
||isInCombat())
16060 if(m_contestedPvPTimer
<= diff
)
16062 ResetContestedPvP();
16065 m_contestedPvPTimer
-= diff
;
16068 void Player::UpdatePvPFlag(time_t currTime
)
16072 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16078 void Player::UpdateDuelFlag(time_t currTime
)
16080 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16083 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16084 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16086 duel
->startTimer
= 0;
16087 duel
->startTime
= currTime
;
16088 duel
->opponent
->duel
->startTimer
= 0;
16089 duel
->opponent
->duel
->startTime
= currTime
;
16092 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16097 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16099 //returning of reagents only for players, so best done here
16100 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16101 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16105 for(uint32 i
= 0; i
< 7; ++i
)
16107 if(spellInfo
->Reagent
[i
] > 0)
16109 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16110 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16111 if( msg
== EQUIP_ERR_OK
)
16113 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16115 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16120 m_temporaryUnsummonedPetNumber
= 0;
16123 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16126 // only if current pet in slot
16127 switch(pet
->getPetType())
16133 m_guardianPets
.erase(pet
->GetGUID());
16136 if(GetPetGUID() == pet
->GetGUID())
16145 switch(pet
->GetEntry())
16147 //warlock pets except imp are removed(?) when logging out
16152 mode
= PET_SAVE_NOT_IN_SLOT
;
16157 pet
->SavePetToDB(mode
);
16159 pet
->CleanupsBeforeDelete();
16160 pet
->AddObjectToRemoveList();
16161 pet
->m_removed
= true;
16163 if(pet
->isControlled())
16165 WorldPacket
data(SMSG_PET_SPELLS
, 8+4);
16168 GetSession()->SendPacket(&data
);
16171 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16175 void Player::RemoveMiniPet()
16177 if(Pet
* pet
= GetMiniPet())
16179 pet
->Remove(PET_SAVE_AS_DELETED
);
16184 Pet
* Player::GetMiniPet()
16188 return ObjectAccessor::GetPet(m_miniPet
);
16191 void Player::RemoveGuardians()
16193 while(!m_guardianPets
.empty())
16195 uint64 guid
= *m_guardianPets
.begin();
16196 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16197 pet
->Remove(PET_SAVE_AS_DELETED
);
16199 m_guardianPets
.erase(guid
);
16203 bool Player::HasGuardianWithEntry(uint32 entry
)
16205 // pet guid middle part is entry (and creature also)
16206 // and in guardian list must be guardians with same entry _always_
16207 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16208 if(GUID_ENPART(*itr
)==entry
)
16214 void Player::Uncharm()
16216 Unit
* charm
= GetCharm();
16220 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16221 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16224 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16226 *data
<< (uint8
)msgtype
;
16227 *data
<< (uint32
)language
;
16228 *data
<< (uint64
)GetGUID();
16229 *data
<< (uint32
)language
; //language 2.1.0 ?
16230 *data
<< (uint64
)GetGUID();
16231 *data
<< (uint32
)(text
.length()+1);
16233 *data
<< (uint8
)chatTag();
16236 void Player::Say(const std::string
& text
, const uint32 language
)
16238 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16239 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16240 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16243 void Player::Yell(const std::string
& text
, const uint32 language
)
16245 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16246 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16247 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16250 void Player::TextEmote(const std::string
& text
)
16252 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16253 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16254 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16257 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16259 if (language
!= LANG_ADDON
) // if not addon data
16260 language
= LANG_UNIVERSAL
; // whispers should always be readable
16262 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16264 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16265 if(!rPlayer
->isDND() || isGameMaster())
16267 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16268 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16269 rPlayer
->GetSession()->SendPacket(&data
);
16271 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16272 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16273 GetSession()->SendPacket(&data
);
16277 // announce to player that player he is whispering to is dnd and cannot receive his message
16278 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16281 if(!isAcceptWhispers())
16283 SetAcceptWhispers(true);
16284 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16287 // announce to player that player he is whispering to is afk
16288 if(rPlayer
->isAFK())
16289 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16291 // if player whisper someone, auto turn of dnd to be able to receive an answer
16292 if(isDND() && !rPlayer
->isGameMaster())
16296 void Player::PetSpellInitialize()
16298 Pet
* pet
= GetPet();
16303 sLog
.outDebug("Pet Spells Groups");
16305 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16307 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16308 data
<< uint64(pet
->GetGUID());
16309 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16311 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16314 for(uint32 i
= 0; i
< 10; i
++)
16316 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16319 size_t spellsCountPos
= data
.wpos();
16323 data
<< uint8(addlist
); // placeholder
16325 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16328 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16330 if(itr
->second
->state
== PETSPELL_REMOVED
)
16333 data
<< uint16(itr
->first
);
16334 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16339 data
.put
<uint8
>(spellsCountPos
, addlist
);
16341 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16342 data
<< uint8(cooldownsCount
);
16344 time_t curTime
= time(NULL
);
16346 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16348 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16350 data
<< uint16(itr
->first
); // spellid
16351 data
<< uint16(0); // spell category?
16352 data
<< uint32(cooldown
); // cooldown
16353 data
<< uint32(0); // category cooldown
16356 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.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(0); // cooldown
16363 data
<< uint32(cooldown
); // category cooldown
16366 GetSession()->SendPacket(&data
);
16369 void Player::PossessSpellInitialize()
16371 Unit
* charm
= GetCharm();
16376 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16380 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16385 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16388 data
<< uint64(charm
->GetGUID());
16389 data
<< uint32(0x00000000);
16393 for(uint32 i
= 0; i
< 10; i
++) //40
16395 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16398 data
<< uint8(addlist
); //1
16401 data
<< uint8(count
); // cooldowns count
16403 GetSession()->SendPacket(&data
);
16406 void Player::CharmSpellInitialize()
16408 Unit
* charm
= GetCharm();
16413 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16416 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16422 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16424 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16426 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16428 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16430 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16436 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16438 data
<< uint64(charm
->GetGUID());
16439 data
<< uint32(0x00000000);
16441 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16442 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16444 data
<< uint8(0) << uint8(0);
16447 for(uint32 i
= 0; i
< 10; i
++) //40
16449 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16452 data
<< uint8(addlist
); //1
16456 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16458 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16459 if(cspell
->spellId
)
16461 data
<< uint16(cspell
->spellId
);
16462 data
<< uint16(cspell
->active
);
16468 data
<< uint8(count
); // cooldowns count
16470 GetSession()->SendPacket(&data
);
16473 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16475 if (!mod
|| !spellInfo
)
16478 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16480 // prevent apply to any spell except spell that trigger expire
16483 if(mod
->lastAffected
!= spell
)
16486 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16490 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16493 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16495 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16497 for(int eff
=0;eff
<96;++eff
)
16501 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16502 else _mask2
= uint64(1) << (eff
-64);
16503 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16506 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16508 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16509 val
+= (*itr
)->value
;
16511 val
+= apply
? mod
->value
: -(mod
->value
);
16512 WorldPacket
data(Opcode
, (1+1+4));
16513 data
<< uint8(eff
);
16514 data
<< uint8(mod
->op
);
16515 data
<< int32(val
);
16516 SendDirectMessage(&data
);
16521 m_spellMods
[mod
->op
].push_back(mod
);
16524 if (mod
->charges
== -1)
16525 --m_SpellModRemoveCount
;
16526 m_spellMods
[mod
->op
].remove(mod
);
16531 void Player::RemoveSpellMods(Spell
const* spell
)
16533 if(!spell
|| (m_SpellModRemoveCount
== 0))
16536 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16538 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16540 SpellModifier
*mod
= *itr
;
16543 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16545 RemoveAurasDueToSpell(mod
->spellId
);
16546 if (m_spellMods
[i
].empty())
16549 itr
= m_spellMods
[i
].begin();
16555 // send Proficiency
16556 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16558 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16559 data
<< pr1
<< pr2
;
16560 GetSession()->SendPacket (&data
);
16563 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16565 QueryResult
*result
= NULL
;
16567 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16569 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16572 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.
16573 { // and SendPetitionQueryOpcode reads data from the DB
16574 Field
*fields
= result
->Fetch();
16575 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16576 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16578 // send update if charter owner in game
16579 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16581 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16583 } while ( result
->NextRow() );
16588 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16590 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16593 CharacterDatabase
.BeginTransaction();
16596 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16597 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16601 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16602 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16604 CharacterDatabase
.CommitTransaction();
16607 void Player::LeaveAllArenaTeams(uint64 guid
)
16609 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
));
16615 Field
*fields
= result
->Fetch();
16616 uint32 at_id
= fields
[0].GetUInt32();
16619 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16621 at
->DelMember(guid
);
16623 } while (result
->NextRow());
16628 void Player::SetRestBonus (float rest_bonus_new
)
16630 // Prevent resting on max level
16631 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16632 rest_bonus_new
= 0;
16634 if(rest_bonus_new
< 0)
16635 rest_bonus_new
= 0;
16637 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16639 if(rest_bonus_new
> rest_bonus_max
)
16640 m_rest_bonus
= rest_bonus_max
;
16642 m_rest_bonus
= rest_bonus_new
;
16644 // update data for client
16645 if(m_rest_bonus
>10)
16646 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16647 else if(m_rest_bonus
<=1)
16648 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16651 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16654 void Player::HandleStealthedUnitsDetection()
16656 std::list
<Unit
*> stealthedUnits
;
16658 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16660 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16661 cell
.SetNoCreate();
16663 MaNGOS::AnyStealthedCheck u_check
;
16664 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16666 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16667 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16669 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16670 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16671 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16673 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16677 i
= stealthedUnits
.erase(i
);
16681 if ((*i
)->isVisibleForOrDetect(this,true))
16684 (*i
)->SendUpdateToPlayer(this);
16685 m_clientGUIDs
.insert((*i
)->GetGUID());
16687 #ifdef MANGOS_DEBUG
16688 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16689 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16692 // target aura duration for caster show only if target exist at caster client
16693 // send data at target visibility change (adding to client)
16694 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16695 SendAurasForTarget(*i
);
16697 i
= stealthedUnits
.erase(i
);
16705 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16707 if(nodes
.size() < 2)
16710 // not let cheating with start flight mounted
16713 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16714 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16715 GetSession()->SendPacket(&data
);
16719 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16721 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16722 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16723 GetSession()->SendPacket(&data
);
16727 // 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
16728 if(GetSession()->isLogingOut() ||
16729 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16730 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16731 IsNonMeleeSpellCasted(false) ||
16734 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16735 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16736 GetSession()->SendPacket(&data
);
16740 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16743 uint32 sourcenode
= nodes
[0];
16745 // starting node too far away (cheat?)
16746 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16747 if( !node
|| node
->map_id
!= GetMapId() ||
16748 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16749 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16750 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16751 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16753 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16754 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16755 GetSession()->SendPacket(&data
);
16759 // Prepare to flight start now
16761 // stop combat at start taxi flight if any
16764 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16767 // clean not finished taxi path if any
16768 m_taxi
.ClearTaxiDestinations();
16770 // 0 element current node
16771 m_taxi
.AddTaxiDestination(sourcenode
);
16773 // fill destinations path tail
16774 uint32 sourcepath
= 0;
16775 uint32 totalcost
= 0;
16777 uint32 prevnode
= sourcenode
;
16778 uint32 lastnode
= 0;
16780 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16784 lastnode
= nodes
[i
];
16785 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16789 m_taxi
.ClearTaxiDestinations();
16795 if(prevnode
== sourcenode
)
16798 m_taxi
.AddTaxiDestination(lastnode
);
16800 prevnode
= lastnode
;
16803 if(!mount_id
) // if not provide then attempt use default.
16804 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16806 if (mount_id
== 0 || sourcepath
== 0)
16808 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16809 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16810 GetSession()->SendPacket(&data
);
16811 m_taxi
.ClearTaxiDestinations();
16815 uint32 money
= GetMoney();
16819 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16822 if(money
< totalcost
)
16824 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16825 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16826 GetSession()->SendPacket(&data
);
16827 m_taxi
.ClearTaxiDestinations();
16831 //Checks and preparations done, DO FLIGHT
16832 ModifyMoney(-(int32
)totalcost
);
16833 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
16835 // prevent stealth flight
16836 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16838 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16839 data
<< uint32(ERR_TAXIOK
);
16840 GetSession()->SendPacket(&data
);
16842 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16844 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16849 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16851 // last check 2.0.10
16852 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16854 data
<< uint8(0x0); // flags (0x1, 0x2)
16855 time_t curTime
= time(NULL
);
16856 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16858 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16860 uint32 unSpellId
= itr
->first
;
16861 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16868 // Not send cooldown for this spells
16869 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16872 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16875 data
<< unTimeMs
; // in m.secs
16876 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
16879 GetSession()->SendPacket(&data
);
16882 void Player::InitDataForForm(bool reapplyMods
)
16884 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16885 if(ssEntry
&& ssEntry
->attackSpeed
)
16887 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16888 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16889 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16892 SetRegularAttackTime();
16898 if(getPowerType()!=POWER_ENERGY
)
16899 setPowerType(POWER_ENERGY
);
16903 case FORM_DIREBEAR
:
16905 if(getPowerType()!=POWER_RAGE
)
16906 setPowerType(POWER_RAGE
);
16909 default: // 0, for example
16911 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16912 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16913 setPowerType(Powers(cEntry
->powerType
));
16918 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16920 UpdateEquipSpellsAtFormChange();
16922 UpdateAttackPowerAndDamage();
16923 UpdateAttackPowerAndDamage(true);
16926 // Return true is the bought item has a max count to force refresh of window by caller
16927 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16929 // cheating attempt
16930 if(count
< 1) count
= 1;
16935 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16938 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16942 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16945 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16946 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16950 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16951 if(!vItems
|| vItems
->Empty())
16953 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16957 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16958 if(vendor_slot
>= vItems
->GetItemCount())
16960 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16964 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16966 // check current item amount if it limited
16967 if( crItem
->maxcount
!= 0 )
16969 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16971 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16976 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16978 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16982 if(crItem
->ExtendedCost
)
16984 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16987 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16991 // honor points price
16992 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16994 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16998 // arena points price
16999 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17001 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17006 for (uint8 i
= 0; i
< 5; ++i
)
17008 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17010 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17015 // check for personal arena rating requirement
17016 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17018 // probably not the proper equip err
17019 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17024 uint32 price
= pProto
->BuyPrice
* count
;
17026 // reputation discount
17027 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17029 if( GetMoney() < price
)
17031 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17035 uint8 bag
= 0; // init for case invalid bagGUID
17037 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17040 if( bagguid
== GetGUID() )
17042 bag
= INVENTORY_SLOT_BAG_0
;
17046 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17048 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17051 if( bagguid
== pBag
->GetGUID() )
17061 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17063 ItemPosCountVec dest
;
17064 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17065 if( msg
!= EQUIP_ERR_OK
)
17067 SendEquipError( msg
, NULL
, NULL
);
17071 ModifyMoney( -(int32
)price
);
17072 if(crItem
->ExtendedCost
) // case for new honor system
17074 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17075 if(iece
->reqhonorpoints
)
17076 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17077 if(iece
->reqarenapoints
)
17078 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17079 for (uint8 i
= 0; i
< 5; ++i
)
17081 if(iece
->reqitem
[i
])
17082 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17086 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17088 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17090 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17091 data
<< pCreature
->GetGUID();
17092 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17093 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17094 data
<< (uint32
)count
;
17095 GetSession()->SendPacket(&data
);
17097 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17100 else if( IsEquipmentPos( bag
, slot
) )
17102 if(pProto
->BuyCount
* count
!= 1)
17104 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17109 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17110 if( msg
!= EQUIP_ERR_OK
)
17112 SendEquipError( msg
, NULL
, NULL
);
17116 ModifyMoney( -(int32
)price
);
17117 if(crItem
->ExtendedCost
) // case for new honor system
17119 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17120 if(iece
->reqhonorpoints
)
17121 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17122 if(iece
->reqarenapoints
)
17123 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17124 for (uint8 i
= 0; i
< 5; ++i
)
17126 if(iece
->reqitem
[i
])
17127 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17131 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17133 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17135 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17136 data
<< pCreature
->GetGUID();
17137 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17138 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17139 data
<< (uint32
)count
;
17140 GetSession()->SendPacket(&data
);
17142 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17144 AutoUnequipOffhandIfNeed();
17149 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17153 return crItem
->maxcount
!=0;
17156 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17158 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17159 // the personal rating of the arena team must match the required limit as well
17160 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17161 uint32 max_personal_rating
= 0;
17162 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17164 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17166 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17167 uint32 t_rating
= at
->GetRating();
17168 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17169 if(max_personal_rating
< p_rating
)
17170 max_personal_rating
= p_rating
;
17173 return max_personal_rating
;
17176 void Player::UpdateHomebindTime(uint32 time
)
17178 // GMs never get homebind timer online
17179 if (m_InstanceValid
|| isGameMaster())
17181 if(m_HomebindTimer
) // instance valid, but timer not reset
17184 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17187 GetSession()->SendPacket(&data
);
17189 // instance is valid, reset homebind timer
17190 m_HomebindTimer
= 0;
17192 else if (m_HomebindTimer
> 0)
17194 if (time
>= m_HomebindTimer
)
17196 // teleport to homebind location
17197 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17200 m_HomebindTimer
-= time
;
17204 // instance is invalid, start homebind timer
17205 m_HomebindTimer
= 60000;
17206 // send message to player
17207 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17208 data
<< m_HomebindTimer
;
17210 GetSession()->SendPacket(&data
);
17211 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17215 void Player::UpdatePvP(bool state
, bool ovrride
)
17217 if(!state
|| ovrride
)
17220 if(Pet
* pet
= GetPet())
17221 pet
->SetPvP(state
);
17222 if(Unit
* charmed
= GetCharm())
17223 charmed
->SetPvP(state
);
17225 pvpInfo
.endTimer
= 0;
17229 if(pvpInfo
.endTimer
!= 0)
17230 pvpInfo
.endTimer
= time(NULL
);
17235 if(Pet
* pet
= GetPet())
17236 pet
->SetPvP(state
);
17237 if(Unit
* charmed
= GetCharm())
17238 charmed
->SetPvP(state
);
17243 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17245 // init cooldown values
17250 // some special item spells without correct cooldown in SpellInfo
17251 // cooldown information stored in item prototype
17252 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17256 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17258 for(int idx
= 0; idx
< 5; ++idx
)
17260 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17262 cat
= proto
->Spells
[idx
].SpellCategory
;
17263 rec
= proto
->Spells
[idx
].SpellCooldown
;
17264 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17271 // if no cooldown found above then base at DBC data
17272 if(rec
< 0 && catrec
< 0)
17274 cat
= spellInfo
->Category
;
17275 rec
= spellInfo
->RecoveryTime
;
17276 catrec
= spellInfo
->CategoryRecoveryTime
;
17279 time_t curTime
= time(NULL
);
17284 // overwrite time for selected category
17285 if(infinityCooldown
)
17287 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17288 // but not allow ignore until reset or re-login
17289 catrecTime
= catrec
> 0 ? curTime
+MONTH
: 0;
17290 recTime
= rec
> 0 ? curTime
+MONTH
: catrecTime
;
17294 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17295 // prevent 0 cooldowns set by another way
17296 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17297 rec
= GetAttackTime(RANGED_ATTACK
);
17299 // Now we have cooldown data (if found any), time to apply mods
17301 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17304 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17306 // replace negative cooldowns by 0
17307 if (rec
< 0) rec
= 0;
17308 if (catrec
< 0) catrec
= 0;
17310 // no cooldown after applying spell mods
17311 if( rec
== 0 && catrec
== 0)
17314 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17315 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17318 // self spell cooldown
17320 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17323 if (cat
&& catrec
> 0)
17325 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17326 if(i_scstore
!= sSpellCategoryStore
.end())
17328 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17330 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17333 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17339 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17343 sc
.itemid
= itemid
;
17344 m_spellCooldowns
[spellid
] = sc
;
17347 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17349 // start cooldowns at server side, if any
17350 AddSpellAndCategoryCooldowns(spellInfo
,itemId
,spell
);
17352 // Send activate cooldown timer (possible 0) at client side
17353 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17354 data
<< spellInfo
->Id
;
17356 SendDirectMessage(&data
);
17359 void Player::UpdatePotionCooldown(Spell
* spell
)
17361 // no potion used i combat or still in combat
17362 if(!m_lastPotionId
|| isInCombat())
17365 // Call not from spell cast, send cooldown event for item spells if no in combat
17368 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17369 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17370 for(int idx
= 0; idx
< 5; ++idx
)
17371 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17372 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17373 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17375 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17377 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17379 m_lastPotionId
= 0;
17382 //slot to be excluded while counting
17383 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17385 if(!enchantmentcondition
)
17388 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17393 uint8 curcount
[4] = {0, 0, 0, 0};
17395 //counting current equipped gem colors
17396 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17400 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17401 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17403 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17405 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17409 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17413 uint32 gemid
= enchantEntry
->GemID
;
17417 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17421 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17425 uint8 GemColor
= gemProperty
->color
;
17427 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17429 if(tmpcolormask
& GemColor
)
17436 bool activate
= true;
17438 for(int i
= 0; i
< 5; i
++)
17440 if(!Condition
->Color
[i
])
17443 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17445 // if have <CompareColor> use them as count, else use <value> from Condition
17446 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17448 switch(Condition
->Comparator
[i
])
17450 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17451 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17453 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17454 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17456 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17457 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17462 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");
17467 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17469 //cycle all equipped items
17470 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17472 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17473 if(slot
== exceptslot
)
17476 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17478 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17481 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17483 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17487 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17491 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17494 //was enchant active with/without item?
17495 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17496 //should it now be?
17497 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17499 // ignore item gem conditions
17500 //if state changed, (dis)apply enchant
17501 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17508 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17509 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17511 //cycle all equipped items
17512 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17514 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17515 if(slot
== exceptslot
)
17518 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17520 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17523 //cycle all (gem)enchants
17524 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17526 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17527 if(!enchant_id
) //if no enchant go to next enchant(slot)
17530 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17534 //only metagems to be (de)activated, so only enchants with condition
17535 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17537 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17542 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17544 if(BattleGround
*bg
= GetBattleGround())
17546 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17548 // call after remove to be sure that player resurrected for correct cast
17549 if( bg
->isBattleGround() && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
) )
17551 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
17552 CastSpell(this, 26013, true); // Deserter
17557 bool Player::CanJoinToBattleground() const
17559 // check Deserter debuff
17560 if(GetDummyAura(26013))
17566 bool Player::CanReportAfkDueToLimit()
17568 // a player can complain about 15 people per 5 minutes
17569 if(m_bgAfkReportedCount
>= 15)
17571 ++m_bgAfkReportedCount
;
17575 ///This player has been blamed to be inactive in a battleground
17576 void Player::ReportedAfkBy(Player
* reporter
)
17578 BattleGround
*bg
= GetBattleGround();
17579 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17582 // check if player has 'Idle' or 'Inactive' debuff
17583 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17585 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17586 // 3 players have to complain to apply debuff
17587 if(m_bgAfkReporter
.size() >= 3)
17589 // cast 'Idle' spell
17590 CastSpell(this, 43680, true);
17591 m_bgAfkReporter
.clear();
17596 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17598 // gamemaster in GM mode see all, including ghosts
17599 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17602 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17603 if (InBattleGround())
17605 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17610 // Live player see live player or dead player with not realized corpse
17611 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17613 return isAlive() || m_deathTimer
> 0;
17616 // Ghost see other friendly ghosts, that's for sure
17617 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17620 // Dead player see live players near own corpse
17623 Corpse
*corpse
= pl
->GetCorpse();
17626 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17627 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17632 // and not see any other
17636 bool Player::IsVisibleGloballyFor( Player
* u
) const
17641 // Always can see self
17645 // Visible units, always are visible for all players
17646 if (GetVisibility() == VISIBILITY_ON
)
17649 // GMs are visible for higher gms (or players are visible for gms)
17650 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17651 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17653 // non faction visibility non-breakable for non-GMs
17654 if (GetVisibility() == VISIBILITY_OFF
)
17657 // non-gm stealth/invisibility not hide from global player lists
17661 void Player::UpdateVisibilityOf(WorldObject
* target
)
17663 if(HaveAtClient(target
))
17665 if(!target
->isVisibleForInState(this,true))
17667 target
->DestroyForPlayer(this);
17668 m_clientGUIDs
.erase(target
->GetGUID());
17670 #ifdef MANGOS_DEBUG
17671 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17672 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17678 if(target
->isVisibleForInState(this,false))
17680 target
->SendUpdateToPlayer(this);
17681 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17682 m_clientGUIDs
.insert(target
->GetGUID());
17684 #ifdef MANGOS_DEBUG
17685 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17686 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17689 // target aura duration for caster show only if target exist at caster client
17690 // send data at target visibility change (adding to client)
17691 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17692 SendAurasForTarget((Unit
*)target
);
17694 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17695 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17701 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17703 s64
.insert(target
->GetGUID());
17707 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17709 if(!target
->IsTransport())
17710 s64
.insert(target
->GetGUID());
17714 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17716 if(HaveAtClient(target
))
17718 if(!target
->isVisibleForInState(this,true))
17720 target
->BuildOutOfRangeUpdateBlock(&data
);
17721 m_clientGUIDs
.erase(target
->GetGUID());
17723 #ifdef MANGOS_DEBUG
17724 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17725 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
));
17731 if(target
->isVisibleForInState(this,false))
17733 visibleNow
.insert(target
);
17734 target
->BuildUpdate(data_updates
);
17735 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17736 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17738 #ifdef MANGOS_DEBUG
17739 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17740 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
));
17746 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17747 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17748 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17749 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17750 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17752 void Player::InitPrimaryProffesions()
17754 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17757 void Player::SendComboPoints()
17759 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17762 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17763 data
.append(combotarget
->GetPackGUID());
17764 data
<< uint8(m_comboPoints
);
17765 GetSession()->SendPacket(&data
);
17769 void Player::AddComboPoints(Unit
* target
, int8 count
)
17774 // without combo points lost (duration checked in aura)
17775 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17777 if(target
->GetGUID() == m_comboTarget
)
17779 m_comboPoints
+= count
;
17784 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17785 target2
->RemoveComboPointHolder(GetGUIDLow());
17787 m_comboTarget
= target
->GetGUID();
17788 m_comboPoints
= count
;
17790 target
->AddComboPointHolder(GetGUIDLow());
17793 if (m_comboPoints
> 5) m_comboPoints
= 5;
17794 if (m_comboPoints
< 0) m_comboPoints
= 0;
17799 void Player::ClearComboPoints()
17804 // without combopoints lost (duration checked in aura)
17805 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17811 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17812 target
->RemoveComboPointHolder(GetGUIDLow());
17817 void Player::SetGroup(Group
*group
, int8 subgroup
)
17823 // never use SetGroup without a subgroup unless you specify NULL for group
17824 assert(subgroup
>= 0);
17825 m_group
.link(group
, this);
17826 m_group
.setSubGroup((uint8
)subgroup
);
17830 void Player::SendInitialPacketsBeforeAddToMap()
17832 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17833 data
<< uint32(0); // unknown, may be rest state time or experience
17834 GetSession()->SendPacket(&data
);
17837 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17838 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17839 data
<< (uint32
) m_homebindMapId
;
17840 data
<< (uint32
) m_homebindZoneId
;
17841 GetSession()->SendPacket(&data
);
17843 // SMSG_SET_PROFICIENCY
17844 // SMSG_UPDATE_AURA_DURATION
17847 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17848 for (int i
= 0; i
< 8; ++i
)
17849 data
<< uint32( GetTutorialInt(i
) );
17850 GetSession()->SendPacket(&data
);
17852 SendInitialSpells();
17854 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17855 data
<< uint32(0); // count, for(count) uint32;
17856 GetSession()->SendPacket(&data
);
17858 SendInitialActionButtons();
17859 m_reputationMgr
.SendInitialReputations();
17860 m_achievementMgr
.SendAllAchievementData();
17863 uint32 newzone
, newarea
;
17864 GetZoneAndAreaId(newzone
,newarea
);
17865 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
17867 // SMSG_SET_AURA_SINGLE
17869 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17870 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17871 data
<< (float)0.01666667f
; // game speed
17872 GetSession()->SendPacket( &data
);
17874 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17875 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17876 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17881 void Player::SendInitialPacketsAfterAddToMap()
17883 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17884 data
<< uint32(0x00000000); // on blizz it increments periodically
17885 GetSession()->SendPacket(&data
);
17887 CastSpell(this, 836, true); // LOGINEFFECT
17889 // set some aura effects that send packet to player client after add player to map
17890 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17891 // same auras state lost at far teleport, send it one more time in this case also
17892 static const AuraType auratypes
[] =
17894 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17895 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17896 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17898 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17900 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17901 if(!auraList
.empty())
17902 auraList
.front()->ApplyModifier(true,true);
17905 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17906 SetMovement(MOVE_ROOT
);
17908 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17909 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17911 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
17912 data2
.append(GetPackGUID());
17913 data2
<< (uint32
)2;
17914 SendMessageToSet(&data2
,true);
17917 SendAurasForTarget(this);
17918 SendEnchantmentDurations(); // must be after add to map
17919 SendItemDurations(); // must be after add to map
17922 void Player::SendUpdateToOutOfRangeGroupMembers()
17924 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17926 if(Group
* group
= GetGroup())
17927 group
->UpdatePlayerOutOfRange(this);
17929 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17930 m_auraUpdateMask
= 0;
17931 if(Pet
*pet
= GetPet())
17932 pet
->ResetAuraUpdateMask();
17935 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
17937 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17938 data
<< uint32(mapid
);
17939 data
<< uint8(reason
); // transfer abort reason
17942 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
17943 case TRANSFER_ABORT_DIFFICULTY
:
17944 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
17945 data
<< uint8(arg
);
17948 GetSession()->SendPacket(&data
);
17951 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17953 // type of warning, based on the time remaining until reset
17956 type
= RAID_INSTANCE_WELCOME
;
17957 else if(time
> 900 && time
<= 3600)
17958 type
= RAID_INSTANCE_WARNING_HOURS
;
17959 else if(time
> 300 && time
<= 900)
17960 type
= RAID_INSTANCE_WARNING_MIN
;
17962 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17963 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17964 data
<< uint32(type
);
17965 data
<< uint32(mapid
);
17966 data
<< uint32(time
);
17967 GetSession()->SendPacket(&data
);
17970 void Player::ApplyEquipCooldown( Item
* pItem
)
17972 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
17974 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17977 if( !spellData
.SpellId
)
17980 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17981 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17984 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17986 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17987 data
<< pItem
->GetGUID();
17988 data
<< uint32(spellData
.SpellId
);
17989 GetSession()->SendPacket(&data
);
17993 void Player::resetSpells()
17995 // not need after this call
17996 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17998 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17999 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18002 // make full copy of map (spells removed and marked as deleted at another spell remove
18003 // and we can't use original map for safe iterative with visit each spell at loop end
18004 PlayerSpellMap smap
= GetSpellMap();
18006 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18007 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18009 learnDefaultSpells();
18010 learnQuestRewardedSpells();
18013 void Player::learnDefaultSpells()
18015 // learn default race/class spells
18016 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18017 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18019 uint32 tspell
= *itr
;
18020 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18021 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18022 addSpell(tspell
,true,true,true,false);
18023 else // but send in normal spell in game learn case
18024 learnSpell(tspell
,true);
18028 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18030 uint32 spell_id
= quest
->GetRewSpellCast();
18032 // skip quests without rewarded spell
18036 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18040 // check learned spells state
18041 bool found
= false;
18042 for(int i
=0; i
< 3; ++i
)
18044 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18051 // skip quests with not teaching spell or already known spell
18055 // prevent learn non first rank unknown profession and second specialization for same profession)
18056 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18057 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18059 // not have first rank learned (unlearned prof?)
18060 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18061 if( !HasSpell(first_spell
) )
18064 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18069 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18071 // search other specialization for same prof
18072 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18074 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18077 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18081 // compare only specializations
18082 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18085 // compare same chain spells
18086 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18089 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18090 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18096 CastSpell( this, spell_id
, true);
18099 void Player::learnQuestRewardedSpells()
18101 // learn spells received from quest completing
18102 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18104 // skip no rewarded quests
18105 if(!itr
->second
.m_rewarded
)
18108 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18112 learnQuestRewardedSpells(quest
);
18116 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18118 uint32 raceMask
= getRaceMask();
18119 uint32 classMask
= getClassMask();
18120 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18122 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18123 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18125 // Check race if set
18126 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18128 // Check class if set
18129 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18132 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18134 // need unlearn spell
18135 if (skill_value
< pAbility
->req_skill_value
)
18136 removeSpell(pAbility
->spellId
);
18138 else if (!IsInWorld())
18139 addSpell(pAbility
->spellId
,true,true,true,false);
18141 learnSpell(pAbility
->spellId
,true);
18146 void Player::SendAurasForTarget(Unit
*target
)
18148 if(target
->GetVisibleAuras()->empty()) // speedup things
18151 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18152 data
.append(target
->GetPackGUID());
18154 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18155 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18157 for(uint32 j
= 0; j
< 3; ++j
)
18159 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18161 data
<< uint8(aura
->GetAuraSlot());
18162 data
<< uint32(aura
->GetId());
18166 uint8 auraFlags
= aura
->GetAuraFlags();
18168 data
<< uint8(auraFlags
);
18170 data
<< uint8(aura
->GetAuraLevel());
18172 data
<< uint8(aura
->GetAuraCharges());
18174 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18176 data
<< uint8(0); // packed GUID of someone (caster?)
18179 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18181 data
<< uint32(aura
->GetAuraMaxDuration());
18182 data
<< uint32(aura
->GetAuraDuration());
18190 GetSession()->SendPacket(&data
);
18193 void Player::SetDailyQuestStatus( uint32 quest_id
)
18195 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18197 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18199 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18200 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18201 m_DailyQuestChanged
= true;
18207 void Player::ResetDailyQuestStatus()
18209 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18210 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18212 // DB data deleted in caller
18213 m_DailyQuestChanged
= false;
18214 m_lastDailyQuestTime
= 0;
18217 BattleGround
* Player::GetBattleGround() const
18219 if(GetBattleGroundId()==0)
18222 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgTypeID
);
18225 bool Player::InArena() const
18227 BattleGround
*bg
= GetBattleGround();
18228 if(!bg
|| !bg
->isArena())
18234 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18236 // get a template bg instead of running one
18237 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18241 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18247 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18249 //returned to hardcoded version of this function, because there is no way to code it dynamic
18250 uint32 level
= getLevel();
18251 if( bgTypeId
== BATTLEGROUND_AV
)
18254 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18255 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18257 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18258 return QUEUE_ID_MAX_LEVEL_80
;
18260 return BGQueueIdBasedOnLevel(queue_id
);
18263 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18265 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18266 if(!vendor_faction
|| !vendor_faction
->faction
)
18269 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18270 if(rank
<= REP_NEUTRAL
)
18273 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18276 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18278 uint32 racemask
= getRaceMask();
18279 uint32 classmask
= getClassMask();
18281 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18282 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18286 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18288 // skip wrong race skills
18289 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18292 // skip wrong class skills
18293 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18302 bool Player::HasQuestForGO(int32 GOId
) const
18304 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18306 uint32 questid
= GetQuestSlotQuestId(i
);
18307 if ( questid
== 0 )
18310 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18311 if(qs_itr
== mQuestStatus
.end())
18314 QuestStatusData
const& qs
= qs_itr
->second
;
18316 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18318 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18322 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18325 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18327 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18330 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18338 void Player::UpdateForQuestsGO()
18340 if(m_clientGUIDs
.empty())
18344 WorldPacket packet
;
18345 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18347 if(IS_GAMEOBJECT_GUID(*itr
))
18349 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18351 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18354 udata
.BuildPacket(&packet
);
18355 GetSession()->SendPacket(&packet
);
18358 void Player::SummonIfPossible(bool agree
)
18362 m_summon_expire
= 0;
18366 // expire and auto declined
18367 if(m_summon_expire
< time(NULL
))
18370 // stop taxi flight at summon
18373 GetMotionMaster()->MovementExpired();
18374 m_taxi
.ClearTaxiDestinations();
18377 // drop flag at summon
18378 // 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
18379 if(BattleGround
*bg
= GetBattleGround())
18380 bg
->EventPlayerDroppedFlag(this);
18382 m_summon_expire
= 0;
18384 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18387 void Player::RemoveItemDurations( Item
*item
)
18389 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18393 m_itemDuration
.erase(itr
);
18399 void Player::AddItemDurations( Item
*item
)
18401 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18403 m_itemDuration
.push_back(item
);
18404 item
->SendTimeUpdate(this);
18408 void Player::AutoUnequipOffhandIfNeed()
18410 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18414 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18415 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18418 ItemPosCountVec off_dest
;
18419 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18420 if( off_msg
== EQUIP_ERR_OK
)
18422 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18423 StoreItem( off_dest
, offItem
, true );
18428 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18429 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18430 CharacterDatabase
.BeginTransaction();
18431 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18432 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18433 CharacterDatabase
.CommitTransaction();
18435 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18436 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18440 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18442 if(spellInfo
->EquippedItemClass
< 0)
18445 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18446 // for optimize check 2 used cases only
18447 switch(spellInfo
->EquippedItemClass
)
18449 case ITEM_CLASS_WEAPON
:
18451 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18452 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18453 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18457 case ITEM_CLASS_ARMOR
:
18459 // tabard not have dependent spells
18460 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18461 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18462 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18465 // shields can be equipped to offhand slot
18466 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18467 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18470 // ranged slot can have some armor subclasses
18471 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18472 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18478 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18485 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18487 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18488 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18489 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18492 // Check no reagent use mask
18493 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18494 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18495 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18496 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18502 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18504 AuraMap
& auras
= GetAuras();
18505 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18507 Aura
* aura
= itr
->second
;
18509 // skip passive (passive item dependent spells work in another way) and not self applied auras
18510 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18511 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18517 // skip if not item dependent or have alternative item
18518 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18524 // no alt item, remove aura, restart check
18525 RemoveAurasDueToSpell(aura
->GetId());
18526 itr
= auras
.begin();
18529 // currently casted spells can be dependent from item
18530 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18532 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18533 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18538 uint32
Player::GetResurrectionSpellId()
18540 // search priceless resurrection possibilities
18542 uint32 spell_id
= 0;
18543 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18544 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18546 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18547 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18549 switch((*itr
)->GetId())
18551 case 20707: spell_id
= 3026; break; // rank 1
18552 case 20762: spell_id
= 20758; break; // rank 2
18553 case 20763: spell_id
= 20759; break; // rank 3
18554 case 20764: spell_id
= 20760; break; // rank 4
18555 case 20765: spell_id
= 20761; break; // rank 5
18556 case 27239: spell_id
= 27240; break; // rank 6
18557 case 47883: spell_id
= 47882; break; // rank 7
18559 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18565 // Twisting Nether // prio: 2 (max)
18566 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18573 // Reincarnation (passive spell) // prio: 1
18574 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18580 // Used in triggers for check "Only to targets that grant experience or honor" req
18581 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18583 uint32 v_level
= pVictim
->getLevel();
18584 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18586 // Victim level less gray level
18587 if(v_level
<=k_grey
)
18590 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18592 if (((Creature
*)pVictim
)->isTotem() ||
18593 ((Creature
*)pVictim
)->isPet() ||
18594 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18600 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18602 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18604 // prepare data for near group iteration (PvP and !PvP cases)
18606 bool honored_kill
= false;
18608 if(Group
*pGroup
= GetGroup())
18611 uint32 sum_level
= 0;
18612 Player
* member_with_max_level
= NULL
;
18613 Player
* not_gray_member_with_max_level
= NULL
;
18615 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18617 if(member_with_max_level
)
18619 /// not get Xp in PvP or no not gray players in group
18620 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18622 /// skip in check PvP case (for speed, not used)
18623 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18624 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18625 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18627 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18629 Player
* pGroupGuy
= itr
->getSource();
18633 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18634 continue; // member (alive or dead) or his corpse at req. distance
18636 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18637 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18638 honored_kill
= true;
18640 // xp and reputation only in !PvP case
18643 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18645 // if is in dungeon then all receive full reputation at kill
18646 // rewarded any alive/dead/near_corpse group member
18647 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18649 // XP updated only for alive group member
18650 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18651 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18653 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18655 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18656 if(Pet
* pet
= pGroupGuy
->GetPet())
18657 pet
->GivePetXP(itr_xp
/2);
18660 // quest objectives updated only for alive group member or dead but with not released body
18661 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18663 // normal creature (not pet/etc) can be only in !PvP case
18664 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18665 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18671 else // if (!pGroup)
18673 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18675 // honor can be in PvP and !PvP (racial leader) cases
18676 if(RewardHonor(pVictim
,1))
18677 honored_kill
= true;
18679 // xp and reputation only in !PvP case
18682 RewardReputation(pVictim
,1);
18683 GiveXP(xp
, pVictim
);
18685 if(Pet
* pet
= GetPet())
18686 pet
->GivePetXP(xp
);
18688 // normal creature (not pet/etc) can be only in !PvP case
18689 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18690 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18693 return xp
|| honored_kill
;
18696 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
18698 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
18700 // prepare data for near group iteration
18701 if(Group
*pGroup
= GetGroup())
18703 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18705 Player
* pGroupGuy
= itr
->getSource();
18709 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
18710 continue; // member (alive or dead) or his corpse at req. distance
18712 // quest objectives updated only for alive group member or dead but with not released body
18713 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18714 pGroupGuy
->KilledMonster(creature_id
, creature_guid
);
18717 else // if (!pGroup)
18718 KilledMonster(creature_id
, creature_guid
);
18721 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18723 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18729 Corpse
* corpse
= GetCorpse();
18733 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18736 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18738 Item
* item
= GetWeaponForAttack(attType
,true);
18740 // unarmed only with base attack
18741 if(attType
!= BASE_ATTACK
&& !item
)
18744 // weapon skill or (unarmed for base attack)
18745 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18746 return GetBaseSkillValue(skill
);
18749 void Player::ResurectUsingRequestData()
18751 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18752 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18754 ResurrectPlayer(0.0f
,false);
18756 if(GetMaxHealth() > m_resurrectHealth
)
18757 SetHealth( m_resurrectHealth
);
18759 SetHealth( GetMaxHealth() );
18761 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18762 SetPower(POWER_MANA
, m_resurrectMana
);
18764 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18766 SetPower(POWER_RAGE
, 0 );
18768 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18770 SpawnCorpseBones();
18773 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18775 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18776 data
.append(target
->GetPackGUID());
18777 data
<< uint8(allowMove
);
18778 GetSession()->SendPacket(&data
);
18781 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18783 // remove new continent flight forms
18784 if( !IsAllowUseFlyMountsHere() )
18786 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18787 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18790 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18791 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
18792 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18793 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
18794 if( !HasAura(itr
->second
->spellId
,0) )
18795 CastSpell(this,itr
->second
->spellId
,true);
18798 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18800 // remove auras from spells with area limitations
18801 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18803 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18804 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
18810 // some auras applied at subzone enter
18811 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
18812 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18813 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
18814 if( !HasAura(itr
->second
->spellId
,0) )
18815 CastSpell(this,itr
->second
->spellId
,true);
18818 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18820 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18821 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18823 return copseReclaimDelay
[0];
18826 time_t now
= time(NULL
);
18827 // 0..2 full period
18828 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18829 return copseReclaimDelay
[count
];
18832 void Player::UpdateCorpseReclaimDelay()
18834 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18836 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18837 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18840 time_t now
= time(NULL
);
18841 if(now
< m_deathExpireTime
)
18843 // full and partly periods 1..3
18844 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18845 if(count
< MAX_DEATH_COUNT
)
18846 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18848 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18851 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18854 void Player::SendCorpseReclaimDelay(bool load
)
18856 Corpse
* corpse
= GetCorpse();
18863 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18866 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18869 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18870 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18872 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18873 if(count
>=MAX_DEATH_COUNT
)
18874 count
= MAX_DEATH_COUNT
-1;
18879 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18881 time_t now
= time(NULL
);
18882 if(now
>= expected_time
)
18885 delay
= expected_time
-now
;
18888 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18890 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18891 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18892 data
<< uint32(delay
*IN_MILISECONDS
);
18893 GetSession()->SendPacket( &data
);
18896 Player
* Player::GetNextRandomRaidMember(float radius
)
18898 Group
*pGroup
= GetGroup();
18902 std::vector
<Player
*> nearMembers
;
18903 nearMembers
.reserve(pGroup
->GetMembersCount());
18905 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18907 Player
* Target
= itr
->getSource();
18909 // IsHostileTo check duel and controlled by enemy
18910 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18911 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18912 nearMembers
.push_back(Target
);
18915 if (nearMembers
.empty())
18918 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18919 return nearMembers
[randTarget
];
18922 PartyResult
Player::CanUninviteFromGroup() const
18924 const Group
* grp
= GetGroup();
18926 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
18928 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
18929 return PARTY_RESULT_YOU_NOT_LEADER
;
18931 if(InBattleGround())
18932 return PARTY_RESULT_INVITE_RESTRICTED
;
18934 return PARTY_RESULT_OK
;
18937 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
18939 //we must move references from m_group to m_originalGroup
18940 SetOriginalGroup(GetGroup(), GetSubGroup());
18943 m_group
.link(group
, this);
18944 m_group
.setSubGroup((uint8
)subgroup
);
18947 void Player::RemoveFromBattleGroundRaid()
18949 //remove existing reference
18951 if( Group
* group
= GetOriginalGroup() )
18953 m_group
.link(group
, this);
18954 m_group
.setSubGroup(GetOriginalSubGroup());
18956 SetOriginalGroup(NULL
);
18959 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
18961 if( group
== NULL
)
18962 m_originalGroup
.unlink();
18965 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18966 assert(subgroup
>= 0);
18967 m_originalGroup
.link(group
, this);
18968 m_originalGroup
.setSubGroup((uint8
)subgroup
);
18972 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18974 LiquidData liquid_status
;
18975 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
18978 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
18979 // Small hack for enable breath in WMO
18981 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
18985 // All liquids type - check under water position
18986 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
18988 if ( res
& LIQUID_MAP_UNDER_WATER
)
18989 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
18991 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
18994 // Allow travel in dark water on taxi or transport
18995 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
18996 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
18998 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
19000 // in lava check, anywhere in lava level
19001 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
19003 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19004 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
19006 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
19008 // in slime check, anywhere in slime level
19009 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
19011 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19012 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
19014 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
19018 void Player::SetCanParry( bool value
)
19020 if(m_canParry
==value
)
19023 m_canParry
= value
;
19024 UpdateParryPercentage();
19027 void Player::SetCanBlock( bool value
)
19029 if(m_canBlock
==value
)
19032 m_canBlock
= value
;
19033 UpdateBlockPercentage();
19036 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19038 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19039 if(itr
->pos
== pos
)
19045 bool Player::CanUseBattleGroundObject()
19047 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19048 // maybe gameobject code should handle that ForceReaction usage
19049 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19050 return ( //InBattleGround() && // in battleground - not need, check in other cases
19051 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19052 //player cannot use object when he is invulnerable (immune)
19053 !isTotalImmune() && // not totally immune
19054 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19055 !HasStealthAura() && // not stealthed
19056 !HasInvisibilityAura() && // not invisible
19057 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19058 isAlive() // live player
19062 bool Player::CanCaptureTowerPoint()
19064 return ( !HasStealthAura() && // not stealthed
19065 !HasInvisibilityAura() && // not invisible
19066 isAlive() // live player
19070 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19072 uint32 level
= getLevel();
19074 if(level
> GT_MAX_LEVEL
)
19075 level
= GT_MAX_LEVEL
; // max level in this dbc
19077 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19078 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19079 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19081 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19084 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19086 if(!bsc
) // shouldn't happen
19091 if(hairstyle
!= newhairstyle
)
19092 cost
+= bsc
->cost
; // full price
19094 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19095 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19097 if(facialhair
!= newfacialhair
)
19098 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19100 return uint32(cost
);
19103 void Player::InitGlyphsForLevel()
19105 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19106 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19108 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19110 uint32 level
= getLevel();
19113 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19115 value
|= (0x01 | 0x02);
19125 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19128 void Player::EnterVehicle(Vehicle
*vehicle
)
19130 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19134 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19138 vehicle
->SetCharmerGUID(GetGUID());
19139 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19140 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19141 vehicle
->setFaction(getFaction());
19143 SetCharm(vehicle
); // charm
19144 SetFarSightGUID(vehicle
->GetGUID()); // set view
19146 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19148 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19149 GetSession()->SendPacket(&data
);
19151 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19152 data
.append(GetPackGUID());
19153 data
<< uint32(0); // counter?
19154 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19155 data
<< uint16(0); // special flags
19156 data
<< uint32(getMSTime()); // time
19157 data
<< vehicle
->GetPositionX(); // x
19158 data
<< vehicle
->GetPositionY(); // y
19159 data
<< vehicle
->GetPositionZ(); // z
19160 data
<< vehicle
->GetOrientation(); // o
19161 // transport part, TODO: load/calculate seat offsets
19162 data
<< uint64(vehicle
->GetGUID()); // transport guid
19163 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19164 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19165 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19166 data
<< float(0); // transport orientation
19167 data
<< uint32(getMSTime()); // transport time
19168 data
<< uint8(0); // seat
19169 // end of transport part
19170 data
<< uint32(0); // fall time
19171 GetSession()->SendPacket(&data
);
19173 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19174 data
<< uint64(vehicle
->GetGUID());
19175 data
<< uint32(0x00000000);
19176 data
<< uint32(0x00000000);
19177 data
<< uint32(0x00000101);
19179 for(uint32 i
= 0; i
< 10; ++i
)
19180 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19184 GetSession()->SendPacket(&data
);
19187 void Player::ExitVehicle(Vehicle
*vehicle
)
19189 vehicle
->SetCharmerGUID(0);
19190 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19191 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19192 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19195 SetFarSightGUID(0);
19197 SetClientControl(vehicle
, 0);
19199 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19200 data
.append(GetPackGUID());
19201 data
<< uint32(0); // counter?
19202 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19203 data
<< uint16(0x40); // special flags
19204 data
<< uint32(getMSTime()); // time
19205 data
<< vehicle
->GetPositionX(); // x
19206 data
<< vehicle
->GetPositionY(); // y
19207 data
<< vehicle
->GetPositionZ(); // z
19208 data
<< vehicle
->GetOrientation(); // o
19209 data
<< uint32(0); // fall time
19210 GetSession()->SendPacket(&data
);
19212 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19215 GetSession()->SendPacket(&data
);
19217 // only for flyable vehicles?
19218 CastSpell(this, 45472, true); // Parachute
19221 bool Player::isTotalImmune()
19223 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
19225 uint32 immuneMask
= 0;
19226 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
19228 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
19229 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
19235 bool Player::HasTitle(uint32 bitIndex
)
19237 if (bitIndex
> 128)
19240 uint32 fieldIndexOffset
= bitIndex
/32;
19241 uint32 flag
= 1 << (bitIndex
%32);
19242 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19245 void Player::SetTitle(CharTitlesEntry
const* title
)
19247 uint32 fieldIndexOffset
= title
->bit_index
/32;
19248 uint32 flag
= 1 << (title
->bit_index
%32);
19249 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19252 void Player::ConvertRune(uint8 index
, uint8 newType
)
19254 SetCurrentRune(index
, newType
);
19256 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19257 data
<< uint8(index
);
19258 data
<< uint8(newType
);
19259 GetSession()->SendPacket(&data
);
19262 void Player::ResyncRunes(uint8 count
)
19264 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19265 for(uint32 i
= 0; i
< count
; ++i
)
19267 data
<< uint8(GetCurrentRune(i
)); // rune type
19268 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19270 GetSession()->SendPacket(&data
);
19273 void Player::AddRunePower(uint8 index
)
19275 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19276 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19277 GetSession()->SendPacket(&data
);
19280 void Player::InitRunes()
19282 if(getClass() != CLASS_DEATH_KNIGHT
)
19285 m_runes
= new Runes
;
19287 m_runes
->runeState
= 0;
19289 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19291 SetBaseRune(i
, i
/ 2); // init base types
19292 SetCurrentRune(i
, i
/ 2); // init current types
19293 SetRuneCooldown(i
, 0); // reset cooldowns
19294 m_runes
->SetRuneState(i
);
19297 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19298 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19301 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19304 loot
.FillLoot (loot_id
,store
,this,true);
19306 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19307 for(uint32 i
= 0; i
< max_slot
; ++i
)
19309 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19311 ItemPosCountVec dest
;
19312 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19313 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19314 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19315 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19316 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19317 if(msg
!= EQUIP_ERR_OK
)
19319 SendEquipError( msg
, NULL
, NULL
);
19323 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19324 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19328 uint32
Player::CalculateTalentsPoints() const
19330 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19332 if(getClass() != CLASS_DEATH_KNIGHT
)
19333 return base_talent
;
19335 uint32 talentPointsForLevel
=
19336 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19337 + m_questRewardTalentCount
;
19339 if(talentPointsForLevel
> base_talent
)
19340 talentPointsForLevel
= base_talent
;
19342 return talentPointsForLevel
;
19345 bool Player::IsAllowUseFlyMountsHere() const
19347 if (isGameMaster())
19350 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19351 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19354 void Player::learnSpellHighRank(uint32 spellid
)
19356 learnSpell(spellid
,false);
19358 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19359 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19360 learnSpellHighRank(itr
->second
);
19363 void Player::_LoadSkills()
19365 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19367 // reset skill modifiers and set correct unlearn flags
19368 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
19370 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19372 // set correct unlearn bit
19373 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19376 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19377 if(!pSkill
) continue;
19379 // enable unlearn button for primary professions only
19380 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19381 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19383 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19385 // set fixed skill ranges
19386 switch(GetSkillRangeType(pSkill
,false))
19388 case SKILL_RANGE_LANGUAGE
: // 300..300
19389 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(300,300));
19391 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
19392 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(1,1));
19398 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19399 learnSkillRewardedSpells(id
, vskill
);
19402 // special settings
19403 if(getClass()==CLASS_DEATH_KNIGHT
)
19405 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19408 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19410 base_skill
= 1; // skill mast be known and then > 0 in any case
19412 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19413 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19414 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19415 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19416 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19417 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19418 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19419 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19420 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19421 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19422 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19423 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19424 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19425 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19426 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19427 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19431 uint32
Player::GetPhaseMaskForSpawn() const
19433 uint32 phase
= PHASEMASK_NORMAL
;
19434 if(!isGameMaster())
19435 phase
= GetPhaseMask();
19438 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19439 if(!phases
.empty())
19440 phase
= phases
.front()->GetMiscValue();
19443 // some aura phases include 1 normal map in addition to phase itself
19444 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19447 return PHASEMASK_NORMAL
;
19450 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19452 ItemPrototype
const* pProto
= pItem
->GetProto();
19454 // proto based limitations
19455 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19458 // check unique-equipped on gems
19459 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19461 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19464 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19468 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19472 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19473 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19474 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19476 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19480 return EQUIP_ERR_OK
;
19483 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19485 // check unique-equipped on item
19486 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19488 // there is an equip limit on this item
19489 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19490 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19493 // check unique-equipped limit
19494 if (itemProto
->ItemLimitCategory
)
19496 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19498 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19500 if(limit_count
> limitEntry
->maxCount
)
19501 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19503 // there is an equip limit on this item
19504 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19505 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19508 return EQUIP_ERR_OK
;
19511 void Player::HandleFall(MovementInfo
const& movementInfo
)
19513 // calculate total z distance of the fall
19514 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19515 sLog
.outDebug("zDiff = %f", z_diff
);
19517 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19518 // 14.57 can be calculated by resolving damageperc formula below to 0
19519 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19520 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19521 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19523 //Safe fall, fall height reduction
19524 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19526 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19530 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19532 float height
= movementInfo
.z
;
19533 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
19537 //Prevent fall damage from being more than the player maximum health
19538 if (damage
> GetMaxHealth())
19539 damage
= GetMaxHealth();
19542 if (GetDummyAura(43621))
19543 damage
= GetMaxHealth()/2;
19545 EnvironmentalDamage(DAMAGE_FALL
, damage
);
19547 // recheck alive, might have died of EnvironmentalDamage
19549 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
19552 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19553 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
);
19558 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
19560 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
19563 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
19565 uint32 CurTalentPoints
= GetFreeTalentPoints();
19567 if(CurTalentPoints
== 0)
19570 if (talentRank
>= MAX_TALENT_RANK
)
19573 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
19578 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
19583 // prevent learn talent for different class (cheating)
19584 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
19587 // find current max talent rank
19588 int32 curtalent_maxrank
= 0;
19589 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19591 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
19593 curtalent_maxrank
= k
+ 1;
19598 // we already have same or higher talent rank learned
19599 if(curtalent_maxrank
>= (talentRank
+ 1))
19602 // check if we have enough talent points
19603 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19606 // Check if it requires another talent
19607 if (talentInfo
->DependsOn
> 0)
19609 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19611 bool hasEnoughRank
= false;
19612 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; i
++)
19614 if (depTalentInfo
->RankID
[i
] != 0)
19615 if (HasSpell(depTalentInfo
->RankID
[i
]))
19616 hasEnoughRank
= true;
19618 if (!hasEnoughRank
)
19623 // Find out how many points we have in this field
19624 uint32 spentPoints
= 0;
19626 uint32 tTab
= talentInfo
->TalentTab
;
19627 if (talentInfo
->Row
> 0)
19629 unsigned int numRows
= sTalentStore
.GetNumRows();
19630 for (unsigned int i
= 0; i
< numRows
; i
++) // Loop through all talents.
19632 // Someday, someone needs to revamp
19633 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19634 if (tmpTalent
) // the way talents are tracked
19636 if (tmpTalent
->TalentTab
== tTab
)
19638 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
19640 if (tmpTalent
->RankID
[j
] != 0)
19642 if (HasSpell(tmpTalent
->RankID
[j
]))
19644 spentPoints
+= j
+ 1;
19653 // not have required min points spent in talent tree
19654 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
19657 // spell not set in talent.dbc
19658 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19661 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19666 if(HasSpell(spellid
))
19669 // learn! (other talent ranks will unlearned at learning)
19670 learnSpell(spellid
, false);
19671 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19673 // update free talent points
19674 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19677 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
19679 Pet
*pet
= GetPet();
19684 if(petGuid
!= pet
->GetGUID())
19687 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
19689 if(CurTalentPoints
== 0)
19692 if (talentRank
>= MAX_PET_TALENT_RANK
)
19695 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
19700 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
19705 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
19710 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
19715 if(pet_family
->petTalentType
< 0) // not hunter pet
19718 // prevent learn talent for different family (cheating)
19719 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
19722 // find current max talent rank
19723 int32 curtalent_maxrank
= 0;
19724 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19726 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
19728 curtalent_maxrank
= k
+ 1;
19733 // we already have same or higher talent rank learned
19734 if(curtalent_maxrank
>= (talentRank
+ 1))
19737 // check if we have enough talent points
19738 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19741 // Check if it requires another talent
19742 if (talentInfo
->DependsOn
> 0)
19744 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19746 bool hasEnoughRank
= false;
19747 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; i
++)
19749 if (depTalentInfo
->RankID
[i
] != 0)
19750 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
19751 hasEnoughRank
= true;
19753 if (!hasEnoughRank
)
19758 // Find out how many points we have in this field
19759 uint32 spentPoints
= 0;
19761 uint32 tTab
= talentInfo
->TalentTab
;
19762 if (talentInfo
->Row
> 0)
19764 unsigned int numRows
= sTalentStore
.GetNumRows();
19765 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19767 // Someday, someone needs to revamp
19768 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19769 if (tmpTalent
) // the way talents are tracked
19771 if (tmpTalent
->TalentTab
== tTab
)
19773 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
19775 if (tmpTalent
->RankID
[j
] != 0)
19777 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
19779 spentPoints
+= j
+ 1;
19788 // not have required min points spent in talent tree
19789 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
19792 // spell not set in talent.dbc
19793 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19796 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19801 if(pet
->HasSpell(spellid
))
19804 // learn! (other talent ranks will unlearned at learning)
19805 pet
->learnSpell(spellid
);
19806 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19808 // update free talent points
19809 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19812 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
19814 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
19817 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19819 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19823 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
19825 if (m_lastFallTime
>= minfo
.fallTime
|| m_lastFallZ
<=minfo
.z
|| opcode
== MSG_MOVE_FALL_LAND
)
19826 SetFallInformation(minfo
.fallTime
, minfo
.z
);
19829 void Player::UnsummonPetTemporaryIfAny()
19831 Pet
* pet
= GetPet();
19835 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
19837 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
19838 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
19841 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
19844 void Player::ResummonPetTemporaryUnSummonedIfAny()
19846 if(!m_temporaryUnsummonedPetNumber
)
19849 // not resummon in not appropriate state
19850 if(IsPetNeedBeTemporaryUnsummoned())
19856 Pet
* NewPet
= new Pet
;
19857 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
19860 m_temporaryUnsummonedPetNumber
= 0;