[9715] Implement required basic elements for dual spec learn gossips.
[getmangos.git] / src / game / Player.cpp
blob2a1ab79090b51085bb7ae0fa3bab507bb20bea3f
1 /*
2 * Copyright (C) 2005-2010 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
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.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"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "ObjectGuid.h"
46 #include "CreatureAI.h"
47 #include "Formulas.h"
48 #include "Group.h"
49 #include "Guild.h"
50 #include "Pet.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
58 #include "Chat.h"
59 #include "Database/DatabaseImpl.h"
60 #include "Spell.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
63 #include "Mail.h"
65 #include <cmath>
67 #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
69 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
70 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
71 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
73 #define SKILL_VALUE(x) PAIR32_LOPART(x)
74 #define SKILL_MAX(x) PAIR32_HIPART(x)
75 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
77 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
78 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
79 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
81 enum CharacterFlags
83 CHARACTER_FLAG_NONE = 0x00000000,
84 CHARACTER_FLAG_UNK1 = 0x00000001,
85 CHARACTER_FLAG_UNK2 = 0x00000002,
86 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
87 CHARACTER_FLAG_UNK4 = 0x00000008,
88 CHARACTER_FLAG_UNK5 = 0x00000010,
89 CHARACTER_FLAG_UNK6 = 0x00000020,
90 CHARACTER_FLAG_UNK7 = 0x00000040,
91 CHARACTER_FLAG_UNK8 = 0x00000080,
92 CHARACTER_FLAG_UNK9 = 0x00000100,
93 CHARACTER_FLAG_UNK10 = 0x00000200,
94 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
95 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
96 CHARACTER_FLAG_UNK13 = 0x00001000,
97 CHARACTER_FLAG_GHOST = 0x00002000,
98 CHARACTER_FLAG_RENAME = 0x00004000,
99 CHARACTER_FLAG_UNK16 = 0x00008000,
100 CHARACTER_FLAG_UNK17 = 0x00010000,
101 CHARACTER_FLAG_UNK18 = 0x00020000,
102 CHARACTER_FLAG_UNK19 = 0x00040000,
103 CHARACTER_FLAG_UNK20 = 0x00080000,
104 CHARACTER_FLAG_UNK21 = 0x00100000,
105 CHARACTER_FLAG_UNK22 = 0x00200000,
106 CHARACTER_FLAG_UNK23 = 0x00400000,
107 CHARACTER_FLAG_UNK24 = 0x00800000,
108 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
109 CHARACTER_FLAG_DECLINED = 0x02000000,
110 CHARACTER_FLAG_UNK27 = 0x04000000,
111 CHARACTER_FLAG_UNK28 = 0x08000000,
112 CHARACTER_FLAG_UNK29 = 0x10000000,
113 CHARACTER_FLAG_UNK30 = 0x20000000,
114 CHARACTER_FLAG_UNK31 = 0x40000000,
115 CHARACTER_FLAG_UNK32 = 0x80000000
118 enum CharacterCustomizeFlags
120 CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
121 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
122 CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
123 CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
126 // corpse reclaim times
127 #define DEATH_EXPIRE_STEP (5*MINUTE)
128 #define MAX_DEATH_COUNT 3
130 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
132 //== PlayerTaxi ================================================
134 PlayerTaxi::PlayerTaxi()
136 // Taxi nodes
137 memset(m_taximask, 0, sizeof(m_taximask));
140 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
142 // class specific initial known nodes
143 switch(chrClass)
145 case CLASS_DEATH_KNIGHT:
147 for(int i = 0; i < TaxiMaskSize; ++i)
148 m_taximask[i] |= sOldContinentsNodesMask[i];
149 break;
153 // race specific initial known nodes: capital and taxi hub masks
154 switch(race)
156 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
157 case RACE_ORC: SetTaximaskNode(23); break; // Orc
158 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
159 case RACE_NIGHTELF: SetTaximaskNode(26);
160 SetTaximaskNode(27); break; // Night Elf
161 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
162 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
163 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
164 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
165 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
166 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
169 // new continent starting masks (It will be accessible only at new map)
170 switch(Player::TeamForRace(race))
172 case ALLIANCE: SetTaximaskNode(100); break;
173 case HORDE: SetTaximaskNode(99); break;
175 // level dependent taxi hubs
176 if(level>=68)
177 SetTaximaskNode(213); //Shattered Sun Staging Area
180 void PlayerTaxi::LoadTaxiMask(const char* data)
182 Tokens tokens = StrSplit(data, " ");
184 int index;
185 Tokens::iterator iter;
186 for (iter = tokens.begin(), index = 0;
187 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
189 // load and set bits only for existed taxi nodes
190 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
194 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
196 if(all)
198 for (uint8 i=0; i<TaxiMaskSize; ++i)
199 data << uint32(sTaxiNodesMask[i]); // all existed nodes
201 else
203 for (uint8 i=0; i<TaxiMaskSize; ++i)
204 data << uint32(m_taximask[i]); // known nodes
208 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
210 ClearTaxiDestinations();
212 Tokens tokens = StrSplit(values," ");
214 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
216 uint32 node = uint32(atol(iter->c_str()));
217 AddTaxiDestination(node);
220 if(m_TaxiDestinations.empty())
221 return true;
223 // Check integrity
224 if(m_TaxiDestinations.size() < 2)
225 return false;
227 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
229 uint32 cost;
230 uint32 path;
231 sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
232 if(!path)
233 return false;
236 // can't load taxi path without mount set (quest taxi path?)
237 if(!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
238 return false;
240 return true;
243 std::string PlayerTaxi::SaveTaxiDestinationsToString()
245 if(m_TaxiDestinations.empty())
246 return "";
248 std::ostringstream ss;
250 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
251 ss << m_TaxiDestinations[i] << " ";
253 return ss.str();
256 uint32 PlayerTaxi::GetCurrentTaxiPath() const
258 if(m_TaxiDestinations.size() < 2)
259 return 0;
261 uint32 path;
262 uint32 cost;
264 sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
266 return path;
269 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
271 ss << "'";
272 for(int i = 0; i < TaxiMaskSize; ++i)
273 ss << taxi.m_taximask[i] << " ";
274 ss << "'";
275 return ss;
278 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, SpellEntry const* spellEntry, SpellEffectIndex eff, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(spellEntry->Id), lastAffected(NULL)
280 uint32 const* ptr = spellEntry->GetEffectSpellClassMask(eff);
281 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
282 mask2= ptr[2];
285 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, Aura const* aura, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(aura->GetId()), lastAffected(NULL)
287 uint32 const* ptr = aura->getAuraSpellClassMask();
288 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
289 mask2= ptr[2];
292 bool SpellModifier::isAffectedOnSpell( SpellEntry const *spell ) const
294 SpellEntry const *affect_spell = sSpellStore.LookupEntry(spellId);
295 // False if affect_spell == NULL or spellFamily not equal
296 if (!affect_spell || affect_spell->SpellFamilyName != spell->SpellFamilyName)
297 return false;
298 if (mask & spell->SpellFamilyFlags)
299 return true;
300 if (mask2 & spell->SpellFamilyFlags2)
301 return true;
302 return false;
305 //== Player ====================================================
307 UpdateMask Player::updateVisualBits;
309 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
311 m_transport = 0;
313 m_speakTime = 0;
314 m_speakCount = 0;
316 m_objectType |= TYPEMASK_PLAYER;
317 m_objectTypeId = TYPEID_PLAYER;
319 m_valuesCount = PLAYER_END;
321 m_session = session;
323 m_divider = 0;
325 m_ExtraFlags = 0;
326 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
327 SetAcceptTicket(true);
329 // players always accept
330 if(GetSession()->GetSecurity() == SEC_PLAYER)
331 SetAcceptWhispers(true);
333 m_curSelection = 0;
334 m_lootGuid = 0;
336 m_comboTarget = 0;
337 m_comboPoints = 0;
339 m_usedTalentCount = 0;
340 m_questRewardTalentCount = 0;
342 m_regenTimer = 0;
343 m_weaponChangeTimer = 0;
345 m_zoneUpdateId = 0;
346 m_zoneUpdateTimer = 0;
348 m_areaUpdateId = 0;
350 m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
352 // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
353 // this must help in case next save after mass player load after server startup
354 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
356 clearResurrectRequestData();
358 m_SpellModRemoveCount = 0;
360 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
362 m_social = NULL;
364 // group is initialized in the reference constructor
365 SetGroupInvite(NULL);
366 m_groupUpdateMask = 0;
367 m_auraUpdateMask = 0;
369 duel = NULL;
371 m_GuildIdInvited = 0;
372 m_ArenaTeamIdInvited = 0;
374 m_atLoginFlags = AT_LOGIN_NONE;
376 mSemaphoreTeleport_Near = false;
377 mSemaphoreTeleport_Far = false;
379 m_DelayedOperations = 0;
380 m_bCanDelayTeleport = false;
381 m_bHasDelayedTeleport = false;
382 m_teleport_options = 0;
384 pTrader = 0;
385 ClearTrade();
387 m_cinematic = 0;
389 PlayerTalkClass = new PlayerMenu( GetSession() );
390 m_currentBuybackSlot = BUYBACK_SLOT_START;
392 m_DailyQuestChanged = false;
393 m_WeeklyQuestChanged = false;
395 for (int i=0; i<MAX_TIMERS; ++i)
396 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
398 m_MirrorTimerFlags = UNDERWATER_NONE;
399 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
400 m_isInWater = false;
401 m_drunkTimer = 0;
402 m_drunk = 0;
403 m_restTime = 0;
404 m_deathTimer = 0;
405 m_deathExpireTime = 0;
407 m_swingErrorMsg = 0;
409 m_DetectInvTimer = 1*IN_MILLISECONDS;
411 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
413 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
414 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
417 m_logintime = time(NULL);
418 m_Last_tick = m_logintime;
419 m_WeaponProficiency = 0;
420 m_ArmorProficiency = 0;
421 m_canParry = false;
422 m_canBlock = false;
423 m_canDualWield = false;
424 m_canTitanGrip = false;
425 m_ammoDPS = 0.0f;
427 m_temporaryUnsummonedPetNumber = 0;
428 //cache for UNIT_CREATED_BY_SPELL to allow
429 //returning reagents for temporarily removed pets
430 //when dying/logging out
431 m_oldpetspell = 0;
433 ////////////////////Rest System/////////////////////
434 time_inn_enter=0;
435 inn_trigger_id=0;
436 m_rest_bonus=0;
437 rest_type=REST_TYPE_NO;
438 ////////////////////Rest System/////////////////////
440 m_mailsUpdated = false;
441 unReadMails = 0;
442 m_nextMailDelivereTime = 0;
444 m_resetTalentsCost = 0;
445 m_resetTalentsTime = 0;
446 m_itemUpdateQueueBlocked = false;
448 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
449 m_forced_speed_changes[i] = 0;
451 m_stableSlots = 0;
453 /////////////////// Instance System /////////////////////
455 m_HomebindTimer = 0;
456 m_InstanceValid = true;
457 m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
458 m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
460 m_lastPotionId = 0;
462 m_activeSpec = 0;
463 m_specsCount = 1;
465 for (int i = 0; i < BASEMOD_END; ++i)
467 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
468 m_auraBaseMod[i][PCT_MOD] = 1.0f;
471 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
472 m_baseRatingValue[i] = 0;
474 m_baseSpellPower = 0;
475 m_baseFeralAP = 0;
476 m_baseManaRegen = 0;
477 m_armorPenetrationPct = 0.0f;
479 // Honor System
480 m_lastHonorUpdateTime = time(NULL);
482 // Player summoning
483 m_summon_expire = 0;
484 m_summon_mapid = 0;
485 m_summon_x = 0.0f;
486 m_summon_y = 0.0f;
487 m_summon_z = 0.0f;
489 m_mover = this;
491 m_miniPet = 0;
492 m_contestedPvPTimer = 0;
494 m_declinedname = NULL;
495 m_runes = NULL;
497 m_lastFallTime = 0;
498 m_lastFallZ = 0;
501 Player::~Player ()
503 CleanupsBeforeDelete();
505 // it must be unloaded already in PlayerLogout and accessed only for loggined player
506 //m_social = NULL;
508 // Note: buy back item already deleted from DB when player was saved
509 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
511 if(m_items[i])
512 delete m_items[i];
514 CleanupChannels();
516 //all mailed items should be deleted, also all mail should be deallocated
517 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
518 delete *itr;
520 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
521 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
523 delete PlayerTalkClass;
525 if (m_transport)
527 m_transport->RemovePassenger(this);
530 for(size_t x = 0; x < ItemSetEff.size(); x++)
531 if(ItemSetEff[x])
532 delete ItemSetEff[x];
534 // clean up player-instance binds, may unload some instance saves
535 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
536 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
537 itr->second.save->RemovePlayer(this);
539 delete m_declinedname;
540 delete m_runes;
543 void Player::CleanupsBeforeDelete()
545 if(m_uint32Values) // only for fully created Object
547 TradeCancel(false);
548 DuelComplete(DUEL_INTERUPTED);
550 Unit::CleanupsBeforeDelete();
553 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 */)
555 //FIXME: outfitId not used in player creating
557 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
559 m_name = name;
561 PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
562 if(!info)
564 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
565 return false;
568 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
569 m_items[i] = NULL;
571 SetLocationMapId(info->mapId);
572 Relocate(info->positionX,info->positionY,info->positionZ);
574 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
575 if(!cEntry)
577 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
578 return false;
581 SetMap(sMapMgr.CreateMap(info->mapId, this));
583 uint8 powertype = cEntry->powerType;
585 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
586 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
588 setFactionForRace(race);
590 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
592 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
593 InitDisplayIds();
594 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
595 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
596 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
597 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
598 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
600 // -1 is default value
601 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1);
603 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
604 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
605 SetByteValue(PLAYER_BYTES_3, 0, gender);
606 SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1)
608 SetUInt32Value( PLAYER_GUILDID, 0 );
609 SetUInt32Value( PLAYER_GUILDRANK, 0 );
610 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
612 for(int i = 0; i < KNOWN_TITLES_SIZE; ++i)
613 SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled
614 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
616 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
617 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
618 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
619 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
621 // set starting level
622 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
623 ? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL)
624 : sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL);
626 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
628 uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL);
629 if(gm_level > start_level)
630 start_level = gm_level;
633 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
635 InitRunes();
637 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_UINT32_START_PLAYER_MONEY));
638 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_UINT32_START_HONOR_POINTS));
639 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_UINT32_START_ARENA_POINTS));
641 // Played time
642 m_Last_tick = time(NULL);
643 m_Played_time[PLAYED_TIME_TOTAL] = 0;
644 m_Played_time[PLAYED_TIME_LEVEL] = 0;
646 // base stats and related field values
647 InitStatsForLevel();
648 InitTaxiNodesForLevel();
649 InitGlyphsForLevel();
650 InitTalentForLevel();
651 InitPrimaryProfessions(); // to max set before any spell added
653 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
654 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
655 SetHealth(GetMaxHealth());
656 if (getPowerType()==POWER_MANA)
658 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
659 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
662 if(getPowerType() == POWER_RUNIC_POWER)
664 SetPower(POWER_RUNE, 8);
665 SetMaxPower(POWER_RUNE, 8);
666 SetPower(POWER_RUNIC_POWER, 0);
667 SetMaxPower(POWER_RUNIC_POWER, 1000);
670 // original spells
671 learnDefaultSpells();
673 // original action bar
674 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
675 addActionButton(0, action_itr->button,action_itr->action,action_itr->type);
677 // original items
678 CharStartOutfitEntry const* oEntry = NULL;
679 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
681 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
683 if(entry->RaceClassGender == RaceClassGender)
685 oEntry = entry;
686 break;
691 if(oEntry)
693 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
695 if(oEntry->ItemId[j] <= 0)
696 continue;
698 uint32 item_id = oEntry->ItemId[j];
700 // just skip, reported in ObjectMgr::LoadItemPrototypes
701 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
702 if(!iProto)
703 continue;
705 // BuyCount by default
706 int32 count = iProto->BuyCount;
708 // special amount for foor/drink
709 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
711 switch(iProto->Spells[0].SpellCategory)
713 case 11: // food
714 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
715 break;
716 case 59: // drink
717 count = 2;
718 break;
720 if(iProto->Stackable < count)
721 count = iProto->Stackable;
723 // special amount for daggers
724 else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
726 count = 2; // will placed to 2 slots
729 StoreNewItemInBestSlots(item_id, count);
733 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
734 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
736 // bags and main-hand weapon must equipped at this moment
737 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
738 // or ammo not equipped in special bag
739 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
741 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
743 uint16 eDest;
744 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
745 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
746 if( msg == EQUIP_ERR_OK )
748 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
749 EquipItem( eDest, pItem, true);
751 // move other items to more appropriate slots (ammo not equipped in special bag)
752 else
754 ItemPosCountVec sDest;
755 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
756 if( msg == EQUIP_ERR_OK )
758 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
759 pItem = StoreItem( sDest, pItem, true);
762 // if this is ammo then use it
763 msg = CanUseAmmo( pItem->GetEntry() );
764 if( msg == EQUIP_ERR_OK )
765 SetAmmo( pItem->GetEntry() );
769 // all item positions resolved
771 return true;
774 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
776 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
778 // attempt equip by one
779 while(titem_amount > 0)
781 uint16 eDest;
782 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
783 if( msg != EQUIP_ERR_OK )
784 break;
786 EquipNewItem( eDest, titem_id, true);
787 AutoUnequipOffhandIfNeed();
788 --titem_amount;
791 if(titem_amount == 0)
792 return true; // equipped
794 // attempt store
795 ItemPosCountVec sDest;
796 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
797 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
798 if( msg == EQUIP_ERR_OK )
800 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
801 return true; // stored
804 // item can't be added
805 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
806 return false;
809 // helper function, mainly for script side, but can be used for simple task in mangos also.
810 Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
812 ItemPosCountVec vDest;
814 uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
816 if (msg == EQUIP_ERR_OK)
818 if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
819 return pItem;
822 return NULL;
825 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
827 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
829 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
830 StopMirrorTimer(Type);
831 return;
833 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
834 data << (uint32)Type;
835 data << CurrentValue;
836 data << MaxValue;
837 data << Regen;
838 data << (uint8)0;
839 data << (uint32)0; // spell id
840 GetSession()->SendPacket( &data );
843 void Player::StopMirrorTimer(MirrorTimerType Type)
845 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
846 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
847 data << (uint32)Type;
848 GetSession()->SendPacket( &data );
851 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
853 if(!isAlive() || isGameMaster())
854 return 0;
856 // Absorb, resist some environmental damage type
857 uint32 absorb = 0;
858 uint32 resist = 0;
859 if (type == DAMAGE_LAVA)
860 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
861 else if (type == DAMAGE_SLIME)
862 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
864 damage-=absorb+resist;
866 DealDamageMods(this,damage,&absorb);
868 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
869 data << uint64(GetGUID());
870 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
871 data << uint32(damage);
872 data << uint32(absorb);
873 data << uint32(resist);
874 SendMessageToSet(&data, true);
876 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
878 if(!isAlive())
880 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
882 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
883 DurabilityLossAll(0.10f,false);
884 // durability lost message
885 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
886 GetSession()->SendPacket(&data2);
889 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
892 return final_damage;
895 int32 Player::getMaxTimer(MirrorTimerType timer)
897 switch (timer)
899 case FATIGUE_TIMER:
900 if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL))
901 return DISABLED_MIRROR_TIMER;
902 return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX)*IN_MILLISECONDS;
903 case BREATH_TIMER:
905 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
906 GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL))
907 return DISABLED_MIRROR_TIMER;
908 int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX)*IN_MILLISECONDS;
909 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
910 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
911 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
912 return UnderWaterTime;
914 case FIRE_TIMER:
916 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL))
917 return DISABLED_MIRROR_TIMER;
918 return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX)*IN_MILLISECONDS;
920 default:
921 return 0;
923 return 0;
926 void Player::UpdateMirrorTimers()
928 // Desync flags for update on next HandleDrowning
929 if (m_MirrorTimerFlags)
930 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
933 void Player::HandleDrowning(uint32 time_diff)
935 if (!m_MirrorTimerFlags)
936 return;
938 // In water
939 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
941 // Breath timer not activated - activate it
942 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
944 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
945 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
947 else // If activated - do tick
949 m_MirrorTimer[BREATH_TIMER]-=time_diff;
950 // Timer limit - need deal damage
951 if (m_MirrorTimer[BREATH_TIMER] < 0)
953 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILLISECONDS;
954 // Calculate and deal damage
955 // TODO: Check this formula
956 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
957 EnvironmentalDamage(DAMAGE_DROWNING, damage);
959 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
960 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
963 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
965 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
966 // Need breath regen
967 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
968 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
969 StopMirrorTimer(BREATH_TIMER);
970 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
971 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
974 // In dark water
975 if (m_MirrorTimerFlags & UNDERWATER_INDARKWATER)
977 // Fatigue timer not activated - activate it
978 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
980 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
981 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
983 else
985 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
986 // Timer limit - need deal damage or teleport ghost to graveyard
987 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
989 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILLISECONDS;
990 if (isAlive()) // Calculate and deal damage
992 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
993 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
995 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
996 RepopAtGraveyard();
998 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER))
999 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
1002 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
1004 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
1005 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
1006 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
1007 StopMirrorTimer(FATIGUE_TIMER);
1008 else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER)
1009 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
1012 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
1014 // Breath timer not activated - activate it
1015 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
1016 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
1017 else
1019 m_MirrorTimer[FIRE_TIMER]-=time_diff;
1020 if (m_MirrorTimer[FIRE_TIMER] < 0)
1022 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILLISECONDS;
1023 // Calculate and deal damage
1024 // TODO: Check this formula
1025 uint32 damage = urand(600, 700);
1026 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1027 EnvironmentalDamage(DAMAGE_LAVA, damage);
1028 else
1029 EnvironmentalDamage(DAMAGE_SLIME, damage);
1033 else
1034 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1036 // Recheck timers flag
1037 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1038 for (int i = 0; i< MAX_TIMERS; ++i)
1039 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1041 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1042 break;
1044 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1047 ///The player sobers by 256 every 10 seconds
1048 void Player::HandleSobering()
1050 m_drunkTimer = 0;
1052 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1053 SetDrunkValue(drunk);
1056 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1058 if(value >= 23000)
1059 return DRUNKEN_SMASHED;
1060 if(value >= 12800)
1061 return DRUNKEN_DRUNK;
1062 if(value & 0xFFFE)
1063 return DRUNKEN_TIPSY;
1064 return DRUNKEN_SOBER;
1067 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1069 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1071 m_drunk = newDrunkenValue;
1072 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1074 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1076 // special drunk invisibility detection
1077 if(newDrunkenState >= DRUNKEN_DRUNK)
1078 m_detectInvisibilityMask |= (1<<6);
1079 else
1080 m_detectInvisibilityMask &= ~(1<<6);
1082 if(newDrunkenState == oldDrunkenState)
1083 return;
1085 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1086 data << uint64(GetGUID());
1087 data << uint32(newDrunkenState);
1088 data << uint32(itemId);
1090 SendMessageToSet(&data, true);
1093 void Player::Update( uint32 p_time )
1095 if(!IsInWorld())
1096 return;
1098 // undelivered mail
1099 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1101 SendNewMail();
1102 ++unReadMails;
1104 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1105 m_nextMailDelivereTime = 0;
1108 //used to implement delayed far teleports
1109 SetCanDelayTeleport(true);
1110 Unit::Update( p_time );
1111 SetCanDelayTeleport(false);
1113 // update player only attacks
1114 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1116 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1119 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1121 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1124 time_t now = time (NULL);
1126 UpdatePvPFlag(now);
1128 UpdateContestedPvP(p_time);
1130 UpdateDuelFlag(now);
1132 CheckDuelDistance(now);
1134 UpdateAfkReport(now);
1136 // Update items that have just a limited lifetime
1137 if (now>m_Last_tick)
1138 UpdateItemDuration(uint32(now- m_Last_tick));
1140 if (!m_timedquests.empty())
1142 QuestSet::iterator iter = m_timedquests.begin();
1143 while (iter != m_timedquests.end())
1145 QuestStatusData& q_status = mQuestStatus[*iter];
1146 if( q_status.m_timer <= p_time )
1148 uint32 quest_id = *iter;
1149 ++iter; // current iter will be removed in FailQuest
1150 FailQuest(quest_id);
1152 else
1154 q_status.m_timer -= p_time;
1155 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1156 ++iter;
1161 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1163 Unit *pVictim = getVictim();
1164 if (pVictim && !IsNonMeleeSpellCasted(false))
1166 // default combat reach 10
1167 // TODO add weapon,skill check
1169 float pldistance = ATTACK_DISTANCE;
1171 if (isAttackReady(BASE_ATTACK))
1173 if(!IsWithinDistInMap(pVictim, pldistance))
1175 setAttackTimer(BASE_ATTACK,100);
1176 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1178 SendAttackSwingNotInRange();
1179 m_swingErrorMsg = 1;
1182 //120 degrees of radiant range
1183 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1185 setAttackTimer(BASE_ATTACK,100);
1186 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1188 SendAttackSwingBadFacingAttack();
1189 m_swingErrorMsg = 2;
1192 else
1194 m_swingErrorMsg = 0; // reset swing error state
1196 // prevent base and off attack in same time, delay attack at 0.2 sec
1197 if(haveOffhandWeapon())
1199 uint32 off_att = getAttackTimer(OFF_ATTACK);
1200 if(off_att < ATTACK_DISPLAY_DELAY)
1201 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1203 AttackerStateUpdate(pVictim, BASE_ATTACK);
1204 resetAttackTimer(BASE_ATTACK);
1208 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1210 if(!IsWithinDistInMap(pVictim, pldistance))
1212 setAttackTimer(OFF_ATTACK,100);
1214 else if( !HasInArc( 2*M_PI_F/3, pVictim ))
1216 setAttackTimer(OFF_ATTACK,100);
1218 else
1220 // prevent base and off attack in same time, delay attack at 0.2 sec
1221 uint32 base_att = getAttackTimer(BASE_ATTACK);
1222 if(base_att < ATTACK_DISPLAY_DELAY)
1223 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1224 // do attack
1225 AttackerStateUpdate(pVictim, OFF_ATTACK);
1226 resetAttackTimer(OFF_ATTACK);
1230 Unit *owner = pVictim->GetOwner();
1231 Unit *u = owner ? owner : pVictim;
1232 if(u->IsPvP() && (!duel || duel->opponent != u))
1234 UpdatePvP(true);
1235 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1240 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1242 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1244 time_t time_inn = time(NULL)-GetTimeInnEnter();
1245 if (time_inn >= 10) //freeze update
1247 float bubble = 0.125f*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME);
1248 //speed collect rest bonus (section/in hour)
1249 SetRestBonus( float(GetRestBonus()+ time_inn*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble ));
1250 UpdateInnerTime(time(NULL));
1255 if (m_regenTimer)
1257 if(p_time >= m_regenTimer)
1258 m_regenTimer = 0;
1259 else
1260 m_regenTimer -= p_time;
1263 if (m_weaponChangeTimer > 0)
1265 if(p_time >= m_weaponChangeTimer)
1266 m_weaponChangeTimer = 0;
1267 else
1268 m_weaponChangeTimer -= p_time;
1271 if (m_zoneUpdateTimer > 0)
1273 if(p_time >= m_zoneUpdateTimer)
1275 uint32 newzone, newarea;
1276 GetZoneAndAreaId(newzone,newarea);
1278 if( m_zoneUpdateId != newzone )
1279 UpdateZone(newzone,newarea); // also update area
1280 else
1282 // use area updates as well
1283 // needed for free far all arenas for example
1284 if( m_areaUpdateId != newarea )
1285 UpdateArea(newarea);
1287 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1290 else
1291 m_zoneUpdateTimer -= p_time;
1294 if (m_timeSyncTimer > 0)
1296 if(p_time >= m_timeSyncTimer)
1297 SendTimeSync();
1298 else
1299 m_timeSyncTimer -= p_time;
1302 if (isAlive())
1304 // if no longer casting, set regen power as soon as it is up.
1305 if (!IsUnderLastManaUseEffect())
1306 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1308 if (!m_regenTimer)
1309 RegenerateAll();
1312 if (m_deathState == JUST_DIED)
1313 KillPlayer();
1315 if(m_nextSave > 0)
1317 if(p_time >= m_nextSave)
1319 // m_nextSave reseted in SaveToDB call
1320 SaveToDB();
1321 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1323 else
1324 m_nextSave -= p_time;
1327 //Handle Water/drowning
1328 HandleDrowning(p_time);
1330 //Handle detect stealth players
1331 if (m_DetectInvTimer > 0)
1333 if (p_time >= m_DetectInvTimer)
1335 HandleStealthedUnitsDetection();
1336 m_DetectInvTimer = 3000;
1338 else
1339 m_DetectInvTimer -= p_time;
1342 // Played time
1343 if (now > m_Last_tick)
1345 uint32 elapsed = uint32(now - m_Last_tick);
1346 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1347 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1348 m_Last_tick = now;
1351 if (m_drunk)
1353 m_drunkTimer += p_time;
1355 if (m_drunkTimer > 10*IN_MILLISECONDS)
1356 HandleSobering();
1359 // not auto-free ghost from body in instances
1360 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1362 if(p_time >= m_deathTimer)
1364 m_deathTimer = 0;
1365 BuildPlayerRepop();
1366 RepopAtGraveyard();
1368 else
1369 m_deathTimer -= p_time;
1372 UpdateEnchantTime(p_time);
1373 UpdateHomebindTime(p_time);
1375 // group update
1376 SendUpdateToOutOfRangeGroupMembers();
1378 Pet* pet = GetPet();
1379 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1381 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1384 //we should execute delayed teleports only for alive(!) players
1385 //because we don't want player's ghost teleported from graveyard
1386 if(IsHasDelayedTeleport() && isAlive())
1387 TeleportTo(m_teleport_dest, m_teleport_options);
1390 void Player::setDeathState(DeathState s)
1392 uint32 ressSpellId = 0;
1394 bool cur = isAlive();
1396 if(s == JUST_DIED && cur)
1398 // drunken state is cleared on death
1399 SetDrunkValue(0);
1400 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1401 ClearComboPoints();
1403 clearResurrectRequestData();
1405 // remove form before other mods to prevent incorrect stats calculation
1406 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1408 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1409 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1411 // remove uncontrolled pets
1412 RemoveMiniPet();
1414 // save value before aura remove in Unit::setDeathState
1415 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1417 // passive spell
1418 if(!ressSpellId)
1419 ressSpellId = GetResurrectionSpellId();
1420 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1421 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1422 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1424 Unit::setDeathState(s);
1426 // restore resurrection spell id for player after aura remove
1427 if(s == JUST_DIED && cur && ressSpellId)
1428 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1430 if(isAlive() && !cur)
1432 //clear aura case after resurrection by another way (spells will be applied before next death)
1433 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1435 // restore default warrior stance
1436 if(getClass()== CLASS_WARRIOR)
1437 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1441 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1443 // 0 1 2 3 4 5 6 7
1444 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1445 // 8 9 10 11 12 13 14
1446 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1447 // 15 16 17 18 19 20
1448 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, character_declinedname.genitive "
1450 Field *fields = result->Fetch();
1452 uint32 guid = fields[0].GetUInt32();
1453 uint8 pRace = fields[2].GetUInt8();
1454 uint8 pClass = fields[3].GetUInt8();
1456 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1457 if(!info)
1459 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1460 return false;
1463 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1464 *p_data << fields[1].GetString(); // name
1465 *p_data << uint8(pRace); // race
1466 *p_data << uint8(pClass); // class
1467 *p_data << uint8(fields[4].GetUInt8()); // gender
1469 uint32 playerBytes = fields[5].GetUInt32();
1470 *p_data << uint8(playerBytes); // skin
1471 *p_data << uint8(playerBytes >> 8); // face
1472 *p_data << uint8(playerBytes >> 16); // hair style
1473 *p_data << uint8(playerBytes >> 24); // hair color
1475 uint32 playerBytes2 = fields[6].GetUInt32();
1476 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1478 *p_data << uint8(fields[7].GetUInt8()); // level
1479 *p_data << uint32(fields[8].GetUInt32()); // zone
1480 *p_data << uint32(fields[9].GetUInt32()); // map
1482 *p_data << fields[10].GetFloat(); // x
1483 *p_data << fields[11].GetFloat(); // y
1484 *p_data << fields[12].GetFloat(); // z
1486 *p_data << uint32(fields[13].GetUInt32()); // guild id
1488 uint32 char_flags = 0;
1489 uint32 playerFlags = fields[14].GetUInt32();
1490 uint32 atLoginFlags = fields[15].GetUInt32();
1491 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1492 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1493 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1494 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1495 if(playerFlags & PLAYER_FLAGS_GHOST)
1496 char_flags |= CHARACTER_FLAG_GHOST;
1497 if(atLoginFlags & AT_LOGIN_RENAME)
1498 char_flags |= CHARACTER_FLAG_RENAME;
1499 if(sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED))
1501 if(!fields[20].GetCppString().empty())
1502 char_flags |= CHARACTER_FLAG_DECLINED;
1504 else
1505 char_flags |= CHARACTER_FLAG_DECLINED;
1507 *p_data << uint32(char_flags); // character flags
1508 // character customize flags
1509 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1510 // First login
1511 *p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
1513 // Pets info
1515 uint32 petDisplayId = 0;
1516 uint32 petLevel = 0;
1517 uint32 petFamily = 0;
1519 // show pet at selection character in character list only for non-ghost character
1520 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1522 uint32 entry = fields[16].GetUInt32();
1523 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1524 if(cInfo)
1526 petDisplayId = fields[17].GetUInt32();
1527 petLevel = fields[18].GetUInt32();
1528 petFamily = cInfo->family;
1532 *p_data << uint32(petDisplayId);
1533 *p_data << uint32(petLevel);
1534 *p_data << uint32(petFamily);
1538 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1539 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1541 uint32 visualbase = slot * 2;
1542 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1543 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1544 if(!proto)
1546 *p_data << uint32(0);
1547 *p_data << uint8(0);
1548 *p_data << uint32(0);
1549 continue;
1552 SpellItemEnchantmentEntry const *enchant = NULL;
1554 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1555 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1557 // values stored in 2 uint16
1558 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1559 if(!enchantId)
1560 continue;
1562 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1563 break;
1566 *p_data << uint32(proto->DisplayInfoID);
1567 *p_data << uint8(proto->InventoryType);
1568 *p_data << uint32(enchant ? enchant->aura_id : 0);
1571 *p_data << uint32(0); // bag 1 display id
1572 *p_data << uint8(0); // bag 1 inventory type
1573 *p_data << uint32(0); // enchant?
1574 *p_data << uint32(0); // bag 2 display id
1575 *p_data << uint8(0); // bag 2 inventory type
1576 *p_data << uint32(0); // enchant?
1577 *p_data << uint32(0); // bag 3 display id
1578 *p_data << uint8(0); // bag 3 inventory type
1579 *p_data << uint32(0); // enchant?
1580 *p_data << uint32(0); // bag 4 display id
1581 *p_data << uint8(0); // bag 4 inventory type
1582 *p_data << uint32(0); // enchant?
1584 return true;
1587 bool Player::ToggleAFK()
1589 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1591 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1593 // afk player not allowed in battleground
1594 if(state && InBattleGround())
1595 LeaveBattleground();
1597 return state;
1600 bool Player::ToggleDND()
1602 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1604 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1607 uint8 Player::chatTag() const
1609 // it's bitmask
1610 // 0x8 - ??
1611 // 0x4 - gm
1612 // 0x2 - dnd
1613 // 0x1 - afk
1614 if(isGMChat())
1615 return 4;
1616 else if(isDND())
1617 return 3;
1618 if(isAFK())
1619 return 1;
1620 else
1621 return 0;
1624 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1626 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1628 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1629 return false;
1632 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1633 Pet* pet = GetPet();
1635 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1637 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1638 // don't let gm level > 1 either
1639 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1640 return false;
1642 // client without expansion support
1643 if(GetSession()->Expansion() < mEntry->Expansion())
1645 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1647 if(GetTransport())
1648 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1650 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1652 return false; // normal client can't teleport to this map...
1654 else
1656 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1659 // if we were on a transport, leave
1660 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1662 m_transport->RemovePassenger(this);
1663 m_transport = NULL;
1664 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
1667 // The player was ported to another map and looses the duel immediately.
1668 // We have to perform this check before the teleport, otherwise the
1669 // ObjectAccessor won't find the flag.
1670 if (duel && GetMapId() != mapid)
1672 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1673 if (obj)
1674 DuelComplete(DUEL_FLED);
1677 // reset movement flags at teleport, because player will continue move with these flags after teleport
1678 m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
1680 if ((GetMapId() == mapid) && (!m_transport))
1682 //lets reset far teleport flag if it wasn't reset during chained teleports
1683 SetSemaphoreTeleportFar(false);
1684 //setup delayed teleport flag
1685 SetDelayedTeleportFlag(IsCanDelayTeleport());
1686 //if teleport spell is casted in Unit::Update() func
1687 //then we need to delay it until update process will be finished
1688 if(IsHasDelayedTeleport())
1690 SetSemaphoreTeleportNear(true);
1691 //lets save teleport destination for player
1692 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1693 m_teleport_options = options;
1694 return true;
1697 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1699 //same map, only remove pet if out of range for new position
1700 if(pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
1701 UnsummonPetTemporaryIfAny();
1704 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1705 CombatStop();
1707 // this will be used instead of the current location in SaveToDB
1708 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1709 SetFallInformation(0, z);
1711 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1712 // at client packet MSG_MOVE_TELEPORT_ACK
1713 SetSemaphoreTeleportNear(true);
1714 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1715 if(!GetSession()->PlayerLogout())
1717 WorldPacket data;
1718 BuildTeleportAckMsg(&data, x, y, z, orientation);
1719 GetSession()->SendPacket(&data);
1722 else
1724 // far teleport to another map
1725 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1726 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1728 // Check enter rights before map getting to avoid creating instance copy for player
1729 // this check not dependent from map instance copy and same for all instance copies of selected map
1730 if (!sMapMgr.CanPlayerEnter(mapid, this))
1731 return false;
1733 // If the map is not created, assume it is possible to enter it.
1734 // It will be created in the WorldPortAck.
1735 Map *map = sMapMgr.FindMap(mapid);
1736 if (!map || map->CanEnter(this))
1738 //lets reset near teleport flag if it wasn't reset during chained teleports
1739 SetSemaphoreTeleportNear(false);
1740 //setup delayed teleport flag
1741 SetDelayedTeleportFlag(IsCanDelayTeleport());
1742 //if teleport spell is casted in Unit::Update() func
1743 //then we need to delay it until update process will be finished
1744 if(IsHasDelayedTeleport())
1746 SetSemaphoreTeleportFar(true);
1747 //lets save teleport destination for player
1748 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1749 m_teleport_options = options;
1750 return true;
1753 SetSelection(0);
1755 CombatStop();
1757 ResetContestedPvP();
1759 // remove player from battleground on far teleport (when changing maps)
1760 if(BattleGround const* bg = GetBattleGround())
1762 // Note: at battleground join battleground id set before teleport
1763 // and we already will found "current" battleground
1764 // just need check that this is targeted map or leave
1765 if(bg->GetMapId() != mapid)
1766 LeaveBattleground(false); // don't teleport to entry point
1769 // remove pet on map change
1770 if (pet)
1771 UnsummonPetTemporaryIfAny();
1773 // remove all dyn objects
1774 RemoveAllDynObjects();
1776 // stop spellcasting
1777 // not attempt interrupt teleportation spell at caster teleport
1778 if(!(options & TELE_TO_SPELL))
1779 if(IsNonMeleeSpellCasted(true))
1780 InterruptNonMeleeSpells(true);
1782 //remove auras before removing from map...
1783 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1785 if(!GetSession()->PlayerLogout())
1787 // send transfer packets
1788 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1789 data << uint32(mapid);
1790 if (m_transport)
1792 data << uint32(m_transport->GetEntry());
1793 data << uint32(GetMapId());
1795 GetSession()->SendPacket(&data);
1797 data.Initialize(SMSG_NEW_WORLD, (20));
1798 if (m_transport)
1800 data << uint32(mapid);
1801 data << float(m_movementInfo.GetTransportPos()->x);
1802 data << float(m_movementInfo.GetTransportPos()->y);
1803 data << float(m_movementInfo.GetTransportPos()->z);
1804 data << float(m_movementInfo.GetTransportPos()->o);
1806 else
1808 data << uint32(mapid);
1809 data << float(x);
1810 data << float(y);
1811 data << float(z);
1812 data << float(orientation);
1814 GetSession()->SendPacket( &data );
1815 SendSavedInstances();
1818 // remove from old map now
1819 if(oldmap)
1820 oldmap->Remove(this, false);
1822 // new final coordinates
1823 float final_x = x;
1824 float final_y = y;
1825 float final_z = z;
1826 float final_o = orientation;
1828 if(m_transport)
1830 final_x += m_movementInfo.GetTransportPos()->x;
1831 final_y += m_movementInfo.GetTransportPos()->y;
1832 final_z += m_movementInfo.GetTransportPos()->z;
1833 final_o += m_movementInfo.GetTransportPos()->o;
1836 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1837 SetFallInformation(0, final_z);
1838 // if the player is saved before worldport ack (at logout for example)
1839 // this will be used instead of the current location in SaveToDB
1841 // move packet sent by client always after far teleport
1842 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1843 SetSemaphoreTeleportFar(true);
1845 else
1846 return false;
1848 return true;
1851 bool Player::TeleportToBGEntryPoint()
1853 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1854 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1855 return TeleportTo(m_bgData.joinPos);
1858 void Player::ProcessDelayedOperations()
1860 if(m_DelayedOperations == 0)
1861 return;
1863 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1865 ResurrectPlayer(0.0f, false);
1867 if(GetMaxHealth() > m_resurrectHealth)
1868 SetHealth( m_resurrectHealth );
1869 else
1870 SetHealth( GetMaxHealth() );
1872 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1873 SetPower(POWER_MANA, m_resurrectMana );
1874 else
1875 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1877 SetPower(POWER_RAGE, 0 );
1878 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1880 SpawnCorpseBones();
1883 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1885 SaveToDB();
1888 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1890 CastSpell(this, 26013, true); // Deserter
1893 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1895 if (m_bgData.mountSpell)
1897 CastSpell(this, m_bgData.mountSpell, true);
1898 m_bgData.mountSpell = 0;
1902 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1904 if (m_bgData.HasTaxiPath())
1906 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1907 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1908 m_bgData.ClearTaxiPath();
1910 ContinueTaxiFlight();
1914 //we have executed ALL delayed ops, so clear the flag
1915 m_DelayedOperations = 0;
1918 void Player::AddToWorld()
1920 ///- Do not add/remove the player from the object storage
1921 ///- It will crash when updating the ObjectAccessor
1922 ///- The player should only be added when logging in
1923 Unit::AddToWorld();
1925 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1927 if(m_items[i])
1928 m_items[i]->AddToWorld();
1932 void Player::RemoveFromWorld()
1934 // cleanup
1935 if(IsInWorld())
1937 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1938 UnsummonAllTotems();
1939 RemoveMiniPet();
1942 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1944 if(m_items[i])
1945 m_items[i]->RemoveFromWorld();
1948 ///- Do not add/remove the player from the object storage
1949 ///- It will crash when updating the ObjectAccessor
1950 ///- The player should only be removed when logging out
1951 Unit::RemoveFromWorld();
1954 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1956 float addRage;
1958 float rageconversion = float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f;
1960 if(attacker)
1962 addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2.0f);
1964 // talent who gave more rage on attack
1965 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1967 else
1969 addRage = damage/rageconversion*2.5f;
1971 // Berserker Rage effect
1972 if (HasAura(18499, EFFECT_INDEX_0))
1973 addRage *= 1.3f;
1976 addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME);
1978 ModifyPower(POWER_RAGE, uint32(addRage*10));
1981 void Player::RegenerateAll(uint32 diff)
1983 // Not in combat or they have regeneration
1984 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1985 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1987 RegenerateHealth(diff);
1988 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1990 Regenerate(POWER_RAGE, diff);
1991 if(getClass() == CLASS_DEATH_KNIGHT)
1992 Regenerate(POWER_RUNIC_POWER, diff);
1996 Regenerate(POWER_ENERGY, diff);
1998 Regenerate(POWER_MANA, diff);
2000 if (getClass() == CLASS_DEATH_KNIGHT)
2001 Regenerate(POWER_RUNE, diff);
2003 m_regenTimer = REGEN_TIME_FULL;
2006 // diff contains the time in milliseconds since last regen.
2007 void Player::Regenerate(Powers power, uint32 diff)
2009 uint32 curValue = GetPower(power);
2010 uint32 maxValue = GetMaxPower(power);
2012 float addvalue = 0.0f;
2014 switch (power)
2016 case POWER_MANA:
2018 bool recentCast = IsUnderLastManaUseEffect();
2019 float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
2020 if (recentCast)
2022 // Mangos Updates Mana in intervals of 2s, which is correct
2023 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2025 else
2027 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2029 } break;
2030 case POWER_RAGE: // Regenerate rage
2032 float RageDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS);
2033 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2034 } break;
2035 case POWER_ENERGY: // Regenerate energy (rogue)
2036 addvalue = 20;
2037 break;
2038 case POWER_RUNIC_POWER:
2040 float RunicPowerDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS);
2041 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
2042 } break;
2043 case POWER_RUNE:
2045 if (getClass() != CLASS_DEATH_KNIGHT)
2046 break;
2048 for(uint32 rune = 0; rune < MAX_RUNES; ++rune)
2050 if(uint16 cd = GetRuneCooldown(rune)) // if we have cooldown, reduce it...
2052 uint32 cd_diff = diff;
2053 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2054 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2055 if ((*i)->GetModifier()->m_miscvalue == power && (*i)->GetMiscBValue()==GetCurrentRune(rune))
2056 cd_diff = cd_diff * ((*i)->GetModifier()->m_amount + 100) / 100;
2058 SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff);
2061 } break;
2062 case POWER_FOCUS:
2063 case POWER_HAPPINESS:
2064 case POWER_HEALTH:
2065 break;
2068 // Mana regen calculated in Player::UpdateManaRegen()
2069 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2070 if(power != POWER_MANA)
2072 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2073 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2074 if ((*i)->GetModifier()->m_miscvalue == power)
2075 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2078 // addvalue computed on a 2sec basis. => update to diff time
2079 addvalue *= float(diff) / REGEN_TIME_FULL;
2081 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2083 curValue += uint32(addvalue);
2084 if (curValue > maxValue)
2085 curValue = maxValue;
2087 else
2089 if(curValue <= uint32(addvalue))
2090 curValue = 0;
2091 else
2092 curValue -= uint32(addvalue);
2094 SetPower(power, curValue);
2097 void Player::RegenerateHealth(uint32 diff)
2099 uint32 curValue = GetHealth();
2100 uint32 maxValue = GetMaxHealth();
2102 if (curValue >= maxValue) return;
2104 float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
2106 float addvalue = 0.0f;
2108 // polymorphed case
2109 if ( IsPolymorphed() )
2110 addvalue = (float)GetMaxHealth()/3;
2111 // normal regen case (maybe partly in combat case)
2112 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2114 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2115 if (!isInCombat())
2117 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2118 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2119 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2121 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2122 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2124 if(!IsStandState())
2125 addvalue *= 1.5;
2128 // always regeneration bonus (including combat)
2129 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2131 if(addvalue < 0)
2132 addvalue = 0;
2134 addvalue *= (float)diff / REGEN_TIME_FULL;
2136 ModifyHealth(int32(addvalue));
2139 Creature* Player::GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask)
2141 // some basic checks
2142 if (guid.IsEmpty() || !IsInWorld() || isInFlight())
2143 return NULL;
2145 // exist (we need look pets also for some interaction (quest/etc)
2146 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2147 if (!unit)
2148 return NULL;
2150 // appropriate npc type
2151 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2152 return NULL;
2154 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2156 if (getClass() != CLASS_HUNTER)
2157 return NULL;
2160 // if a dead unit should be able to talk - the creature must be alive and have special flags
2161 if (!unit->isAlive())
2162 return NULL;
2164 if (isAlive() && unit->isInvisibleForAlive())
2165 return NULL;
2167 // not allow interaction under control, but allow with own pets
2168 if (unit->GetCharmerGUID())
2169 return NULL;
2171 // not enemy
2172 if (unit->IsHostileTo(this))
2173 return NULL;
2175 // not unfriendly
2176 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2177 if(factionTemplate->faction)
2178 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2179 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2180 return NULL;
2182 // not too far
2183 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2184 return NULL;
2186 return unit;
2189 GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type) const
2191 // some basic checks
2192 if (guid.IsEmpty() || !IsInWorld() || isInFlight())
2193 return NULL;
2195 if (GameObject *go = GetMap()->GetGameObject(guid))
2197 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2199 float maxdist;
2200 switch(go->GetGoType())
2202 // TODO: find out how the client calculates the maximal usage distance to spellless working
2203 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2204 case GAMEOBJECT_TYPE_GUILD_BANK:
2205 case GAMEOBJECT_TYPE_MAILBOX:
2206 maxdist = 10.0f;
2207 break;
2208 case GAMEOBJECT_TYPE_FISHINGHOLE:
2209 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2210 break;
2211 default:
2212 maxdist = INTERACTION_DISTANCE;
2213 break;
2216 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2217 return go;
2219 sLog.outError("GetGameObjectIfCanInteractWith: 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,
2220 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2223 return NULL;
2226 bool Player::IsUnderWater() const
2228 return IsInWater() &&
2229 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2232 void Player::SetInWater(bool apply)
2234 if(m_isInWater==apply)
2235 return;
2237 //define player in water by opcodes
2238 //move player's guid into HateOfflineList of those mobs
2239 //which can't swim and move guid back into ThreatList when
2240 //on surface.
2241 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2242 m_isInWater = apply;
2244 // remove auras that need water/land
2245 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2247 getHostileRefManager().updateThreatTables();
2250 struct SetGameMasterOnHelper
2252 explicit SetGameMasterOnHelper() {}
2253 void operator()(Unit* unit) const
2255 unit->setFaction(35);
2256 unit->getHostileRefManager().setOnlineOfflineState(false);
2260 struct SetGameMasterOffHelper
2262 explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
2263 void operator()(Unit* unit) const
2265 unit->setFaction(faction);
2266 unit->getHostileRefManager().setOnlineOfflineState(true);
2268 uint32 faction;
2271 void Player::SetGameMaster(bool on)
2273 if(on)
2275 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2276 setFaction(35);
2277 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2279 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2281 SetFFAPvP(false);
2282 ResetContestedPvP();
2284 getHostileRefManager().setOnlineOfflineState(false);
2285 CombatStopWithPets();
2287 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2289 else
2291 // restore phase
2292 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2293 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2295 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2296 setFactionForRace(getRace());
2297 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2299 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2301 // restore FFA PvP Server state
2302 if(sWorld.IsFFAPvPRealm())
2303 SetFFAPvP(true);
2305 // restore FFA PvP area state, remove not allowed for GM mounts
2306 UpdateArea(m_areaUpdateId);
2308 getHostileRefManager().setOnlineOfflineState(true);
2311 UpdateVisibilityForPlayer();
2314 void Player::SetGMVisible(bool on)
2316 if(on)
2318 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2320 // Reapply stealth/invisibility if active or show if not any
2321 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2322 SetVisibility(VISIBILITY_GROUP_STEALTH);
2323 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2324 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2325 else
2326 SetVisibility(VISIBILITY_ON);
2328 else
2330 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2332 SetAcceptWhispers(false);
2333 SetGameMaster(true);
2335 SetVisibility(VISIBILITY_OFF);
2339 bool Player::IsGroupVisibleFor(Player* p) const
2341 switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY))
2343 default: return IsInSameGroupWith(p);
2344 case 1: return IsInSameRaidWith(p);
2345 case 2: return GetTeam()==p->GetTeam();
2349 bool Player::IsInSameGroupWith(Player const* p) const
2351 return (p==this || (GetGroup() != NULL &&
2352 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2355 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2356 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2357 void Player::UninviteFromGroup()
2359 Group* group = GetGroupInvite();
2360 if(!group)
2361 return;
2363 group->RemoveInvite(this);
2365 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2367 if(group->IsCreated())
2369 group->Disband(true);
2370 sObjectMgr.RemoveGroup(group);
2372 else
2373 group->RemoveAllInvites();
2375 delete group;
2379 void Player::RemoveFromGroup(Group* group, uint64 guid)
2381 if(group)
2383 if (group->RemoveMember(guid, 0) <= 1)
2385 // group->Disband(); already disbanded in RemoveMember
2386 sObjectMgr.RemoveGroup(group);
2387 delete group;
2388 // removemember sets the player's group pointer to NULL
2393 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2395 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2396 data << uint64(victim ? victim->GetGUID() : 0); // guid
2397 data << uint32(GivenXP+RestXP); // given experience
2398 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2399 if(victim)
2401 data << uint32(GivenXP); // experience without rested bonus
2402 data << float(1); // 1 - none 0 - 100% group bonus output
2404 data << uint8(0); // new 2.4.0
2405 GetSession()->SendPacket(&data);
2408 void Player::GiveXP(uint32 xp, Unit* victim)
2410 if ( xp < 1 )
2411 return;
2413 if(!isAlive())
2414 return;
2416 uint32 level = getLevel();
2418 // XP to money conversion processed in Player::RewardQuest
2419 if(level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
2420 return;
2422 if(victim)
2424 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2425 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2426 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2427 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2429 else
2431 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2432 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2433 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2434 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2437 // XP resting bonus for kill
2438 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2440 SendLogXPGain(xp,victim,rested_bonus_xp);
2442 uint32 curXP = GetUInt32Value(PLAYER_XP);
2443 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2444 uint32 newXP = curXP + xp + rested_bonus_xp;
2446 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2448 newXP -= nextLvlXP;
2450 if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
2451 GiveLevel(level + 1);
2453 level = getLevel();
2454 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2457 SetUInt32Value(PLAYER_XP, newXP);
2460 // Update player to next level
2461 // Current player experience not update (must be update by caller)
2462 void Player::GiveLevel(uint32 level)
2464 if ( level == getLevel() )
2465 return;
2467 PlayerLevelInfo info;
2468 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2470 PlayerClassLevelInfo classInfo;
2471 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2473 // send levelup info to client
2474 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2475 data << uint32(level);
2476 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2477 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2478 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2479 data << uint32(0);
2480 data << uint32(0);
2481 data << uint32(0);
2482 data << uint32(0);
2483 data << uint32(0);
2484 data << uint32(0);
2485 // end for
2486 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2487 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2489 GetSession()->SendPacket(&data);
2491 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2493 //update level, max level of skills
2494 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2496 _ApplyAllLevelScaleItemMods(false);
2498 SetLevel(level);
2500 UpdateSkillsForLevel ();
2502 // save base values (bonuses already included in stored stats
2503 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2504 SetCreateStat(Stats(i), info.stats[i]);
2506 SetCreateHealth(classInfo.basehealth);
2507 SetCreateMana(classInfo.basemana);
2509 InitTalentForLevel();
2510 InitTaxiNodesForLevel();
2511 InitGlyphsForLevel();
2513 UpdateAllStats();
2515 // set current level health and mana/energy to maximum after applying all mods.
2516 SetHealth(GetMaxHealth());
2517 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2518 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2519 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2520 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2521 SetPower(POWER_FOCUS, 0);
2522 SetPower(POWER_HAPPINESS, 0);
2524 _ApplyAllLevelScaleItemMods(true);
2526 // update level to hunter/summon pet
2527 if (Pet* pet = GetPet())
2528 pet->SynchronizeLevelWithOwner();
2530 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2531 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2533 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2536 void Player::UpdateFreeTalentPoints(bool resetIfNeed)
2538 uint32 level = getLevel();
2539 // talents base at level diff ( talents = level - 9 but some can be used already)
2540 if (level < 10)
2542 // Remove all talent points
2543 if (m_usedTalentCount > 0) // Free any used talents
2545 if (resetIfNeed)
2546 resetTalents(true);
2547 SetFreeTalentPoints(0);
2550 else
2552 uint32 talentPointsForLevel = CalculateTalentsPoints();
2554 // if used more that have then reset
2555 if (m_usedTalentCount > talentPointsForLevel)
2557 if (resetIfNeed && GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2558 resetTalents(true);
2559 else
2560 SetFreeTalentPoints(0);
2562 // else update amount of free points
2563 else
2564 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2568 void Player::InitTalentForLevel()
2570 UpdateFreeTalentPoints();
2572 if (!GetSession()->PlayerLoading())
2573 SendTalentsInfoData(false); // update at client
2576 void Player::InitStatsForLevel(bool reapplyMods)
2578 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2579 _RemoveAllStatBonuses();
2581 PlayerClassLevelInfo classInfo;
2582 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2584 PlayerLevelInfo info;
2585 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2587 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) );
2588 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2590 // reset before any aura state sources (health set/aura apply)
2591 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2593 UpdateSkillsForLevel ();
2595 // set default cast time multiplier
2596 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2598 // reset size before reapply auras
2599 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2601 // save base values (bonuses already included in stored stats
2602 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2603 SetCreateStat(Stats(i), info.stats[i]);
2605 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2606 SetStat(Stats(i), info.stats[i]);
2608 SetCreateHealth(classInfo.basehealth);
2610 //set create powers
2611 SetCreateMana(classInfo.basemana);
2613 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2615 InitStatBuffMods();
2617 //reset rating fields values
2618 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2619 SetUInt32Value(index, 0);
2621 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2622 for (int i = 0; i < 7; ++i)
2624 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2625 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2626 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2629 //reset attack power, damage and attack speed fields
2630 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2631 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2632 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2634 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2635 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2636 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2637 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2638 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2639 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2641 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2642 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2643 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2644 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2645 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2646 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2648 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2649 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2650 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2651 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2653 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2654 for (uint8 i = 0; i < 7; ++i)
2655 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2657 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2658 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2659 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2661 // Dodge percentage
2662 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2664 // set armor (resistance 0) to original value (create_agility*2)
2665 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2666 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2667 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2668 // set other resistance to original value (0)
2669 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2671 SetResistance(SpellSchools(i), 0);
2672 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2673 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2676 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2677 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2678 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2680 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2681 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2683 // Reset no reagent cost field
2684 for(int i = 0; i < 3; ++i)
2685 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2686 // Init data for form but skip reapply item mods for form
2687 InitDataForForm(reapplyMods);
2689 // save new stats
2690 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2691 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2693 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2695 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2696 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2698 // cleanup unit flags (will be re-applied if need at aura load).
2699 RemoveFlag( UNIT_FIELD_FLAGS,
2700 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2701 UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_PASSIVE | UNIT_FLAG_LOOTING |
2702 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2703 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2704 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2705 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2706 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2708 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2710 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2711 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2713 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2714 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2716 // restore if need some important flags
2717 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2719 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2720 _ApplyAllStatBonuses();
2722 // set current level health and mana/energy to maximum after applying all mods.
2723 SetHealth(GetMaxHealth());
2724 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2725 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2726 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2727 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2728 SetPower(POWER_FOCUS, 0);
2729 SetPower(POWER_HAPPINESS, 0);
2730 SetPower(POWER_RUNIC_POWER, 0);
2732 // update level to hunter/summon pet
2733 if (Pet* pet = GetPet())
2734 pet->SynchronizeLevelWithOwner();
2737 void Player::SendInitialSpells()
2739 time_t curTime = time(NULL);
2740 time_t infTime = curTime + infinityCooldownDelayCheck;
2742 uint16 spellCount = 0;
2744 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2745 data << uint8(0);
2747 size_t countPos = data.wpos();
2748 data << uint16(spellCount); // spell count placeholder
2750 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2752 if(itr->second.state == PLAYERSPELL_REMOVED)
2753 continue;
2755 if(!itr->second.active || itr->second.disabled)
2756 continue;
2758 data << uint32(itr->first);
2759 data << uint16(0); // it's not slot id
2761 spellCount +=1;
2764 data.put<uint16>(countPos,spellCount); // write real count value
2766 uint16 spellCooldowns = m_spellCooldowns.size();
2767 data << uint16(spellCooldowns);
2768 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2770 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2771 if(!sEntry)
2772 continue;
2774 data << uint32(itr->first);
2776 data << uint16(itr->second.itemid); // cast item id
2777 data << uint16(sEntry->Category); // spell category
2779 // send infinity cooldown in special format
2780 if(itr->second.end >= infTime)
2782 data << uint32(1); // cooldown
2783 data << uint32(0x80000000); // category cooldown
2784 continue;
2787 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILLISECONDS : 0;
2789 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2791 data << uint32(0); // cooldown
2792 data << uint32(cooldown); // category cooldown
2794 else
2796 data << uint32(cooldown); // cooldown
2797 data << uint32(0); // category cooldown
2801 GetSession()->SendPacket(&data);
2803 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2806 void Player::RemoveMail(uint32 id)
2808 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2810 if ((*itr)->messageID == id)
2812 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2813 m_mail.erase(itr);
2814 return;
2819 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2821 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2822 data << (uint32) mailId;
2823 data << (uint32) mailAction;
2824 data << (uint32) mailError;
2825 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2826 data << (uint32) equipError;
2827 else if( mailAction == MAIL_ITEM_TAKEN )
2829 data << (uint32) item_guid; // item guid low?
2830 data << (uint32) item_count; // item count?
2832 GetSession()->SendPacket(&data);
2835 void Player::SendNewMail()
2837 // deliver undelivered mail
2838 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2839 data << (uint32) 0;
2840 GetSession()->SendPacket(&data);
2843 void Player::UpdateNextMailTimeAndUnreads()
2845 // calculate next delivery time (min. from non-delivered mails
2846 // and recalculate unReadMail
2847 time_t cTime = time(NULL);
2848 m_nextMailDelivereTime = 0;
2849 unReadMails = 0;
2850 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2852 if((*itr)->deliver_time > cTime)
2854 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2855 m_nextMailDelivereTime = (*itr)->deliver_time;
2857 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2858 ++unReadMails;
2862 void Player::AddNewMailDeliverTime(time_t deliver_time)
2864 if(deliver_time <= time(NULL)) // ready now
2866 ++unReadMails;
2867 SendNewMail();
2869 else // not ready and no have ready mails
2871 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2872 m_nextMailDelivereTime = deliver_time;
2876 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2878 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2879 if (!spellInfo)
2881 // do character spell book cleanup (all characters)
2882 if(!IsInWorld() && !learning) // spell load case
2884 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2885 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2887 else
2888 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2890 return false;
2893 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2895 // do character spell book cleanup (all characters)
2896 if(!IsInWorld() && !learning) // spell load case
2898 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2899 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2901 else
2902 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2904 return false;
2907 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2909 bool dependent_set = false;
2910 bool disabled_case = false;
2911 bool superceded_old = false;
2913 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2914 if (itr != m_spells.end())
2916 uint32 next_active_spell_id = 0;
2917 // fix activate state for non-stackable low rank (and find next spell for !active case)
2918 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2920 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2921 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2923 if(HasSpell(next_itr->second))
2925 // high rank already known so this must !active
2926 active = false;
2927 next_active_spell_id = next_itr->second;
2928 break;
2933 // not do anything if already known in expected state
2934 if(itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
2935 itr->second.dependent == dependent && itr->second.disabled == disabled)
2937 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2938 itr->second.state = PLAYERSPELL_UNCHANGED;
2940 return false;
2943 // dependent spell known as not dependent, overwrite state
2944 if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
2946 itr->second.dependent = dependent;
2947 if (itr->second.state != PLAYERSPELL_NEW)
2948 itr->second.state = PLAYERSPELL_CHANGED;
2949 dependent_set = true;
2952 // update active state for known spell
2953 if(itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
2955 itr->second.active = active;
2957 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2958 itr->second.state = PLAYERSPELL_UNCHANGED;
2959 else if(itr->second.state != PLAYERSPELL_NEW)
2960 itr->second.state = PLAYERSPELL_CHANGED;
2962 if(active)
2964 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2965 CastSpell (this, spell_id, true);
2967 else if(IsInWorld())
2969 if(next_active_spell_id)
2971 // update spell ranks in spellbook and action bar
2972 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2973 data << uint32(spell_id);
2974 data << uint32(next_active_spell_id);
2975 GetSession()->SendPacket( &data );
2977 else
2979 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2980 data << uint32(spell_id);
2981 GetSession()->SendPacket(&data);
2985 return active; // learn (show in spell book if active now)
2988 if(itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
2990 if(itr->second.state != PLAYERSPELL_NEW)
2991 itr->second.state = PLAYERSPELL_CHANGED;
2992 itr->second.disabled = disabled;
2994 if(disabled)
2995 return false;
2997 disabled_case = true;
2999 else switch(itr->second.state)
3001 case PLAYERSPELL_UNCHANGED: // known saved spell
3002 return false;
3003 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
3005 m_spells.erase(itr);
3006 state = PLAYERSPELL_CHANGED;
3007 break; // need re-add
3009 default: // known not saved yet spell (new or modified)
3011 // can be in case spell loading but learned at some previous spell loading
3012 if(!IsInWorld() && !learning && !dependent_set)
3013 itr->second.state = PLAYERSPELL_UNCHANGED;
3015 return false;
3020 TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
3022 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
3024 // talent: unlearn all other talent ranks (high and low)
3025 if (talentPos)
3027 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
3029 for(int i=0; i < MAX_TALENT_RANK; ++i)
3031 // skip learning spell and no rank spell case
3032 uint32 rankSpellId = talentInfo->RankID[i];
3033 if(!rankSpellId || rankSpellId == spell_id)
3034 continue;
3036 removeSpell(rankSpellId, false, false);
3040 // non talent spell: learn low ranks (recursive call)
3041 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
3043 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
3044 addSpell(prev_spell, active, true, true, disabled);
3045 else // at normal learning
3046 learnSpell(prev_spell, true);
3049 PlayerSpell newspell;
3050 newspell.state = state;
3051 newspell.active = active;
3052 newspell.dependent = dependent;
3053 newspell.disabled = disabled;
3055 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3056 if(newspell.active && !newspell.disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3058 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3060 if(itr2->second.state == PLAYERSPELL_REMOVED) continue;
3061 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3062 if(!i_spellInfo) continue;
3064 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo, itr2->first) )
3066 if(itr2->second.active)
3068 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3070 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3072 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3073 data << uint32(itr2->first);
3074 data << uint32(spell_id);
3075 GetSession()->SendPacket( &data );
3078 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3079 itr2->second.active = false;
3080 if(itr2->second.state != PLAYERSPELL_NEW)
3081 itr2->second.state = PLAYERSPELL_CHANGED;
3082 superceded_old = true; // new spell replace old in action bars and spell book.
3084 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3086 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3088 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3089 data << uint32(spell_id);
3090 data << uint32(itr2->first);
3091 GetSession()->SendPacket( &data );
3094 // mark new spell as disable (not learned yet for client and will not learned)
3095 newspell.active = false;
3096 if(newspell.state != PLAYERSPELL_NEW)
3097 newspell.state = PLAYERSPELL_CHANGED;
3104 m_spells[spell_id] = newspell;
3106 // return false if spell disabled
3107 if (newspell.disabled)
3108 return false;
3111 if (talentPos)
3113 // update talent map
3114 PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
3115 if (iter != m_talents[m_activeSpec].end())
3117 // check if ranks different or removed
3118 if ((*iter).second.state == PLAYERSPELL_REMOVED || talentPos->rank != (*iter).second.currentRank)
3120 (*iter).second.currentRank = talentPos->rank;
3122 if ((*iter).second.state != PLAYERSPELL_NEW)
3123 (*iter).second.state = PLAYERSPELL_CHANGED;
3126 else
3128 PlayerTalent talent;
3129 talent.currentRank = talentPos->rank;
3130 talent.m_talentEntry = sTalentStore.LookupEntry(talentPos->talent_id);
3131 talent.state = IsInWorld() ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
3132 m_talents[m_activeSpec][talentPos->talent_id] = talent;
3135 // update used talent points count
3136 m_usedTalentCount += GetTalentSpellCost(talentPos);
3137 UpdateFreeTalentPoints(false);
3140 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3141 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3143 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3144 SetFreePrimaryProfessions(freeProfs-1);
3147 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3148 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3149 if (talentPos && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3151 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3152 CastSpell(this, spell_id, true);
3154 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3155 else if (IsPassiveSpell(spell_id))
3157 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3158 CastSpell(this, spell_id, true);
3160 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3162 CastSpell(this, spell_id, true);
3163 return false;
3166 // add dependent skills
3167 uint16 maxskill = GetMaxSkillValueForLevel();
3169 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3171 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3173 if (spellLearnSkill)
3175 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3176 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3178 if (skill_value < spellLearnSkill->value)
3179 skill_value = spellLearnSkill->value;
3181 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3183 if (skill_max_value < new_skill_max_value)
3184 skill_max_value = new_skill_max_value;
3186 SetSkill(spellLearnSkill->skill, spellLearnSkill->step, skill_value, skill_max_value);
3188 else
3190 // not ranked skills
3191 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3193 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3194 if (!pSkill)
3195 continue;
3197 if (HasSkill(pSkill->id))
3198 continue;
3200 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3201 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3202 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3204 switch(GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0))
3206 case SKILL_RANGE_LANGUAGE:
3207 SetSkill(pSkill->id, GetSkillStep(pSkill->id), 300, 300 );
3208 break;
3209 case SKILL_RANGE_LEVEL:
3210 SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, GetMaxSkillValueForLevel() );
3211 break;
3212 case SKILL_RANGE_MONO:
3213 SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, 1 );
3214 break;
3215 default:
3216 break;
3222 // learn dependent spells
3223 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3225 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3227 if (!itr2->second.autoLearned)
3229 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3230 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3231 else // at normal learning
3232 learnSpell(itr2->second.spell, true);
3236 if (!GetSession()->PlayerLoading())
3238 // not ranked skills
3239 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3241 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3242 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3245 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3248 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3249 return active && !disabled && !superceded_old;
3252 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3254 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3255 // talent dependent passives activated at form apply have proper stance data
3256 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3258 //Check CasterAuraStates
3259 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3262 void Player::learnSpell(uint32 spell_id, bool dependent)
3264 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3266 bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
3267 bool active = disabled ? itr->second.active : true;
3269 bool learning = addSpell(spell_id, active, true, dependent, false);
3271 // learn all disabled higher ranks (recursive)
3272 if(disabled)
3274 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3275 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3277 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3278 if (iter != m_spells.end() && iter->second.disabled)
3279 learnSpell(i->second, false);
3283 // prevent duplicated entires in spell book, also not send if not in world (loading)
3284 if(!learning || !IsInWorld ())
3285 return;
3287 WorldPacket data(SMSG_LEARNED_SPELL, 6);
3288 data << uint32(spell_id);
3289 data << uint16(0); // 3.3.3 unk
3290 GetSession()->SendPacket(&data);
3293 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3295 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3296 if (itr == m_spells.end())
3297 return;
3299 if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled))
3300 return;
3302 // unlearn non talent higher ranks (recursive)
3303 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3304 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3305 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3306 removeSpell(itr2->second, disabled, false);
3308 // re-search, it can be corrupted in prev loop
3309 itr = m_spells.find(spell_id);
3310 if (itr == m_spells.end() || itr->second.state == PLAYERSPELL_REMOVED)
3311 return; // already unleared
3313 bool cur_active = itr->second.active;
3314 bool cur_dependent = itr->second.dependent;
3316 if (disabled)
3318 itr->second.disabled = disabled;
3319 if(itr->second.state != PLAYERSPELL_NEW)
3320 itr->second.state = PLAYERSPELL_CHANGED;
3322 else
3324 if(itr->second.state == PLAYERSPELL_NEW)
3325 m_spells.erase(itr);
3326 else
3327 itr->second.state = PLAYERSPELL_REMOVED;
3330 RemoveAurasDueToSpell(spell_id);
3332 // remove pet auras
3333 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
3334 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i)))
3335 RemovePetAura(petSpell);
3337 TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
3338 if (talentPos)
3340 // update talent map
3341 PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
3342 if (iter != m_talents[m_activeSpec].end())
3344 if ((*iter).second.state != PLAYERSPELL_NEW)
3345 (*iter).second.state = PLAYERSPELL_REMOVED;
3346 else
3347 m_talents[m_activeSpec].erase(iter);
3349 else
3350 sLog.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent",GetGUIDLow(), spell_id );
3352 // free talent points
3353 uint32 talentCosts = GetTalentSpellCost(talentPos);
3355 if(talentCosts < m_usedTalentCount)
3356 m_usedTalentCount -= talentCosts;
3357 else
3358 m_usedTalentCount = 0;
3360 UpdateFreeTalentPoints(false);
3363 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3364 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3366 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3367 if(freeProfs <= sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL))
3368 SetFreePrimaryProfessions(freeProfs);
3371 // remove dependent skill
3372 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3373 if(spellLearnSkill)
3375 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3376 if(!prev_spell) // first rank, remove skill
3377 SetSkill(spellLearnSkill->skill, 0, 0, 0);
3378 else
3380 // search prev. skill setting by spell ranks chain
3381 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3382 while(!prevSkill && prev_spell)
3384 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3385 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3388 if (!prevSkill) // not found prev skill setting, remove skill
3389 SetSkill(spellLearnSkill->skill, 0, 0, 0);
3390 else // set to prev. skill setting values
3392 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3393 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3395 if (skill_value > prevSkill->value)
3396 skill_value = prevSkill->value;
3398 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3400 if (skill_max_value > new_skill_max_value)
3401 skill_max_value = new_skill_max_value;
3403 SetSkill(prevSkill->skill, prevSkill->step, skill_value, skill_max_value);
3408 else
3410 // not ranked skills
3411 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3413 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3415 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3416 if (!pSkill)
3417 continue;
3419 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3420 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3421 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3422 ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
3424 // not reset skills for professions and racial abilities
3425 if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) &&
3426 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0))
3427 continue;
3429 SetSkill(pSkill->id, GetSkillStep(pSkill->id), 0, 0);
3434 // remove dependent spells
3435 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3437 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3438 removeSpell(itr2->second.spell, disabled);
3440 // activate lesser rank in spellbook/action bar, and cast it if need
3441 bool prev_activate = false;
3443 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3445 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3447 // if talent then lesser rank also talent and need learn
3448 if (talentPos)
3450 if(learn_low_rank)
3451 learnSpell(prev_id, false);
3453 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3454 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3456 // need manually update dependence state (learn spell ignore like attempts)
3457 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3458 if (prev_itr != m_spells.end())
3460 if (prev_itr->second.dependent != cur_dependent)
3462 prev_itr->second.dependent = cur_dependent;
3463 if (prev_itr->second.state != PLAYERSPELL_NEW)
3464 prev_itr->second.state = PLAYERSPELL_CHANGED;
3467 // now re-learn if need re-activate
3468 if (cur_active && !prev_itr->second.active && learn_low_rank)
3470 if (addSpell(prev_id, true, false, prev_itr->second.dependent, prev_itr->second.disabled))
3472 // downgrade spell ranks in spellbook and action bar
3473 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3474 data << uint32(spell_id);
3475 data << uint32(prev_id);
3476 GetSession()->SendPacket( &data );
3477 prev_activate = true;
3484 if (m_canTitanGrip)
3486 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3487 if (IsSpellHaveEffect(spellInfo, SPELL_EFFECT_TITAN_GRIP))
3489 m_canTitanGrip = false;
3490 if(sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET))
3491 AutoUnequipOffhandIfNeed();
3495 // remove from spell book if not replaced by lesser rank
3496 if (!prev_activate && sendUpdate)
3498 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3499 data << uint32(spell_id);
3500 GetSession()->SendPacket(&data);
3504 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3506 m_spellCooldowns.erase(spell_id);
3508 if(update)
3509 SendClearCooldown(spell_id, this);
3512 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3514 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3515 if (ct == sSpellCategoryStore.end())
3516 return;
3518 const SpellCategorySet& ct_set = ct->second;
3519 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3521 if (ct_set.find(i->first) != ct_set.end())
3522 RemoveSpellCooldown((i++)->first, update);
3523 else
3524 ++i;
3528 void Player::RemoveArenaSpellCooldowns()
3530 // remove cooldowns on spells that has < 15 min CD
3531 SpellCooldowns::iterator itr, next;
3532 // iterate spell cooldowns
3533 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3535 next = itr;
3536 ++next;
3537 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3538 // check if spellentry is present and if the cooldown is less than 15 mins
3539 if( entry &&
3540 entry->RecoveryTime <= 15 * MINUTE * IN_MILLISECONDS &&
3541 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILLISECONDS )
3543 // remove & notify
3544 RemoveSpellCooldown(itr->first, true);
3549 void Player::RemoveAllSpellCooldown()
3551 if(!m_spellCooldowns.empty())
3553 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3554 SendClearCooldown(itr->first, this);
3556 m_spellCooldowns.clear();
3560 void Player::_LoadSpellCooldowns(QueryResult *result)
3562 // some cooldowns can be already set at aura loading...
3564 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3566 if(result)
3568 time_t curTime = time(NULL);
3572 Field *fields = result->Fetch();
3574 uint32 spell_id = fields[0].GetUInt32();
3575 uint32 item_id = fields[1].GetUInt32();
3576 time_t db_time = (time_t)fields[2].GetUInt64();
3578 if(!sSpellStore.LookupEntry(spell_id))
3580 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3581 continue;
3584 // skip outdated cooldown
3585 if(db_time <= curTime)
3586 continue;
3588 AddSpellCooldown(spell_id, item_id, db_time);
3590 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3592 while( result->NextRow() );
3594 delete result;
3598 void Player::_SaveSpellCooldowns()
3600 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3602 time_t curTime = time(NULL);
3603 time_t infTime = curTime + infinityCooldownDelayCheck;
3605 /* copied following sql-code partly from achievementmgr */
3606 bool first_round = true;
3607 std::ostringstream ss;
3609 // remove outdated and save active
3610 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3612 if(itr->second.end <= curTime)
3613 m_spellCooldowns.erase(itr++);
3614 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3616 if (first_round)
3618 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3619 first_round = false;
3621 // next new/changed record prefix
3622 else
3623 ss << ", ";
3624 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3625 ++itr;
3627 else
3628 ++itr;
3631 // if something changed execute
3632 if (!first_round)
3633 CharacterDatabase.Execute( ss.str().c_str() );
3636 uint32 Player::resetTalentsCost() const
3638 // The first time reset costs 1 gold
3639 if(m_resetTalentsCost < 1*GOLD)
3640 return 1*GOLD;
3641 // then 5 gold
3642 else if(m_resetTalentsCost < 5*GOLD)
3643 return 5*GOLD;
3644 // After that it increases in increments of 5 gold
3645 else if(m_resetTalentsCost < 10*GOLD)
3646 return 10*GOLD;
3647 else
3649 time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3650 if(months > 0)
3652 // This cost will be reduced by a rate of 5 gold per month
3653 int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months);
3654 // to a minimum of 10 gold.
3655 return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost);
3657 else
3659 // After that it increases in increments of 5 gold
3660 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3661 // until it hits a cap of 50 gold.
3662 if(new_cost > 50*GOLD)
3663 new_cost = 50*GOLD;
3664 return new_cost;
3669 bool Player::resetTalents(bool no_cost, bool all_specs)
3671 // not need after this call
3672 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS) && all_specs)
3673 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3675 if (m_usedTalentCount == 0 && !all_specs)
3677 UpdateFreeTalentPoints(false); // for fix if need counter
3678 return false;
3681 uint32 cost = 0;
3683 if(!no_cost)
3685 cost = resetTalentsCost();
3687 if (GetMoney() < cost)
3689 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3690 return false;
3694 for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end();)
3696 if (iter->second.state == PLAYERSPELL_REMOVED)
3698 ++iter;
3699 continue;
3702 TalentEntry const *talentInfo = (*iter).second.m_talentEntry;
3703 if (!talentInfo)
3705 m_talents[m_activeSpec].erase(iter++);
3706 continue;
3709 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3711 if (!talentTabInfo)
3713 m_talents[m_activeSpec].erase(iter++);
3714 continue;
3717 // unlearn only talents for character class
3718 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3719 // to prevent unexpected lost normal learned spell skip another class talents
3720 if ((getClassMask() & talentTabInfo->ClassMask) == 0)
3722 ++iter;
3723 continue;
3726 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3727 if (talentInfo->RankID[j])
3728 removeSpell(talentInfo->RankID[j],!IsPassiveSpell(talentInfo->RankID[j]),false);
3730 iter = m_talents[m_activeSpec].begin();
3733 // for not current spec just mark removed all saved to DB case and drop not saved
3734 if (all_specs)
3736 for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec)
3738 if (spec == m_activeSpec)
3739 continue;
3741 for (PlayerTalentMap::iterator iter = m_talents[spec].begin(); iter != m_talents[spec].end();)
3743 switch (iter->second.state)
3745 case PLAYERSPELL_REMOVED:
3746 ++iter;
3747 break;
3748 case PLAYERSPELL_NEW:
3749 m_talents[spec].erase(iter++);
3750 break;
3751 default:
3752 iter->second.state = PLAYERSPELL_REMOVED;
3753 ++iter;
3754 break;
3760 UpdateFreeTalentPoints(false);
3762 if(!no_cost)
3764 ModifyMoney(-(int32)cost);
3765 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3766 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3768 m_resetTalentsCost = cost;
3769 m_resetTalentsTime = time(NULL);
3772 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3773 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3774 /* when prev line will dropped use next line
3775 if(Pet* pet = GetPet())
3777 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3778 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3781 return true;
3784 Mail* Player::GetMail(uint32 id)
3786 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3788 if ((*itr)->messageID == id)
3790 return (*itr);
3793 return NULL;
3796 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3798 if(target == this)
3800 Object::_SetCreateBits(updateMask, target);
3802 else
3804 for(uint16 index = 0; index < m_valuesCount; index++)
3806 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3807 updateMask->SetBit(index);
3812 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3814 if(target == this)
3816 Object::_SetUpdateBits(updateMask, target);
3818 else
3820 Object::_SetUpdateBits(updateMask, target);
3821 *updateMask &= updateVisualBits;
3825 void Player::InitVisibleBits()
3827 updateVisualBits.SetCount(PLAYER_END);
3829 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3830 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3831 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3832 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3833 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3834 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3835 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3836 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3837 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3838 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3839 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3840 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3841 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3842 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3843 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3844 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3845 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3846 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3847 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3848 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3849 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3850 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3851 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3852 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3853 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3854 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3855 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3856 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3857 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3858 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3859 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3860 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3861 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3862 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3863 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3864 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3865 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3866 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3867 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3868 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3869 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3870 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3871 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3872 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3873 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3874 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3875 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3876 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3877 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3878 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3879 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3880 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3881 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3882 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3883 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3885 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3886 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3887 updateVisualBits.SetBit(PLAYER_FLAGS);
3888 updateVisualBits.SetBit(PLAYER_GUILDID);
3889 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3890 updateVisualBits.SetBit(PLAYER_BYTES);
3891 updateVisualBits.SetBit(PLAYER_BYTES_2);
3892 updateVisualBits.SetBit(PLAYER_BYTES_3);
3893 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3894 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3896 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3897 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3898 updateVisualBits.SetBit(i);
3900 // Players visible items are not inventory stuff
3901 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3903 uint32 offset = i * 2;
3905 // item entry
3906 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3907 // enchant
3908 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3911 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3914 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3916 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3918 if(m_items[i] == NULL)
3919 continue;
3921 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3924 if(target == this)
3926 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3928 if(m_items[i] == NULL)
3929 continue;
3931 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3933 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3935 if(m_items[i] == NULL)
3936 continue;
3938 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3942 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3945 void Player::DestroyForPlayer( Player *target, bool anim ) const
3947 Unit::DestroyForPlayer( target, anim );
3949 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3951 if(m_items[i] == NULL)
3952 continue;
3954 m_items[i]->DestroyForPlayer( target );
3957 if(target == this)
3959 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3961 if(m_items[i] == NULL)
3962 continue;
3964 m_items[i]->DestroyForPlayer( target );
3966 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3968 if(m_items[i] == NULL)
3969 continue;
3971 m_items[i]->DestroyForPlayer( target );
3976 bool Player::HasSpell(uint32 spell) const
3978 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3979 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3980 !itr->second.disabled);
3983 bool Player::HasActiveSpell(uint32 spell) const
3985 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3986 return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
3987 itr->second.active && !itr->second.disabled);
3990 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3992 if (!trainer_spell)
3993 return TRAINER_SPELL_RED;
3995 if (!trainer_spell->learnedSpell)
3996 return TRAINER_SPELL_RED;
3998 // known spell
3999 if(HasSpell(trainer_spell->learnedSpell))
4000 return TRAINER_SPELL_GRAY;
4002 // check race/class requirement
4003 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
4004 return TRAINER_SPELL_RED;
4006 // check level requirement
4007 if(getLevel() < trainer_spell->reqLevel)
4008 return TRAINER_SPELL_RED;
4010 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
4012 // check prev.rank requirement
4013 if(spell_chain->prev && !HasSpell(spell_chain->prev))
4014 return TRAINER_SPELL_RED;
4016 // check additional spell requirement
4017 if(spell_chain->req && !HasSpell(spell_chain->req))
4018 return TRAINER_SPELL_RED;
4021 // check skill requirement
4022 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
4023 return TRAINER_SPELL_RED;
4025 // exist, already checked at loading
4026 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
4028 // secondary prof. or not prof. spell
4029 uint32 skill = spell->EffectMiscValue[1];
4031 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
4032 return TRAINER_SPELL_GREEN;
4034 // check primary prof. limit
4035 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
4036 return TRAINER_SPELL_GREEN_DISABLED;
4038 return TRAINER_SPELL_GREEN;
4041 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
4043 uint32 guid = GUID_LOPART(playerguid);
4045 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
4046 // bones will be deleted by corpse/bones deleting thread shortly
4047 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
4049 // remove from guild
4050 uint32 guildId = GetGuildIdFromDB(playerguid);
4051 if(guildId != 0)
4053 Guild* guild = sObjectMgr.GetGuildById(guildId);
4054 if(guild)
4055 guild->DelMember(guid);
4058 // remove from arena teams
4059 LeaveAllArenaTeams(playerguid);
4061 // the player was uninvited already on logout so just remove from group
4062 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid);
4063 if(resultGroup)
4065 uint32 groupId = (*resultGroup)[0].GetUInt32();
4066 delete resultGroup;
4067 if (Group* group = sObjectMgr.GetGroupById(groupId))
4068 RemoveFromGroup(group, playerguid);
4071 // remove signs from petitions (also remove petitions if owner);
4072 RemovePetitionsAndSigns(playerguid, 10);
4074 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
4075 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
4076 if(resultMail)
4080 Field *fields = resultMail->Fetch();
4082 uint32 mail_id = fields[0].GetUInt32();
4083 uint16 mailType = fields[1].GetUInt16();
4084 uint16 mailTemplateId= fields[2].GetUInt16();
4085 uint32 sender = fields[3].GetUInt32();
4086 std::string subject = fields[4].GetCppString();
4087 std::string body = fields[5].GetCppString();
4088 uint32 money = fields[6].GetUInt32();
4089 bool has_items = fields[7].GetBool();
4091 //we can return mail now
4092 //so firstly delete the old one
4093 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
4095 // mail not from player
4096 if (mailType != MAIL_NORMAL)
4098 if(has_items)
4099 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4100 continue;
4103 MailDraft draft(subject, body);
4104 if (mailTemplateId)
4105 draft = MailDraft(mailTemplateId, false); // items already included
4107 if(has_items)
4109 // data needs to be at first place for Item::LoadFromDB
4110 // 0 1 2 3
4111 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,text,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
4112 if(resultItems)
4116 Field *fields2 = resultItems->Fetch();
4118 uint32 item_guidlow = fields2[2].GetUInt32();
4119 uint32 item_template = fields2[3].GetUInt32();
4121 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4122 if(!itemProto)
4124 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4125 continue;
4128 Item *pItem = NewItemOrBag(itemProto);
4129 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4131 pItem->FSetState(ITEM_REMOVED);
4132 pItem->SaveToDB(); // it also deletes item object !
4133 continue;
4136 draft.AddItem(pItem);
4138 while (resultItems->NextRow());
4140 delete resultItems;
4144 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4146 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4148 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4150 while (resultMail->NextRow());
4152 delete resultMail;
4155 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4156 // Get guids of character's pets, will deleted in transaction
4157 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4159 // NOW we can finally clear other DB data related to character
4160 CharacterDatabase.BeginTransaction();
4161 if (resultPets)
4165 Field *fields3 = resultPets->Fetch();
4166 uint32 petguidlow = fields3[0].GetUInt32();
4167 Pet::DeleteFromDB(petguidlow);
4168 } while (resultPets->NextRow());
4169 delete resultPets;
4172 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4173 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4174 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4175 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4176 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4177 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4178 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid);
4179 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4180 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4181 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4182 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4183 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4184 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
4185 CharacterDatabase.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'",guid);
4186 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4187 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4188 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4189 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4190 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'",guid);
4191 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4192 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4193 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4194 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4195 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4196 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4197 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4198 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4199 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4200 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4201 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'",guid, guid);
4202 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4203 CharacterDatabase.CommitTransaction();
4205 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4206 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4209 void Player::SetMovement(PlayerMovementType pType)
4211 WorldPacket data;
4212 switch(pType)
4214 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4215 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4216 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4217 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4218 default:
4219 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4220 return;
4222 data << GetPackGUID();
4223 data << uint32(0);
4224 GetSession()->SendPacket( &data );
4227 /* Preconditions:
4228 - a resurrectable corpse must not be loaded for the player (only bones)
4229 - the player must be in world
4231 void Player::BuildPlayerRepop()
4233 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4234 data << GetPackGUID();
4235 GetSession()->SendPacket(&data);
4237 if(getRace() == RACE_NIGHTELF)
4238 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)
4239 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4241 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4242 // there must be SMSG.STOP_MIRROR_TIMER
4243 // there we must send 888 opcode
4245 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4246 if(GetCorpse())
4248 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4249 ASSERT(false);
4252 // create a corpse and place it at the player's location
4253 Corpse *corpse = CreateCorpse();
4254 if(!corpse)
4256 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4257 return;
4259 GetMap()->Add(corpse);
4261 // convert player body to ghost
4262 SetHealth( 1 );
4264 SetMovement(MOVE_WATER_WALK);
4265 if(!GetSession()->isLogingOut())
4266 SetMovement(MOVE_UNROOT);
4268 // BG - remove insignia related
4269 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4271 SendCorpseReclaimDelay();
4273 // to prevent cheating
4274 corpse->ResetGhostTime();
4276 StopMirrorTimers(); //disable timers(bars)
4278 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4280 // set and clear other
4281 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4284 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4286 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4287 data << uint32(-1);
4288 data << float(0);
4289 data << float(0);
4290 data << float(0);
4291 GetSession()->SendPacket(&data);
4293 // speed change, land walk
4295 // remove death flag + set aura
4296 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4297 if(getRace() == RACE_NIGHTELF)
4298 RemoveAurasDueToSpell(20584); // speed bonuses
4299 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4301 setDeathState(ALIVE);
4303 SetMovement(MOVE_LAND_WALK);
4304 SetMovement(MOVE_UNROOT);
4306 m_deathTimer = 0;
4308 // set health/powers (0- will be set in caller)
4309 if(restore_percent>0.0f)
4311 SetHealth(uint32(GetMaxHealth()*restore_percent));
4312 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4313 SetPower(POWER_RAGE, 0);
4314 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4317 // trigger update zone for alive state zone updates
4318 uint32 newzone, newarea;
4319 GetZoneAndAreaId(newzone,newarea);
4320 UpdateZone(newzone,newarea);
4322 // update visibility
4323 UpdateVisibilityForPlayer();
4325 if(!applySickness)
4326 return;
4328 //Characters from level 1-10 are not affected by resurrection sickness.
4329 //Characters from level 11-19 will suffer from one minute of sickness
4330 //for each level they are above 10.
4331 //Characters level 20 and up suffer from ten minutes of sickness.
4332 int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL);
4334 if(int32(getLevel()) >= startLevel)
4336 // set resurrection sickness
4337 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4339 // not full duration
4340 if(int32(getLevel()) < startLevel+9)
4342 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4344 for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
4346 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,SpellEffectIndex(i)))
4348 Aur->SetAuraDuration(delta*IN_MILLISECONDS);
4349 Aur->SendAuraUpdate(false);
4356 void Player::KillPlayer()
4358 SetMovement(MOVE_ROOT);
4360 StopMirrorTimers(); //disable timers(bars)
4362 setDeathState(CORPSE);
4363 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4365 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4366 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4368 // 6 minutes until repop at graveyard
4369 m_deathTimer = 6*MINUTE*IN_MILLISECONDS;
4371 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4373 // don't create corpse at this moment, player might be falling
4375 // update visibility
4376 UpdateObjectVisibility();
4379 Corpse* Player::CreateCorpse()
4381 // prevent existence 2 corpse for player
4382 SpawnCorpseBones();
4384 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4386 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4387 SetPvPDeath(false);
4389 if (!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4391 delete corpse;
4392 return NULL;
4395 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4396 _pb = GetUInt32Value(PLAYER_BYTES);
4397 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4399 uint8 race = (uint8)(_uf);
4400 uint8 skin = (uint8)(_pb);
4401 uint8 face = (uint8)(_pb >> 8);
4402 uint8 hairstyle = (uint8)(_pb >> 16);
4403 uint8 haircolor = (uint8)(_pb >> 24);
4404 uint8 facialhair = (uint8)(_pb2);
4406 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4407 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4409 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4410 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4412 uint32 flags = CORPSE_FLAG_UNK2;
4413 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4414 flags |= CORPSE_FLAG_HIDE_HELM;
4415 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4416 flags |= CORPSE_FLAG_HIDE_CLOAK;
4417 if (InBattleGround() && !InArena())
4418 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4419 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4421 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4423 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4425 uint32 iDisplayID;
4426 uint32 iIventoryType;
4427 uint32 _cfi;
4428 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4430 if (m_items[i])
4432 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4433 iIventoryType = m_items[i]->GetProto()->InventoryType;
4435 _cfi = iDisplayID | (iIventoryType << 24);
4436 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4440 // we not need saved corpses for BG/arenas
4441 if (!GetMap()->IsBattleGroundOrArena())
4442 corpse->SaveToDB();
4444 // register for player, but not show
4445 sObjectAccessor.AddCorpse(corpse);
4446 return corpse;
4449 void Player::SpawnCorpseBones()
4451 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4452 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4453 SaveToDB(); // prevent loading as ghost without corpse
4456 Corpse* Player::GetCorpse() const
4458 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4461 void Player::DurabilityLossAll(double percent, bool inventory)
4463 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4464 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4465 DurabilityLoss(pItem,percent);
4467 if(inventory)
4469 // bags not have durability
4470 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4472 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4473 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4474 DurabilityLoss(pItem,percent);
4476 // keys not have durability
4477 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4479 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4480 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4481 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4482 if(Item* pItem = GetItemByPos( i, j ))
4483 DurabilityLoss(pItem,percent);
4487 void Player::DurabilityLoss(Item* item, double percent)
4489 if(!item )
4490 return;
4492 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4494 if(!pMaxDurability)
4495 return;
4497 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4499 if(pDurabilityLoss < 1 )
4500 pDurabilityLoss = 1;
4502 DurabilityPointsLoss(item,pDurabilityLoss);
4505 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4507 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4508 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4509 DurabilityPointsLoss(pItem,points);
4511 if(inventory)
4513 // bags not have durability
4514 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4516 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4517 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4518 DurabilityPointsLoss(pItem,points);
4520 // keys not have durability
4521 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4523 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4524 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4525 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4526 if(Item* pItem = GetItemByPos( i, j ))
4527 DurabilityPointsLoss(pItem,points);
4531 void Player::DurabilityPointsLoss(Item* item, int32 points)
4533 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4534 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4535 int32 pNewDurability = pOldDurability - points;
4537 if (pNewDurability < 0)
4538 pNewDurability = 0;
4539 else if (pNewDurability > pMaxDurability)
4540 pNewDurability = pMaxDurability;
4542 if (pOldDurability != pNewDurability)
4544 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4545 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4546 _ApplyItemMods(item,item->GetSlot(), false);
4548 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4550 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4551 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4552 _ApplyItemMods(item,item->GetSlot(), true);
4554 item->SetState(ITEM_CHANGED, this);
4558 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4560 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4561 DurabilityPointsLoss(pItem,1);
4564 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4566 uint32 TotalCost = 0;
4567 // equipped, backpack, bags itself
4568 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4569 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4571 // bank, buyback and keys not repaired
4573 // items in inventory bags
4574 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4575 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4576 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4577 return TotalCost;
4580 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4582 Item* item = GetItemByPos(pos);
4584 uint32 TotalCost = 0;
4585 if(!item)
4586 return TotalCost;
4588 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4589 if(!maxDurability)
4590 return TotalCost;
4592 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4594 if(cost)
4596 uint32 LostDurability = maxDurability - curDurability;
4597 if(LostDurability>0)
4599 ItemPrototype const *ditemProto = item->GetProto();
4601 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4602 if(!dcost)
4604 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4605 return TotalCost;
4608 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4609 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4610 if(!dQualitymodEntry)
4612 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4613 return TotalCost;
4616 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4617 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4619 costs = uint32(costs * discountMod);
4621 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4622 costs = 1;
4624 if (guildBank)
4626 if (GetGuildId()==0)
4628 DEBUG_LOG("You are not member of a guild");
4629 return TotalCost;
4632 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4633 if (!pGuild)
4634 return TotalCost;
4636 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4638 DEBUG_LOG("You do not have rights to withdraw for repairs");
4639 return TotalCost;
4642 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4644 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4645 return TotalCost;
4648 if (pGuild->GetGuildBankMoney() < costs)
4650 DEBUG_LOG("There is not enough money in bank");
4651 return TotalCost;
4654 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4655 TotalCost = costs;
4657 else if (GetMoney() < costs)
4659 DEBUG_LOG("You do not have enough money");
4660 return TotalCost;
4662 else
4663 ModifyMoney( -int32(costs) );
4667 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4668 item->SetState(ITEM_CHANGED, this);
4670 // reapply mods for total broken and repaired item if equipped
4671 if(IsEquipmentPos(pos) && !curDurability)
4672 _ApplyItemMods(item,pos & 255, true);
4673 return TotalCost;
4676 void Player::RepopAtGraveyard()
4678 // note: this can be called also when the player is alive
4679 // for example from WorldSession::HandleMovementOpcodes
4681 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4683 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4684 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4686 ResurrectPlayer(0.5f);
4687 SpawnCorpseBones();
4690 WorldSafeLocsEntry const *ClosestGrave = NULL;
4692 // Special handle for battleground maps
4693 if( BattleGround *bg = GetBattleGround() )
4694 ClosestGrave = bg->GetClosestGraveYard(this);
4695 else
4696 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4698 // stop countdown until repop
4699 m_deathTimer = 0;
4701 // if no grave found, stay at the current location
4702 // and don't show spirit healer location
4703 if(ClosestGrave)
4705 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4706 if(isDead()) // not send if alive, because it used in TeleportTo()
4708 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4709 data << ClosestGrave->map_id;
4710 data << ClosestGrave->x;
4711 data << ClosestGrave->y;
4712 data << ClosestGrave->z;
4713 GetSession()->SendPacket(&data);
4718 void Player::JoinedChannel(Channel *c)
4720 m_channels.push_back(c);
4723 void Player::LeftChannel(Channel *c)
4725 m_channels.remove(c);
4728 void Player::CleanupChannels()
4730 while(!m_channels.empty())
4732 Channel* ch = *m_channels.begin();
4733 m_channels.erase(m_channels.begin()); // remove from player's channel list
4734 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4735 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4736 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4739 sLog.outDebug("Player: channels cleaned up!");
4742 void Player::UpdateLocalChannels(uint32 newZone )
4744 if(m_channels.empty())
4745 return;
4747 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4748 if(!current_zone)
4749 return;
4751 ChannelMgr* cMgr = channelMgr(GetTeam());
4752 if(!cMgr)
4753 return;
4755 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4757 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4759 next = i; ++next;
4761 // skip non built-in channels
4762 if(!(*i)->IsConstant())
4763 continue;
4765 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4766 if(!ch)
4767 continue;
4769 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4770 continue;
4772 // new channel
4773 char new_channel_name_buf[100];
4774 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4775 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4777 if((*i)!=new_channel)
4779 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4781 // leave old channel
4782 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4783 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4784 LeftChannel(*i); // remove from player's channel list
4785 cMgr->LeftChannel(name); // delete if empty
4788 sLog.outDebug("Player: channels cleaned up!");
4791 void Player::LeaveLFGChannel()
4793 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4795 if((*i)->IsLFG())
4797 (*i)->Leave(GetGUID());
4798 break;
4803 void Player::UpdateDefense()
4805 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE);
4807 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4809 // update dependent from defense skill part
4810 UpdateDefenseBonusesMod();
4814 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4816 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4818 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4819 return;
4822 float val = 1.0f;
4824 switch(modType)
4826 case FLAT_MOD:
4827 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4828 break;
4829 case PCT_MOD:
4830 if(amount <= -100.0f)
4831 amount = -200.0f;
4833 val = (100.0f + amount) / 100.0f;
4834 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4835 break;
4838 if(!CanModifyStats())
4839 return;
4841 switch(modGroup)
4843 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4844 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4845 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4846 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4847 default: break;
4851 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4853 if(modGroup >= BASEMOD_END || modType > MOD_END)
4855 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4856 return 0.0f;
4859 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4860 return 0.0f;
4862 return m_auraBaseMod[modGroup][modType];
4865 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4867 if(modGroup >= BASEMOD_END)
4869 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4870 return 0.0f;
4873 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4874 return 0.0f;
4876 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4879 uint32 Player::GetShieldBlockValue() const
4881 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4883 value = (value < 0) ? 0 : value;
4885 return uint32(value);
4888 float Player::GetMeleeCritFromAgility()
4890 uint32 level = getLevel();
4891 uint32 pclass = getClass();
4893 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4895 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4896 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4897 if (critBase==NULL || critRatio==NULL)
4898 return 0.0f;
4900 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4901 return crit*100.0f;
4904 float Player::GetDodgeFromAgility()
4906 // Table for base dodge values
4907 float dodge_base[MAX_CLASSES] = {
4908 0.0075f, // Warrior
4909 0.00652f, // Paladin
4910 -0.0545f, // Hunter
4911 -0.0059f, // Rogue
4912 0.03183f, // Priest
4913 0.0114f, // DK
4914 0.0167f, // Shaman
4915 0.034575f, // Mage
4916 0.02011f, // Warlock
4917 0.0f, // ??
4918 -0.0187f // Druid
4920 // Crit/agility to dodge/agility coefficient multipliers
4921 float crit_to_dodge[MAX_CLASSES] = {
4922 1.1f, // Warrior
4923 1.0f, // Paladin
4924 1.6f, // Hunter
4925 2.0f, // Rogue
4926 1.0f, // Priest
4927 1.0f, // DK?
4928 1.0f, // Shaman
4929 1.0f, // Mage
4930 1.0f, // Warlock
4931 0.0f, // ??
4932 1.7f // Druid
4935 uint32 level = getLevel();
4936 uint32 pclass = getClass();
4938 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4940 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4941 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4942 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4943 return 0.0f;
4945 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4946 return dodge*100.0f;
4949 float Player::GetSpellCritFromIntellect()
4951 uint32 level = getLevel();
4952 uint32 pclass = getClass();
4954 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4956 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4957 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4958 if (critBase==NULL || critRatio==NULL)
4959 return 0.0f;
4961 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4962 return crit*100.0f;
4965 float Player::GetRatingCoefficient(CombatRating cr) const
4967 uint32 level = getLevel();
4969 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4971 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4972 if (Rating == NULL)
4973 return 1.0f; // By default use minimum coefficient (not must be called)
4975 return Rating->ratio;
4978 float Player::GetRatingBonusValue(CombatRating cr) const
4980 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4983 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4985 switch (attType)
4987 case BASE_ATTACK:
4988 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4989 case OFF_ATTACK:
4990 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4991 default:
4992 break;
4994 return 0.0f;
4997 float Player::OCTRegenHPPerSpirit()
4999 uint32 level = getLevel();
5000 uint32 pclass = getClass();
5002 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
5004 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
5005 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
5006 if (baseRatio==NULL || moreRatio==NULL)
5007 return 0.0f;
5009 // Formula from PaperDollFrame script
5010 float spirit = GetStat(STAT_SPIRIT);
5011 float baseSpirit = spirit;
5012 if (baseSpirit>50) baseSpirit = 50;
5013 float moreSpirit = spirit - baseSpirit;
5014 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
5015 return regen;
5018 float Player::OCTRegenMPPerSpirit()
5020 uint32 level = getLevel();
5021 uint32 pclass = getClass();
5023 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
5025 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
5026 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
5027 if (moreRatio==NULL)
5028 return 0.0f;
5030 // Formula get from PaperDollFrame script
5031 float spirit = GetStat(STAT_SPIRIT);
5032 float regen = spirit * moreRatio->ratio;
5033 return regen;
5036 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
5038 m_baseRatingValue[cr]+=(apply ? value : -value);
5040 // explicit affected values
5041 switch (cr)
5043 case CR_HASTE_MELEE:
5045 float RatingChange = value / GetRatingCoefficient(cr);
5046 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
5047 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
5048 break;
5050 case CR_HASTE_RANGED:
5052 float RatingChange = value / GetRatingCoefficient(cr);
5053 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
5054 break;
5056 case CR_HASTE_SPELL:
5058 float RatingChange = value / GetRatingCoefficient(cr);
5059 ApplyCastTimePercentMod(RatingChange,apply);
5060 break;
5064 UpdateRating(cr);
5067 void Player::UpdateRating(CombatRating cr)
5069 int32 amount = m_baseRatingValue[cr];
5070 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
5071 // stat used stored in miscValueB for this aura
5072 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
5073 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
5074 if ((*i)->GetMiscValue() & (1<<cr))
5075 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
5076 if (amount < 0)
5077 amount = 0;
5078 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
5080 bool affectStats = CanModifyStats();
5082 switch (cr)
5084 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
5085 case CR_DEFENSE_SKILL:
5086 UpdateDefenseBonusesMod();
5087 break;
5088 case CR_DODGE:
5089 UpdateDodgePercentage();
5090 break;
5091 case CR_PARRY:
5092 UpdateParryPercentage();
5093 break;
5094 case CR_BLOCK:
5095 UpdateBlockPercentage();
5096 break;
5097 case CR_HIT_MELEE:
5098 UpdateMeleeHitChances();
5099 break;
5100 case CR_HIT_RANGED:
5101 UpdateRangedHitChances();
5102 break;
5103 case CR_HIT_SPELL:
5104 UpdateSpellHitChances();
5105 break;
5106 case CR_CRIT_MELEE:
5107 if(affectStats)
5109 UpdateCritPercentage(BASE_ATTACK);
5110 UpdateCritPercentage(OFF_ATTACK);
5112 break;
5113 case CR_CRIT_RANGED:
5114 if(affectStats)
5115 UpdateCritPercentage(RANGED_ATTACK);
5116 break;
5117 case CR_CRIT_SPELL:
5118 if(affectStats)
5119 UpdateAllSpellCritChances();
5120 break;
5121 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
5122 case CR_HIT_TAKEN_RANGED:
5123 break;
5124 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
5125 break;
5126 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5127 case CR_CRIT_TAKEN_RANGED:
5128 break;
5129 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5130 break;
5131 case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
5132 case CR_HASTE_RANGED:
5133 case CR_HASTE_SPELL:
5134 break;
5135 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5136 case CR_WEAPON_SKILL_OFFHAND:
5137 case CR_WEAPON_SKILL_RANGED:
5138 break;
5139 case CR_EXPERTISE:
5140 if(affectStats)
5142 UpdateExpertise(BASE_ATTACK);
5143 UpdateExpertise(OFF_ATTACK);
5145 break;
5146 case CR_ARMOR_PENETRATION:
5147 if(affectStats)
5148 UpdateArmorPenetration();
5149 break;
5153 void Player::UpdateAllRatings()
5155 for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
5156 UpdateRating(CombatRating(cr));
5159 void Player::SetRegularAttackTime()
5161 for(int i = 0; i < MAX_ATTACK; ++i)
5163 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5164 if (tmpitem)
5166 ItemPrototype const *proto = tmpitem->GetProto();
5167 if(proto->Delay)
5168 SetAttackTime(WeaponAttackType(i), proto->Delay);
5169 else
5170 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5175 //skill+step, checking for max value
5176 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5178 if(!skill_id)
5179 return false;
5181 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5182 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5183 return false;
5185 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5186 uint32 data = GetUInt32Value(valueIndex);
5187 uint32 value = SKILL_VALUE(data);
5188 uint32 max = SKILL_MAX(data);
5190 if ((!max) || (!value) || (value >= max))
5191 return false;
5193 if (value*512 < max*urand(0,512))
5195 uint32 new_value = value+step;
5196 if(new_value > max)
5197 new_value = max;
5199 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5200 if(itr->second.uState != SKILL_NEW)
5201 itr->second.uState = SKILL_CHANGED;
5202 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5203 return true;
5206 return false;
5209 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5211 if ( SkillValue >= GrayLevel )
5212 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10;
5213 if ( SkillValue >= GreenLevel )
5214 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10;
5215 if ( SkillValue >= YellowLevel )
5216 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10;
5217 return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10;
5220 bool Player::UpdateCraftSkill(uint32 spellid)
5222 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5224 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5226 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5228 if (_spell_idx->second->skillId)
5230 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5232 // Alchemy Discoveries here
5233 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5234 if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
5236 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5237 learnSpell(discoveredSpell, false);
5240 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING);
5242 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5243 _spell_idx->second->max_value,
5244 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5245 _spell_idx->second->min_value),
5246 craft_skill_gain);
5249 return false;
5252 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5254 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5256 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5258 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5259 switch (SkillId)
5261 case SKILL_HERBALISM:
5262 case SKILL_LOCKPICKING:
5263 case SKILL_JEWELCRAFTING:
5264 case SKILL_INSCRIPTION:
5265 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5266 case SKILL_SKINNING:
5267 if( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0)
5268 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5269 else
5270 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5271 case SKILL_MINING:
5272 if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0)
5273 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5274 else
5275 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5277 return false;
5280 bool Player::UpdateFishingSkill()
5282 sLog.outDebug("UpdateFishingSkill");
5284 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5286 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5288 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
5290 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5293 // levels sync. with spell requirement for skill levels to learn
5294 // bonus abilities in sSkillLineAbilityStore
5295 // Used only to avoid scan DBC at each skill grow
5296 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5298 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5300 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5301 if ( !SkillId )
5302 return false;
5304 if(Chance <= 0) // speedup in 0 chance case
5306 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5307 return false;
5310 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5311 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5312 return false;
5314 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5316 uint32 data = GetUInt32Value(valueIndex);
5317 uint16 SkillValue = SKILL_VALUE(data);
5318 uint16 MaxValue = SKILL_MAX(data);
5320 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5321 return false;
5323 int32 Roll = irand(1,1000);
5325 if ( Roll <= Chance )
5327 uint32 new_value = SkillValue+step;
5328 if(new_value > MaxValue)
5329 new_value = MaxValue;
5331 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5332 if(itr->second.uState != SKILL_NEW)
5333 itr->second.uState = SKILL_CHANGED;
5334 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5336 if((SkillValue < *bsl && new_value >= *bsl))
5338 learnSkillRewardedSpells( SkillId, new_value);
5339 break;
5342 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5343 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5344 return true;
5347 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5348 return false;
5351 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5353 // no skill gain in pvp
5354 Unit *pVictim = getVictim();
5355 if(pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
5356 return;
5358 if(IsInFeralForm())
5359 return; // always maximized SKILL_FERAL_COMBAT in fact
5361 if(m_form == FORM_TREE)
5362 return; // use weapon but not skill up
5364 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON);
5366 switch(attType)
5368 case BASE_ATTACK:
5370 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5372 if (!tmpitem)
5373 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5374 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5375 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5376 break;
5378 case OFF_ATTACK:
5379 case RANGED_ATTACK:
5381 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5382 if (tmpitem)
5383 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5384 break;
5387 UpdateAllCritPercentages();
5390 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5392 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5393 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5394 uint32 moblevel = pVictim->getLevelForTarget(this);
5395 if(moblevel < greylevel)
5396 return;
5398 if (moblevel > plevel + 5)
5399 moblevel = plevel + 5;
5401 uint32 lvldif = moblevel - greylevel;
5402 if(lvldif < 3)
5403 lvldif = 3;
5405 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5406 if(skilldif <= 0)
5407 return;
5409 float chance = float(3 * lvldif * skilldif) / plevel;
5410 if(!defence)
5412 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5413 chance *= 0.1f * GetStat(STAT_INTELLECT);
5416 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5418 if(roll_chance_f(chance))
5420 if(defence)
5421 UpdateDefense();
5422 else
5423 UpdateWeaponSkill(attType);
5425 else
5426 return;
5429 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5431 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5432 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5433 return;
5435 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5437 uint32 bonus_val = GetUInt32Value(bonusIndex);
5438 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5439 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5441 if(talent) // permanent bonus stored in high part
5442 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5443 else // temporary/item bonus stored in low part
5444 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5447 void Player::UpdateSkillsForLevel()
5449 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5450 uint32 maxSkill = GetMaxSkillValueForLevel();
5452 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL);
5454 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5456 if(itr->second.uState == SKILL_DELETED)
5457 continue;
5459 uint32 pskill = itr->first;
5461 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5462 if(!pSkill)
5463 continue;
5465 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5466 continue;
5468 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5469 uint32 data = GetUInt32Value(valueIndex);
5470 uint32 max = SKILL_MAX(data);
5471 uint32 val = SKILL_VALUE(data);
5473 /// update only level dependent max skill values
5474 if(max!=1)
5476 /// maximize skill always
5477 if(alwaysMaxSkill)
5479 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5480 if(itr->second.uState != SKILL_NEW)
5481 itr->second.uState = SKILL_CHANGED;
5483 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5485 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5486 if(itr->second.uState != SKILL_NEW)
5487 itr->second.uState = SKILL_CHANGED;
5493 void Player::UpdateSkillsToMaxSkillsForLevel()
5495 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5497 if(itr->second.uState == SKILL_DELETED)
5498 continue;
5500 uint32 pskill = itr->first;
5501 if( IsProfessionOrRidingSkill(pskill))
5502 continue;
5503 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5504 uint32 data = GetUInt32Value(valueIndex);
5506 uint32 max = SKILL_MAX(data);
5508 if(max > 1)
5510 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5511 if(itr->second.uState != SKILL_NEW)
5512 itr->second.uState = SKILL_CHANGED;
5515 if(pskill == SKILL_DEFENSE)
5516 UpdateDefenseBonusesMod();
5520 // This functions sets a skill line value (and adds if doesn't exist yet)
5521 // To "remove" a skill line, set it's values to zero
5522 void Player::SetSkill(uint16 id, uint16 step, uint16 currVal, uint16 maxVal)
5524 if(!id)
5525 return;
5527 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5529 // has skill
5530 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5532 if(currVal)
5534 // update step
5535 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), MAKE_PAIR32(id, step));
5536 // update value
5537 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_SKILL_VALUE(currVal, maxVal));
5538 if(itr->second.uState != SKILL_NEW)
5539 itr->second.uState = SKILL_CHANGED;
5540 learnSkillRewardedSpells(id, currVal);
5541 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
5542 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
5544 else //remove
5546 // clear skill fields
5547 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), 0);
5548 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), 0);
5549 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos), 0);
5551 // mark as deleted or simply remove from map if not saved yet
5552 if(itr->second.uState != SKILL_NEW)
5553 itr->second.uState = SKILL_DELETED;
5554 else
5555 mSkillStatus.erase(itr);
5557 // remove all spells that related to this skill
5558 for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
5559 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5560 if (pAbility->skillId == id)
5561 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5564 else if(currVal) // add
5566 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5568 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5570 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5571 if(!pSkill)
5573 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5574 return;
5577 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step));
5578 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal, maxVal));
5579 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
5580 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
5582 // insert new entry or update if not deleted old entry yet
5583 if(itr != mSkillStatus.end())
5585 itr->second.pos = i;
5586 itr->second.uState = SKILL_CHANGED;
5588 else
5589 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5591 // apply skill bonuses
5592 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0);
5594 // temporary bonuses
5595 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5596 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5597 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5598 (*j)->ApplyModifier(true);
5600 // permanent bonuses
5601 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5602 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5603 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5604 (*j)->ApplyModifier(true);
5606 // Learn all spells for skill
5607 learnSkillRewardedSpells(id, currVal);
5608 return;
5614 bool Player::HasSkill(uint32 skill) const
5616 if(!skill)
5617 return false;
5619 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5620 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5623 uint16 Player::GetSkillStep(uint16 skill) const
5625 if(!skill)
5626 return 0;
5628 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5629 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5630 return 0;
5632 return PAIR32_HIPART(GetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos)));
5635 uint16 Player::GetSkillValue(uint32 skill) const
5637 if(!skill)
5638 return 0;
5640 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5641 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5642 return 0;
5644 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5646 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5647 result += SKILL_TEMP_BONUS(bonus);
5648 result += SKILL_PERM_BONUS(bonus);
5649 return result < 0 ? 0 : result;
5652 uint16 Player::GetMaxSkillValue(uint32 skill) const
5654 if(!skill)
5655 return 0;
5657 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5658 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5659 return 0;
5661 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5663 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5664 result += SKILL_TEMP_BONUS(bonus);
5665 result += SKILL_PERM_BONUS(bonus);
5666 return result < 0 ? 0 : result;
5669 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5671 if(!skill)
5672 return 0;
5674 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5675 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5676 return 0;
5678 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5681 uint16 Player::GetBaseSkillValue(uint32 skill) const
5683 if(!skill)
5684 return 0;
5686 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5687 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5688 return 0;
5690 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5691 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5692 return result < 0 ? 0 : result;
5695 uint16 Player::GetPureSkillValue(uint32 skill) const
5697 if(!skill)
5698 return 0;
5700 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5701 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5702 return 0;
5704 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5707 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5709 if(!skill)
5710 return 0;
5712 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5713 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5714 return 0;
5716 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5719 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5721 if(!skill)
5722 return 0;
5724 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5725 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5726 return 0;
5728 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5731 void Player::SendInitialActionButtons() const
5733 sLog.outDetail( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
5735 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5736 data << uint8(1); // talent spec amount (in packet)
5737 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
5738 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
5740 ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
5741 if(itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5742 data << uint32(itr->second.packedData);
5743 else
5744 data << uint32(0);
5747 GetSession()->SendPacket( &data );
5748 sLog.outDetail( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec );
5751 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg)
5753 if(button >= MAX_ACTION_BUTTONS)
5755 if (msg)
5757 if (player)
5758 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5759 else
5760 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5763 return false;
5766 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5768 if (msg)
5770 if (player)
5771 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5772 else
5773 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5775 return false;
5778 switch(type)
5780 case ACTION_BUTTON_SPELL:
5781 if(!sSpellStore.LookupEntry(action))
5783 if (msg)
5785 if (player)
5786 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5787 else
5788 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5790 return false;
5793 if(player && !player->HasSpell(action))
5795 if (msg)
5796 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5797 return false;
5799 break;
5800 case ACTION_BUTTON_ITEM:
5801 if(!ObjectMgr::GetItemPrototype(action))
5803 if (msg)
5805 if (player)
5806 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5807 else
5808 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5810 return false;
5812 break;
5813 default:
5814 break; // other cases not checked at this moment
5817 return true;
5820 ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
5822 // check action only for active spec (so not check at copy/load passive spec)
5823 if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
5824 return NULL;
5826 // it create new button (NEW state) if need or return existed
5827 ActionButton& ab = m_actionButtons[spec][button];
5829 // set data and update to CHANGED if not NEW
5830 ab.SetActionAndType(action,ActionButtonType(type));
5832 sLog.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
5833 return &ab;
5836 void Player::removeActionButton(uint8 spec, uint8 button)
5838 ActionButtonList& currentActionButtonList = m_actionButtons[spec];
5839 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5840 if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5841 return;
5843 if (buttonItr->second.uState == ACTIONBUTTON_NEW)
5844 currentActionButtonList.erase(buttonItr); // new and not saved
5845 else
5846 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5848 sLog.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
5851 ActionButton const* Player::GetActionButton(uint8 button)
5853 ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
5854 ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
5855 if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5856 return NULL;
5858 return &buttonItr->second;
5861 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5863 // prevent crash when a bad coord is sent by the client
5864 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5866 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5867 return false;
5870 Map *m = GetMap();
5872 const float old_x = GetPositionX();
5873 const float old_y = GetPositionY();
5874 const float old_z = GetPositionZ();
5875 const float old_r = GetOrientation();
5877 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5879 if (teleport || old_x != x || old_y != y || old_z != z)
5880 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5881 else
5882 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5884 // move and update visible state if need
5885 m->PlayerRelocation(this, x, y, z, orientation);
5887 // reread after Map::Relocation
5888 m = GetMap();
5889 x = GetPositionX();
5890 y = GetPositionY();
5891 z = GetPositionZ();
5893 // group update
5894 if(GetGroup() && (old_x != x || old_y != y))
5895 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5898 // code block for underwater state update
5899 UpdateUnderwaterState(m, x, y, z);
5901 CheckExploreSystem();
5903 return true;
5906 void Player::SaveRecallPosition()
5908 m_recallMap = GetMapId();
5909 m_recallX = GetPositionX();
5910 m_recallY = GetPositionY();
5911 m_recallZ = GetPositionZ();
5912 m_recallO = GetOrientation();
5915 void Player::SendMessageToSet(WorldPacket *data, bool self)
5917 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5918 if(_map)
5920 _map->MessageBroadcast(this, data, self);
5921 return;
5924 //if player is not in world and map in not created/already destroyed
5925 //no need to create one, just send packet for itself!
5926 if(self)
5927 GetSession()->SendPacket(data);
5930 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5932 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5933 if(_map)
5935 _map->MessageDistBroadcast(this, data, dist, self);
5936 return;
5939 if(self)
5940 GetSession()->SendPacket(data);
5943 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5945 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5946 if(_map)
5948 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5949 return;
5952 if(self)
5953 GetSession()->SendPacket(data);
5956 void Player::SendDirectMessage(WorldPacket *data)
5958 GetSession()->SendPacket(data);
5961 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5963 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5964 data << uint32(CinematicSequenceId);
5965 SendDirectMessage(&data);
5968 void Player::SendMovieStart(uint32 MovieId)
5970 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5971 data << uint32(MovieId);
5972 SendDirectMessage(&data);
5975 void Player::CheckExploreSystem()
5977 if (!isAlive())
5978 return;
5980 if (isInFlight())
5981 return;
5983 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5984 if(areaFlag==0xffff)
5985 return;
5986 int offset = areaFlag / 32;
5988 if(offset >= PLAYER_EXPLORED_ZONES_SIZE)
5990 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 < %u ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset, PLAYER_EXPLORED_ZONES_SIZE);
5991 return;
5994 uint32 val = (uint32)(1 << (areaFlag % 32));
5995 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5997 if( !(currFields & val) )
5999 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
6001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
6003 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
6004 if(!p)
6006 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
6008 else if(p->area_level > 0)
6010 uint32 area = p->ID;
6011 if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
6013 SendExplorationExperience(area,0);
6015 else
6017 int32 diff = int32(getLevel()) - p->area_level;
6018 uint32 XP = 0;
6019 if (diff < -5)
6021 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
6023 else if (diff > 5)
6025 int32 exploration_percent = (100-((diff-5)*5));
6026 if (exploration_percent > 100)
6027 exploration_percent = 100;
6028 else if (exploration_percent < 0)
6029 exploration_percent = 0;
6031 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
6033 else
6035 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
6038 GiveXP( XP, NULL );
6039 SendExplorationExperience(area,XP);
6041 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
6046 uint32 Player::TeamForRace(uint8 race)
6048 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
6049 if(!rEntry)
6051 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
6052 return ALLIANCE;
6055 switch(rEntry->TeamID)
6057 case 7: return ALLIANCE;
6058 case 1: return HORDE;
6061 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
6062 return ALLIANCE;
6065 uint32 Player::getFactionForRace(uint8 race)
6067 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
6068 if(!rEntry)
6070 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
6071 return 0;
6074 return rEntry->FactionID;
6077 void Player::setFactionForRace(uint8 race)
6079 m_team = TeamForRace(race);
6080 setFaction( getFactionForRace(race) );
6083 ReputationRank Player::GetReputationRank(uint32 faction) const
6085 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
6086 return GetReputationMgr().GetRank(factionEntry);
6089 //Calculate total reputation percent player gain with quest/creature level
6090 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
6092 float percent = 100.0f;
6094 float rate = for_quest ? sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL);
6096 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
6097 percent *= rate;
6099 float repMod = (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
6101 if (!for_quest)
6102 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
6104 percent += rep > 0 ? repMod : -repMod;
6106 if (percent <= 0.0f)
6107 return 0;
6109 return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f);
6112 //Calculates how many reputation points player gains in victim's enemy factions
6113 void Player::RewardReputation(Unit *pVictim, float rate)
6115 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
6116 return;
6118 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
6120 if(!Rep)
6121 return;
6123 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6125 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
6126 donerep1 = int32(donerep1*rate);
6127 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6128 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
6129 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6130 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
6132 // Wiki: Team factions value divided by 2
6133 if (factionEntry1 && Rep->is_teamaward1)
6135 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6136 if(team1_factionEntry)
6137 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
6141 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6143 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
6144 donerep2 = int32(donerep2*rate);
6145 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6146 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
6147 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6148 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
6150 // Wiki: Team factions value divided by 2
6151 if (factionEntry2 && Rep->is_teamaward2)
6153 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6154 if(team2_factionEntry)
6155 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
6160 //Calculate how many reputation points player gain with the quest
6161 void Player::RewardReputation(Quest const *pQuest)
6163 // quest reputation reward/loss
6164 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6166 if (!pQuest->RewRepFaction[i])
6167 continue;
6169 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6170 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6171 if (pQuest->RewRepValue[i])
6173 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6175 if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6176 GetReputationMgr().ModifyReputation(factionEntry, rep);
6178 else
6180 uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
6181 uint32 field = abs(pQuest->RewRepValueId[i]);
6183 if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
6185 int32 repPoints = pRow->rewardValue[field];
6187 if (!repPoints)
6188 continue;
6190 repPoints = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), repPoints, pQuest->RewRepFaction[i], true);
6192 if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
6193 GetReputationMgr().ModifyReputation(factionEntry, repPoints);
6198 // TODO: implement reputation spillover
6201 void Player::UpdateArenaFields(void)
6203 /* arena calcs go here */
6206 void Player::UpdateHonorFields()
6208 /// called when rewarding honor and at each save
6209 time_t now = time(NULL);
6210 time_t today = (time(NULL) / DAY) * DAY;
6212 if(m_lastHonorUpdateTime < today)
6214 time_t yesterday = today - DAY;
6216 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6218 // update yesterday's contribution
6219 if(m_lastHonorUpdateTime >= yesterday )
6221 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6223 // this is the first update today, reset today's contribution
6224 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6225 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6227 else
6229 // no honor/kills yesterday or today, reset
6230 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6231 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6235 m_lastHonorUpdateTime = now;
6238 ///Calculate the amount of honor gained based on the victim
6239 ///and the size of the group for which the honor is divided
6240 ///An exact honor value can also be given (overriding the calcs)
6241 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6243 // do not reward honor in arenas, but enable onkill spellproc
6244 if(InArena())
6246 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6247 return false;
6249 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6250 return false;
6252 return true;
6255 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6256 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6257 return false;
6259 uint64 victim_guid = 0;
6260 uint32 victim_rank = 0;
6262 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6263 UpdateHonorFields();
6265 if(honor <= 0)
6267 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6268 return false;
6270 victim_guid = uVictim->GetGUID();
6272 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6274 Player *pVictim = (Player *)uVictim;
6276 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6277 return false;
6279 float f = 1; //need for total kills (?? need more info)
6280 uint32 k_grey = 0;
6281 uint32 k_level = getLevel();
6282 uint32 v_level = pVictim->getLevel();
6285 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6286 // [0] Just name
6287 // [1..14] Alliance honor titles and player name
6288 // [15..28] Horde honor titles and player name
6289 // [29..38] Other title and player name
6290 // [39+] Nothing
6291 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6292 // Get Killer titles, CharTitlesEntry::bit_index
6293 // Ranks:
6294 // title[1..14] -> rank[5..18]
6295 // title[15..28] -> rank[5..18]
6296 // title[other] -> 0
6297 if (victim_title == 0)
6298 victim_guid = 0; // Don't show HK: <rank> message, only log.
6299 else if (victim_title < 15)
6300 victim_rank = victim_title + 4;
6301 else if (victim_title < 29)
6302 victim_rank = victim_title - 14 + 4;
6303 else
6304 victim_guid = 0; // Don't show HK: <rank> message, only log.
6307 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6309 if(v_level<=k_grey)
6310 return false;
6312 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6314 int32 v_rank =1; //need more info
6316 honor = ((f * diff_level * (190 + v_rank*10))/6);
6317 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6319 // count the number of playerkills in one day
6320 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6321 // and those in a lifetime
6322 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6323 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6324 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6325 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6327 else
6329 Creature *cVictim = (Creature *)uVictim;
6331 if (!cVictim->isRacialLeader())
6332 return false;
6334 honor = 100; // ??? need more info
6335 victim_rank = 19; // HK: Leader
6339 if (uVictim != NULL)
6341 honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR);
6342 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6344 if(groupsize > 1)
6345 honor /= groupsize;
6347 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6350 // honor - for show honor points in log
6351 // victim_guid - for show victim name in log
6352 // victim_rank [1..4] HK: <dishonored rank>
6353 // victim_rank [5..19] HK: <alliance\horde rank>
6354 // victim_rank [0,20+] HK: <>
6355 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6356 data << (uint32) honor;
6357 data << (uint64) victim_guid;
6358 data << (uint32) victim_rank;
6360 GetSession()->SendPacket(&data);
6362 // add honor points
6363 ModifyHonorPoints(int32(honor));
6365 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6366 return true;
6369 void Player::ModifyHonorPoints( int32 value )
6371 if(value < 0)
6373 if (GetHonorPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
6374 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) + value);
6375 else
6376 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6378 else
6379 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS));
6382 void Player::ModifyArenaPoints( int32 value )
6384 if(value < 0)
6386 if (GetArenaPoints() > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
6387 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) + value);
6388 else
6389 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6391 else
6392 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS));
6395 uint32 Player::GetGuildIdFromDB(uint64 guid)
6397 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6398 if(!result)
6399 return 0;
6401 uint32 id = result->Fetch()[0].GetUInt32();
6402 delete result;
6403 return id;
6406 uint32 Player::GetRankFromDB(uint64 guid)
6408 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6409 if( result )
6411 uint32 v = result->Fetch()[0].GetUInt32();
6412 delete result;
6413 return v;
6415 else
6416 return 0;
6419 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6421 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);
6422 if(!result)
6423 return 0;
6425 uint32 id = (*result)[0].GetUInt32();
6426 delete result;
6427 return id;
6430 uint32 Player::GetZoneIdFromDB(uint64 guid)
6432 uint32 guidLow = GUID_LOPART(guid);
6433 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6434 if (!result)
6435 return 0;
6436 Field* fields = result->Fetch();
6437 uint32 zone = fields[0].GetUInt32();
6438 delete result;
6440 if (!zone)
6442 // stored zone is zero, use generic and slow zone detection
6443 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6444 if( !result )
6445 return 0;
6446 fields = result->Fetch();
6447 uint32 map = fields[0].GetUInt32();
6448 float posx = fields[1].GetFloat();
6449 float posy = fields[2].GetFloat();
6450 float posz = fields[3].GetFloat();
6451 delete result;
6453 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6455 if (zone > 0)
6456 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6459 return zone;
6462 uint32 Player::GetLevelFromDB(uint64 guid)
6464 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6465 if (!result)
6466 return 0;
6468 Field* fields = result->Fetch();
6469 uint32 level = fields[0].GetUInt32();
6470 delete result;
6472 return level;
6475 void Player::UpdateArea(uint32 newArea)
6477 // FFA_PVP flags are area and not zone id dependent
6478 // so apply them accordingly
6479 m_areaUpdateId = newArea;
6481 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6483 if(area && (area->flags & AREA_FLAG_ARENA))
6485 if(!isGameMaster())
6486 SetFFAPvP(true);
6488 else
6490 // remove ffa flag only if not ffapvp realm
6491 // removal in sanctuaries and capitals is handled in zone update
6492 if(IsFFAPvP() && !sWorld.IsFFAPvPRealm())
6493 SetFFAPvP(false);
6496 UpdateAreaDependentAuras(newArea);
6499 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6501 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6502 if(!zone)
6503 return;
6505 if(m_zoneUpdateId != newZone)
6507 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6509 if (sWorld.getConfig(CONFIG_BOOL_WEATHER))
6511 if(Weather *wth = sWorld.FindWeather(zone->ID))
6512 wth->SendWeatherUpdateToPlayer(this);
6513 else if(!sWorld.AddWeather(zone->ID))
6515 // send fine weather packet to remove old zone's weather
6516 Weather::SendFineWeatherUpdateToPlayer(this);
6521 m_zoneUpdateId = newZone;
6522 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6524 // zone changed, so area changed as well, update it
6525 UpdateArea(newArea);
6527 // in PvP, any not controlled zone (except zone->team == 6, default case)
6528 // in PvE, only opposition team capital
6529 switch(zone->team)
6531 case AREATEAM_ALLY:
6532 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6533 break;
6534 case AREATEAM_HORDE:
6535 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6536 break;
6537 case AREATEAM_NONE:
6538 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6539 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6540 break;
6541 default: // 6 in fact
6542 pvpInfo.inHostileArea = false;
6543 break;
6546 if(pvpInfo.inHostileArea) // in hostile area
6548 if(!IsPvP() || pvpInfo.endTimer != 0)
6549 UpdatePvP(true, true);
6551 else // in friendly area
6553 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6554 pvpInfo.endTimer = time(0); // start toggle-off
6557 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6559 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6560 if(sWorld.IsFFAPvPRealm())
6561 SetFFAPvP(false);
6563 else
6565 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6568 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6569 SetRestType(REST_TYPE_IN_CITY);
6570 else // anywhere else
6572 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6574 if (GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6576 AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(inn_trigger_id);
6577 if (!at || !IsPointInAreaTriggerZone(at, GetMapId(), GetPositionX(), GetPositionY(), GetPositionY()))
6578 SetRestType(REST_TYPE_NO);
6580 else // not in tavern (leave city then)
6581 SetRestType(REST_TYPE_NO);
6585 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6586 // if player resurrected at teleport this will be applied in resurrect code
6587 if(isAlive())
6588 DestroyZoneLimitedItem( true, newZone );
6590 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6591 AutoUnequipOffhandIfNeed();
6593 // recent client version not send leave/join channel packets for built-in local channels
6594 UpdateLocalChannels( newZone );
6596 // group update
6597 if(GetGroup())
6598 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6600 UpdateZoneDependentAuras(newZone);
6603 //If players are too far way of duel flag... then player loose the duel
6604 void Player::CheckDuelDistance(time_t currTime)
6606 if(!duel)
6607 return;
6609 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6610 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6611 if(!obj)
6612 return;
6614 if(duel->outOfBound == 0)
6616 if(!IsWithinDistInMap(obj, 50))
6618 duel->outOfBound = currTime;
6620 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6621 GetSession()->SendPacket(&data);
6624 else
6626 if(IsWithinDistInMap(obj, 40))
6628 duel->outOfBound = 0;
6630 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6631 GetSession()->SendPacket(&data);
6633 else if(currTime >= (duel->outOfBound+10))
6635 DuelComplete(DUEL_FLED);
6640 void Player::DuelComplete(DuelCompleteType type)
6642 // duel not requested
6643 if(!duel)
6644 return;
6646 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6647 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6648 GetSession()->SendPacket(&data);
6649 duel->opponent->GetSession()->SendPacket(&data);
6651 if(type != DUEL_INTERUPTED)
6653 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6654 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6655 data << duel->opponent->GetName();
6656 data << GetName();
6657 SendMessageToSet(&data,true);
6660 if (type == DUEL_WON)
6662 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6663 if (duel->opponent)
6664 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6667 //Remove Duel Flag object
6668 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6669 if(obj)
6670 duel->initiator->RemoveGameObject(obj,true);
6672 /* remove auras */
6673 std::vector<uint32> auras2remove;
6674 AuraMap const& vAuras = duel->opponent->GetAuras();
6675 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6677 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6678 auras2remove.push_back(i->second->GetId());
6681 for(size_t i=0; i<auras2remove.size(); ++i)
6682 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6684 auras2remove.clear();
6685 AuraMap const& auras = GetAuras();
6686 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6688 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6689 auras2remove.push_back(i->second->GetId());
6691 for(size_t i=0; i<auras2remove.size(); ++i)
6692 RemoveAurasDueToSpell(auras2remove[i]);
6694 // cleanup combo points
6695 if(GetComboTarget()==duel->opponent->GetGUID())
6696 ClearComboPoints();
6697 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6698 ClearComboPoints();
6700 if(duel->opponent->GetComboTarget()==GetGUID())
6701 duel->opponent->ClearComboPoints();
6702 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6703 duel->opponent->ClearComboPoints();
6705 //cleanups
6706 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6707 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6708 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6709 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6711 delete duel->opponent->duel;
6712 duel->opponent->duel = NULL;
6713 delete duel;
6714 duel = NULL;
6717 //---------------------------------------------------------//
6719 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6721 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6722 return;
6724 // not apply/remove mods for broken item
6725 if(item->IsBroken())
6726 return;
6728 ItemPrototype const *proto = item->GetProto();
6730 if(!proto)
6731 return;
6733 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6735 uint32 attacktype = Player::GetAttackBySlot(slot);
6736 if(attacktype < MAX_ATTACK)
6737 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6739 _ApplyItemBonuses(proto,slot,apply);
6741 if( slot==EQUIPMENT_SLOT_RANGED )
6742 _ApplyAmmoBonuses();
6744 ApplyItemEquipSpell(item,apply);
6745 ApplyEnchantment(item, apply);
6747 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6748 CorrectMetaGemEnchants(slot, apply);
6750 sLog.outDebug("_ApplyItemMods complete.");
6753 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6755 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6756 return;
6758 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6759 if (only_level_scale && !ssd)
6760 return;
6762 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6763 uint32 ssd_level = getLevel();
6764 if (ssd && ssd_level > ssd->MaxLevel)
6765 ssd_level = ssd->MaxLevel;
6767 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6768 if (only_level_scale && !ssv)
6769 return;
6771 for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6773 uint32 statType = 0;
6774 int32 val = 0;
6775 // If set ScalingStatDistribution need get stats and values from it
6776 if (ssd && ssv)
6778 if (ssd->StatMod[i] < 0)
6779 continue;
6780 statType = ssd->StatMod[i];
6781 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6783 else
6785 if (i >= proto->StatsCount)
6786 continue;
6787 statType = proto->ItemStat[i].ItemStatType;
6788 val = proto->ItemStat[i].ItemStatValue;
6791 if(val == 0)
6792 continue;
6794 switch (statType)
6796 case ITEM_MOD_MANA:
6797 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6798 break;
6799 case ITEM_MOD_HEALTH: // modify HP
6800 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6801 break;
6802 case ITEM_MOD_AGILITY: // modify agility
6803 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6804 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6805 break;
6806 case ITEM_MOD_STRENGTH: //modify strength
6807 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6808 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6809 break;
6810 case ITEM_MOD_INTELLECT: //modify intellect
6811 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6812 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6813 break;
6814 case ITEM_MOD_SPIRIT: //modify spirit
6815 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6816 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6817 break;
6818 case ITEM_MOD_STAMINA: //modify stamina
6819 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6820 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6821 break;
6822 case ITEM_MOD_DEFENSE_SKILL_RATING:
6823 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6824 break;
6825 case ITEM_MOD_DODGE_RATING:
6826 ApplyRatingMod(CR_DODGE, int32(val), apply);
6827 break;
6828 case ITEM_MOD_PARRY_RATING:
6829 ApplyRatingMod(CR_PARRY, int32(val), apply);
6830 break;
6831 case ITEM_MOD_BLOCK_RATING:
6832 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6833 break;
6834 case ITEM_MOD_HIT_MELEE_RATING:
6835 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6836 break;
6837 case ITEM_MOD_HIT_RANGED_RATING:
6838 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6839 break;
6840 case ITEM_MOD_HIT_SPELL_RATING:
6841 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6842 break;
6843 case ITEM_MOD_CRIT_MELEE_RATING:
6844 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6845 break;
6846 case ITEM_MOD_CRIT_RANGED_RATING:
6847 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6848 break;
6849 case ITEM_MOD_CRIT_SPELL_RATING:
6850 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6851 break;
6852 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6853 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6854 break;
6855 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6856 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6857 break;
6858 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6859 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6860 break;
6861 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6862 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6863 break;
6864 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6865 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6866 break;
6867 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6868 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6869 break;
6870 case ITEM_MOD_HASTE_MELEE_RATING:
6871 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6872 break;
6873 case ITEM_MOD_HASTE_RANGED_RATING:
6874 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6875 break;
6876 case ITEM_MOD_HASTE_SPELL_RATING:
6877 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6878 break;
6879 case ITEM_MOD_HIT_RATING:
6880 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6881 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6882 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6883 break;
6884 case ITEM_MOD_CRIT_RATING:
6885 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6886 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6887 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6888 break;
6889 case ITEM_MOD_HIT_TAKEN_RATING:
6890 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6891 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6892 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6893 break;
6894 case ITEM_MOD_CRIT_TAKEN_RATING:
6895 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6896 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6897 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6898 break;
6899 case ITEM_MOD_RESILIENCE_RATING:
6900 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6901 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6902 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6903 break;
6904 case ITEM_MOD_HASTE_RATING:
6905 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6906 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6907 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6908 break;
6909 case ITEM_MOD_EXPERTISE_RATING:
6910 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6911 break;
6912 case ITEM_MOD_ATTACK_POWER:
6913 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6914 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6915 break;
6916 case ITEM_MOD_RANGED_ATTACK_POWER:
6917 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6918 break;
6919 case ITEM_MOD_MANA_REGENERATION:
6920 ApplyManaRegenBonus(int32(val), apply);
6921 break;
6922 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6923 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6924 break;
6925 case ITEM_MOD_SPELL_POWER:
6926 ApplySpellPowerBonus(int32(val), apply);
6927 break;
6928 case ITEM_MOD_BLOCK_VALUE:
6929 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(val), apply);
6930 break;
6931 // depricated item mods
6932 case ITEM_MOD_FERAL_ATTACK_POWER:
6933 case ITEM_MOD_SPELL_HEALING_DONE:
6934 case ITEM_MOD_SPELL_DAMAGE_DONE:
6935 break;
6939 // Apply Spell Power from ScalingStatValue if set
6940 if(ssv)
6942 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6943 ApplySpellPowerBonus(spellbonus, apply);
6946 // If set ScalingStatValue armor get it or use item armor
6947 uint32 armor = proto->Armor;
6948 if (ssv)
6950 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6951 armor = ssvarmor;
6953 // Add armor bonus from ArmorDamageModifier if > 0
6954 if (proto->ArmorDamageModifier > 0)
6955 armor += uint32(proto->ArmorDamageModifier);
6957 if (armor)
6958 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6960 if (proto->Block)
6961 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6963 if (proto->HolyRes)
6964 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6966 if (proto->FireRes)
6967 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6969 if (proto->NatureRes)
6970 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6972 if (proto->FrostRes)
6973 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6975 if (proto->ShadowRes)
6976 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6978 if (proto->ArcaneRes)
6979 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6981 WeaponAttackType attType = BASE_ATTACK;
6982 float damage = 0.0f;
6984 if( slot == EQUIPMENT_SLOT_RANGED && (
6985 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6986 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6988 attType = RANGED_ATTACK;
6990 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6992 attType = OFF_ATTACK;
6995 float minDamage = proto->Damage[0].DamageMin;
6996 float maxDamage = proto->Damage[0].DamageMax;
6997 int32 extraDPS = 0;
6998 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6999 if (ssv)
7001 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
7003 float average = extraDPS * proto->Delay / 1000.0f;
7004 minDamage = 0.7f * average;
7005 maxDamage = 1.3f * average;
7008 if (minDamage > 0 )
7010 damage = apply ? minDamage : BASE_MINDAMAGE;
7011 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
7012 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
7015 if (maxDamage > 0 )
7017 damage = apply ? maxDamage : BASE_MAXDAMAGE;
7018 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
7021 // Apply feral bonus from ScalingStatValue if set
7022 if (ssv)
7024 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
7025 ApplyFeralAPBonus(feral_bonus, apply);
7027 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
7028 if(getClass() == CLASS_DRUID)
7030 int32 feral_bonus = proto->getFeralBonus(extraDPS);
7031 if (feral_bonus > 0)
7032 ApplyFeralAPBonus(feral_bonus, apply);
7035 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
7036 return;
7038 if (proto->Delay)
7040 if(slot == EQUIPMENT_SLOT_RANGED)
7041 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
7042 else if(slot==EQUIPMENT_SLOT_MAINHAND)
7043 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
7044 else if(slot==EQUIPMENT_SLOT_OFFHAND)
7045 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
7048 if(CanModifyStats() && (damage || proto->Delay))
7049 UpdateDamagePhysical(attType);
7052 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
7054 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
7055 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
7056 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
7058 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7059 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
7060 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
7062 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7063 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
7064 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
7067 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
7069 // generic not weapon specific case processes in aura code
7070 if(aura->GetSpellProto()->EquippedItemClass == -1)
7071 return;
7073 BaseModGroup mod = BASEMOD_END;
7074 switch(attackType)
7076 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
7077 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
7078 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
7079 default: return;
7082 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7084 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
7088 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
7090 // ignore spell mods for not wands
7091 Modifier const* modifier = aura->GetModifier();
7092 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
7093 return;
7095 // generic not weapon specific case processes in aura code
7096 if(aura->GetSpellProto()->EquippedItemClass == -1)
7097 return;
7099 UnitMods unitMod = UNIT_MOD_END;
7100 switch(attackType)
7102 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
7103 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
7104 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
7105 default: return;
7108 UnitModifierType unitModType = TOTAL_VALUE;
7109 switch(modifier->m_auraname)
7111 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
7112 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
7113 default: return;
7116 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
7118 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
7122 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
7124 if(!item)
7125 return;
7127 ItemPrototype const *proto = item->GetProto();
7128 if(!proto)
7129 return;
7131 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7133 _Spell const& spellData = proto->Spells[i];
7135 // no spell
7136 if(!spellData.SpellId )
7137 continue;
7139 // wrong triggering type
7140 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
7141 continue;
7143 // check if it is valid spell
7144 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
7145 if(!spellproto)
7146 continue;
7148 ApplyEquipSpell(spellproto,item,apply,form_change);
7152 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
7154 if(apply)
7156 // Cannot be used in this stance/form
7157 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
7158 return;
7160 if(form_change) // check aura active state from other form
7162 bool found = false;
7163 for (int k=0; k < MAX_EFFECT_INDEX; ++k)
7165 spellEffectPair spair = spellEffectPair(spellInfo->Id, SpellEffectIndex(k));
7166 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
7168 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
7170 found = true;
7171 break;
7174 if(found)
7175 break;
7178 if(found) // and skip re-cast already active aura at form change
7179 return;
7182 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7184 CastSpell(this,spellInfo,true,item);
7186 else
7188 if(form_change) // check aura compatibility
7190 // Cannot be used in this stance/form
7191 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7192 return; // and remove only not compatible at form change
7195 if(item)
7196 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7197 else
7198 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7202 void Player::UpdateEquipSpellsAtFormChange()
7204 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7206 if(m_items[i] && !m_items[i]->IsBroken())
7208 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7209 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7213 // item set bonuses not dependent from item broken state
7214 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7216 ItemSetEffect* eff = ItemSetEff[setindex];
7217 if(!eff)
7218 continue;
7220 for(uint32 y=0;y<8; ++y)
7222 SpellEntry const* spellInfo = eff->spells[y];
7223 if(!spellInfo)
7224 continue;
7226 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7227 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7232 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7234 Item *item = GetWeaponForAttack(attType, true, false);
7235 if(!item)
7236 return;
7238 ItemPrototype const *proto = item->GetProto();
7239 if(!proto)
7240 return;
7242 if (!Target || Target == this )
7243 return;
7245 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7247 _Spell const& spellData = proto->Spells[i];
7249 // no spell
7250 if(!spellData.SpellId )
7251 continue;
7253 // wrong triggering type
7254 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7255 continue;
7257 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7258 if(!spellInfo)
7260 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7261 continue;
7264 // not allow proc extra attack spell at extra attack
7265 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7266 return;
7268 float chance = (float)spellInfo->procChance;
7270 if(spellData.SpellPPMRate)
7272 uint32 WeaponSpeed = proto->Delay;
7273 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7275 else if(chance > 100.0f)
7277 chance = GetWeaponProcChance();
7280 if (roll_chance_f(chance))
7281 CastSpell(Target, spellInfo->Id, true, item);
7284 // item combat enchantments
7285 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7287 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7288 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7289 if(!pEnchant) continue;
7290 for (int s = 0; s < 3; ++s)
7292 if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7293 continue;
7295 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7296 if (!spellInfo)
7298 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7299 continue;
7302 // Use first rank to access spell item enchant procs
7303 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7305 float chance = ppmRate
7306 ? GetPPMProcChance(proto->Delay, ppmRate)
7307 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7310 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7311 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7313 if (roll_chance_f(chance))
7315 if(IsPositiveSpell(pEnchant->spellid[s]))
7316 CastSpell(this, pEnchant->spellid[s], true, item);
7317 else
7318 CastSpell(Target, pEnchant->spellid[s], true, item);
7324 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7326 ItemPrototype const* proto = item->GetProto();
7327 // special learning case
7328 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7330 uint32 learn_spell_id = proto->Spells[0].SpellId;
7331 uint32 learning_spell_id = proto->Spells[1].SpellId;
7333 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7334 if (!spellInfo)
7336 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7337 SendEquipError(EQUIP_ERR_NONE, item);
7338 return;
7341 Spell *spell = new Spell(this, spellInfo, false);
7342 spell->m_CastItem = item;
7343 spell->m_cast_count = cast_count; //set count of casts
7344 spell->m_currentBasePoints[EFFECT_INDEX_0] = learning_spell_id;
7345 spell->prepare(&targets);
7346 return;
7349 // use triggered flag only for items with many spell casts and for not first cast
7350 int count = 0;
7352 // item spells casted at use
7353 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7355 _Spell const& spellData = proto->Spells[i];
7357 // no spell
7358 if(!spellData.SpellId)
7359 continue;
7361 // wrong triggering type
7362 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7363 continue;
7365 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7366 if(!spellInfo)
7368 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7369 continue;
7372 Spell *spell = new Spell(this, spellInfo, (count > 0));
7373 spell->m_CastItem = item;
7374 spell->m_cast_count = cast_count; // set count of casts
7375 spell->m_glyphIndex = glyphIndex; // glyph index
7376 spell->prepare(&targets);
7378 ++count;
7381 // Item enchantments spells casted at use
7382 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7384 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7385 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7386 if(!pEnchant) continue;
7387 for (int s = 0; s < 3; ++s)
7389 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7390 continue;
7392 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7393 if (!spellInfo)
7395 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7396 continue;
7399 Spell *spell = new Spell(this, spellInfo, (count > 0));
7400 spell->m_CastItem = item;
7401 spell->m_cast_count = cast_count; // set count of casts
7402 spell->m_glyphIndex = glyphIndex; // glyph index
7403 spell->prepare(&targets);
7405 ++count;
7410 void Player::_RemoveAllItemMods()
7412 sLog.outDebug("_RemoveAllItemMods start.");
7414 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7416 if(m_items[i])
7418 ItemPrototype const *proto = m_items[i]->GetProto();
7419 if(!proto)
7420 continue;
7422 // item set bonuses not dependent from item broken state
7423 if(proto->ItemSet)
7424 RemoveItemsSetItem(this,proto);
7426 if(m_items[i]->IsBroken())
7427 continue;
7429 ApplyItemEquipSpell(m_items[i],false);
7430 ApplyEnchantment(m_items[i], false);
7434 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7436 if(m_items[i])
7438 if(m_items[i]->IsBroken())
7439 continue;
7440 ItemPrototype const *proto = m_items[i]->GetProto();
7441 if(!proto)
7442 continue;
7444 uint32 attacktype = Player::GetAttackBySlot(i);
7445 if(attacktype < MAX_ATTACK)
7446 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7448 _ApplyItemBonuses(proto,i, false);
7450 if( i == EQUIPMENT_SLOT_RANGED )
7451 _ApplyAmmoBonuses();
7455 sLog.outDebug("_RemoveAllItemMods complete.");
7458 void Player::_ApplyAllItemMods()
7460 sLog.outDebug("_ApplyAllItemMods start.");
7462 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7464 if(m_items[i])
7466 if(m_items[i]->IsBroken())
7467 continue;
7469 ItemPrototype const *proto = m_items[i]->GetProto();
7470 if(!proto)
7471 continue;
7473 uint32 attacktype = Player::GetAttackBySlot(i);
7474 if(attacktype < MAX_ATTACK)
7475 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7477 _ApplyItemBonuses(proto,i, true);
7479 if( i == EQUIPMENT_SLOT_RANGED )
7480 _ApplyAmmoBonuses();
7484 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7486 if(m_items[i])
7488 ItemPrototype const *proto = m_items[i]->GetProto();
7489 if(!proto)
7490 continue;
7492 // item set bonuses not dependent from item broken state
7493 if(proto->ItemSet)
7494 AddItemsSetItem(this,m_items[i]);
7496 if(m_items[i]->IsBroken())
7497 continue;
7499 ApplyItemEquipSpell(m_items[i],true);
7500 ApplyEnchantment(m_items[i], true);
7504 sLog.outDebug("_ApplyAllItemMods complete.");
7507 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7509 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7511 if(m_items[i])
7513 if(m_items[i]->IsBroken())
7514 continue;
7516 ItemPrototype const *proto = m_items[i]->GetProto();
7517 if(!proto)
7518 continue;
7520 _ApplyItemBonuses(proto,i, apply, true);
7525 void Player::_ApplyAmmoBonuses()
7527 // check ammo
7528 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7529 if(!ammo_id)
7530 return;
7532 float currentAmmoDPS;
7534 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7535 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7536 currentAmmoDPS = 0.0f;
7537 else
7538 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7540 if(currentAmmoDPS == GetAmmoDPS())
7541 return;
7543 m_ammoDPS = currentAmmoDPS;
7545 if(CanModifyStats())
7546 UpdateDamagePhysical(RANGED_ATTACK);
7549 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7551 if(!ammo_proto)
7552 return false;
7554 // check ranged weapon
7555 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7556 if (!weapon)
7557 return false;
7559 ItemPrototype const* weapon_proto = weapon->GetProto();
7560 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7561 return false;
7563 // check ammo ws. weapon compatibility
7564 switch(weapon_proto->SubClass)
7566 case ITEM_SUBCLASS_WEAPON_BOW:
7567 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7568 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7569 return false;
7570 break;
7571 case ITEM_SUBCLASS_WEAPON_GUN:
7572 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7573 return false;
7574 break;
7575 default:
7576 return false;
7579 return true;
7582 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7583 Called by remove insignia spell effect */
7584 void Player::RemovedInsignia(Player* looterPlr)
7586 if (!GetBattleGroundId())
7587 return;
7589 // If not released spirit, do it !
7590 if(m_deathTimer > 0)
7592 m_deathTimer = 0;
7593 BuildPlayerRepop();
7594 RepopAtGraveyard();
7597 Corpse *corpse = GetCorpse();
7598 if (!corpse)
7599 return;
7601 // We have to convert player corpse to bones, not to be able to resurrect there
7602 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7603 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7604 if (!bones)
7605 return;
7607 // Now we must make bones lootable, and send player loot
7608 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7610 // We store the level of our player in the gold field
7611 // We retrieve this information at Player::SendLoot()
7612 bones->loot.gold = getLevel();
7613 bones->lootRecipient = looterPlr;
7614 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7617 void Player::SendLootRelease(ObjectGuid guid)
7619 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7620 data << guid;
7621 data << uint8(1);
7622 SendDirectMessage( &data );
7625 void Player::SendLoot(ObjectGuid guid, LootType loot_type)
7627 if (uint64 lguid = GetLootGUID())
7628 m_session->DoLootRelease(lguid);
7630 Loot *loot = 0;
7631 PermissionTypes permission = ALL_PERMISSION;
7633 sLog.outDebug("Player::SendLoot");
7634 switch(guid.GetHigh())
7636 case HIGHGUID_GAMEOBJECT:
7638 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7639 GameObject *go = GetMap()->GetGameObject(guid);
7641 // not check distance for GO in case owned GO (fishing bobber case, for example)
7642 // And permit out of range GO with no owner in case fishing hole
7643 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7645 SendLootRelease(guid);
7646 return;
7649 loot = &go->loot;
7651 if (go->getLootState() == GO_READY)
7653 uint32 lootid = go->GetGOInfo()->GetLootId();
7654 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7655 if (BattleGround *bg = GetBattleGround())
7656 if (bg->GetTypeID() == BATTLEGROUND_AV)
7657 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7659 SendLootRelease(guid);
7660 return;
7663 if (lootid)
7665 sLog.outDebug(" if(lootid)");
7666 loot->clear();
7667 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7670 if (loot_type == LOOT_FISHING)
7671 go->getFishLoot(loot,this);
7673 go->SetLootState(GO_ACTIVATED);
7675 break;
7677 case HIGHGUID_ITEM:
7679 Item *item = GetItemByGuid( guid );
7681 if (!item)
7683 SendLootRelease(guid);
7684 return;
7687 loot = &item->loot;
7689 if (!item->m_lootGenerated)
7691 item->m_lootGenerated = true;
7692 loot->clear();
7694 switch(loot_type)
7696 case LOOT_DISENCHANTING:
7697 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7698 break;
7699 case LOOT_PROSPECTING:
7700 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7701 break;
7702 case LOOT_MILLING:
7703 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7704 break;
7705 default:
7706 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7707 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7708 break;
7711 break;
7713 case HIGHGUID_CORPSE: // remove insignia
7715 Corpse *bones = GetMap()->GetCorpse(guid);
7717 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7719 SendLootRelease(guid);
7720 return;
7723 loot = &bones->loot;
7725 if (!bones->lootForBody)
7727 bones->lootForBody = true;
7728 uint32 pLevel = bones->loot.gold;
7729 bones->loot.clear();
7730 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7731 loot->FillLoot(0, LootTemplates_Creature, this, false);
7732 // It may need a better formula
7733 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7734 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) );
7737 if (bones->lootRecipient != this)
7738 permission = NONE_PERMISSION;
7739 break;
7741 case HIGHGUID_UNIT:
7743 Creature *creature = GetMap()->GetCreature(guid);
7745 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7746 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7748 SendLootRelease(guid);
7749 return;
7752 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7754 SendLootRelease(guid);
7755 return;
7758 loot = &creature->loot;
7760 if (loot_type == LOOT_PICKPOCKETING)
7762 if (!creature->lootForPickPocketed)
7764 creature->lootForPickPocketed = true;
7765 loot->clear();
7767 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7768 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7770 // Generate extra money for pick pocket loot
7771 const uint32 a = urand(0, creature->getLevel()/2);
7772 const uint32 b = urand(0, getLevel()/2);
7773 loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
7776 else
7778 // the player whose group may loot the corpse
7779 Player *recipient = creature->GetLootRecipient();
7780 if (!recipient)
7782 creature->SetLootRecipient(this);
7783 recipient = this;
7786 if (creature->lootForPickPocketed)
7788 creature->lootForPickPocketed = false;
7789 loot->clear();
7792 if (!creature->lootForBody)
7794 creature->lootForBody = true;
7795 loot->clear();
7797 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7798 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7800 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7802 if (Group* group = recipient->GetGroup())
7804 group->UpdateLooterGuid(creature,true);
7806 switch (group->GetLootMethod())
7808 case GROUP_LOOT:
7809 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7810 group->GroupLoot(recipient->GetObjectGuid(), loot, creature);
7811 break;
7812 case NEED_BEFORE_GREED:
7813 group->NeedBeforeGreed(recipient->GetObjectGuid(), loot, creature);
7814 break;
7815 case MASTER_LOOT:
7816 group->MasterLoot(recipient->GetObjectGuid(), loot, creature);
7817 break;
7818 default:
7819 break;
7824 // possible only if creature->lootForBody && loot->empty() at spell cast check
7825 if (loot_type == LOOT_SKINNING)
7827 loot->clear();
7828 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7830 // set group rights only for loot_type != LOOT_SKINNING
7831 else
7833 if(Group* group = GetGroup())
7835 if (group == recipient->GetGroup())
7837 if (group->GetLootMethod() == FREE_FOR_ALL)
7838 permission = ALL_PERMISSION;
7839 else if (group->GetLooterGuid() == GetGUID())
7841 if (group->GetLootMethod() == MASTER_LOOT)
7842 permission = MASTER_PERMISSION;
7843 else
7844 permission = ALL_PERMISSION;
7846 else
7847 permission = GROUP_PERMISSION;
7849 else
7850 permission = NONE_PERMISSION;
7852 else if (recipient == this)
7853 permission = ALL_PERMISSION;
7854 else
7855 permission = NONE_PERMISSION;
7858 break;
7860 default:
7862 sLog.outError("%s is unsupported for looting.", guid.GetString().c_str());
7863 return;
7867 SetLootGUID(guid);
7869 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7870 switch(loot_type)
7872 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7873 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7874 default: break;
7877 // need know merged fishing/corpse loot type for achievements
7878 loot->loot_type = loot_type;
7880 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7882 data << guid;
7883 data << uint8(loot_type);
7884 data << LootView(*loot, this, permission);
7886 SendDirectMessage(&data);
7888 // add 'this' player as one of the players that are looting 'loot'
7889 if (permission != NONE_PERMISSION)
7890 loot->AddLooter(GetGUID());
7892 if (loot_type == LOOT_CORPSE && !guid.IsItem())
7893 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7896 void Player::SendNotifyLootMoneyRemoved()
7898 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7899 GetSession()->SendPacket( &data );
7902 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7904 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7905 data << uint8(lootSlot);
7906 GetSession()->SendPacket( &data );
7909 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7911 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7912 data << Field;
7913 data << Value;
7914 GetSession()->SendPacket(&data);
7917 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7919 // data depends on zoneid/mapid...
7920 BattleGround* bg = GetBattleGround();
7921 uint16 NumberOfFields = 0;
7922 uint32 mapid = GetMapId();
7924 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7926 // may be exist better way to do this...
7927 switch(zoneid)
7929 case 0:
7930 case 1:
7931 case 4:
7932 case 8:
7933 case 10:
7934 case 11:
7935 case 12:
7936 case 36:
7937 case 38:
7938 case 40:
7939 case 41:
7940 case 51:
7941 case 267:
7942 case 1519:
7943 case 1537:
7944 case 2257:
7945 case 2918:
7946 NumberOfFields = 8;
7947 break;
7948 case 139:
7949 NumberOfFields = 41;
7950 break;
7951 case 1377:
7952 NumberOfFields = 15;
7953 break;
7954 case 2597:
7955 NumberOfFields = 83;
7956 break;
7957 case 3277:
7958 NumberOfFields = 16;
7959 break;
7960 case 3358:
7961 case 3820:
7962 NumberOfFields = 40;
7963 break;
7964 case 3483:
7965 NumberOfFields = 27;
7966 break;
7967 case 3518:
7968 NumberOfFields = 39;
7969 break;
7970 case 3519:
7971 NumberOfFields = 38;
7972 break;
7973 case 3521:
7974 NumberOfFields = 37;
7975 break;
7976 case 3698:
7977 case 3702:
7978 case 3968:
7979 NumberOfFields = 11;
7980 break;
7981 case 3703:
7982 NumberOfFields = 11;
7983 break;
7984 default:
7985 NumberOfFields = 12;
7986 break;
7989 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7990 data << uint32(mapid); // mapid
7991 data << uint32(zoneid); // zone id
7992 data << uint32(areaid); // area id, new 2.1.0
7993 data << uint16(NumberOfFields); // count of uint64 blocks
7994 data << uint32(0x8d8) << uint32(0x0); // 1
7995 data << uint32(0x8d7) << uint32(0x0); // 2
7996 data << uint32(0x8d6) << uint32(0x0); // 3
7997 data << uint32(0x8d5) << uint32(0x0); // 4
7998 data << uint32(0x8d4) << uint32(0x0); // 5
7999 data << uint32(0x8d3) << uint32(0x0); // 6
8000 // 7 1 - Arena season in progress, 0 - end of season
8001 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS));
8002 // 8 Arena season id
8003 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID));
8004 if(mapid == 530) // Outland
8006 data << uint32(0x9bf) << uint32(0x0); // 7
8007 data << uint32(0x9bd) << uint32(0xF); // 8
8008 data << uint32(0x9bb) << uint32(0xF); // 9
8010 switch(zoneid)
8012 case 1:
8013 case 11:
8014 case 12:
8015 case 38:
8016 case 40:
8017 case 51:
8018 case 1519:
8019 case 1537:
8020 case 2257:
8021 break;
8022 case 2597: // AV
8023 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
8024 bg->FillInitialWorldStates(data);
8025 else
8027 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
8028 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
8029 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
8030 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
8031 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
8032 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
8033 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
8034 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
8035 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
8036 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
8037 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
8038 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
8039 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
8040 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
8041 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
8042 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
8043 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
8044 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
8045 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
8046 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
8047 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
8048 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
8049 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
8050 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
8051 data << uint32(0x568) << uint32(0x1); // 31 towerp c
8052 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
8053 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
8054 data << uint32(0x563) << uint32(0x0); // 34 dunn a
8055 data << uint32(0x562) << uint32(0x0); // 35 duns a
8056 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
8057 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
8058 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
8059 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
8060 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
8061 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
8062 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
8063 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
8064 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
8065 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
8066 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
8067 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
8068 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
8069 data << uint32(0x55a) << uint32(0x0); // 49 duns d
8070 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
8071 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
8072 data << uint32(0x557) << uint32(0x0); // 52 towerp d
8073 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
8074 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
8075 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
8076 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
8077 data << uint32(0x552) << uint32(0x1); // 57 dunn c
8078 data << uint32(0x551) << uint32(0x1); // 58 duns c
8079 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
8080 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
8081 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
8082 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
8083 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
8084 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
8085 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
8086 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
8087 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
8088 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
8089 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
8090 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
8091 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
8092 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
8093 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8094 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8095 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8096 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8097 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8098 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8099 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8100 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8101 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8103 break;
8104 case 3277: // WS
8105 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
8106 bg->FillInitialWorldStates(data);
8107 else
8109 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8110 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8111 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8112 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8113 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
8114 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8115 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8116 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8118 break;
8119 case 3358: // AB
8120 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
8121 bg->FillInitialWorldStates(data);
8122 else
8124 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8125 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8126 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8127 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8128 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8129 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8130 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8131 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8132 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8133 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8134 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8135 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8136 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8137 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8138 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8139 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8140 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8141 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8142 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8143 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8144 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8145 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8146 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8147 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8148 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8149 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8150 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8151 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8152 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8153 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8154 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
8155 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8157 break;
8158 case 3820: // EY
8159 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
8160 bg->FillInitialWorldStates(data);
8161 else
8163 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8164 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8165 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8166 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8167 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8168 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8169 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8170 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8171 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8172 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8173 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8174 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8175 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8176 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8177 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8178 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8179 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8180 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8181 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8182 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8183 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8184 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8185 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8186 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8187 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8188 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8189 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8190 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8191 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8192 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8193 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8194 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8195 // and some more ... unknown
8197 break;
8198 case 3483: // Hellfire Peninsula
8199 data << uint32(0x9ba) << uint32(0x1); // 10
8200 data << uint32(0x9b9) << uint32(0x1); // 11
8201 data << uint32(0x9b5) << uint32(0x0); // 12
8202 data << uint32(0x9b4) << uint32(0x1); // 13
8203 data << uint32(0x9b3) << uint32(0x0); // 14
8204 data << uint32(0x9b2) << uint32(0x0); // 15
8205 data << uint32(0x9b1) << uint32(0x1); // 16
8206 data << uint32(0x9b0) << uint32(0x0); // 17
8207 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8208 data << uint32(0x9ac) << uint32(0x0); // 19
8209 data << uint32(0x9a8) << uint32(0x0); // 20
8210 data << uint32(0x9a7) << uint32(0x0); // 21
8211 data << uint32(0x9a6) << uint32(0x1); // 22
8212 break;
8213 case 3519: // Terokkar Forest
8214 data << uint32(0xa41) << uint32(0x0); // 10
8215 data << uint32(0xa40) << uint32(0x14); // 11
8216 data << uint32(0xa3f) << uint32(0x0); // 12
8217 data << uint32(0xa3e) << uint32(0x0); // 13
8218 data << uint32(0xa3d) << uint32(0x5); // 14
8219 data << uint32(0xa3c) << uint32(0x0); // 15
8220 data << uint32(0xa87) << uint32(0x0); // 16
8221 data << uint32(0xa86) << uint32(0x0); // 17
8222 data << uint32(0xa85) << uint32(0x0); // 18
8223 data << uint32(0xa84) << uint32(0x0); // 19
8224 data << uint32(0xa83) << uint32(0x0); // 20
8225 data << uint32(0xa82) << uint32(0x0); // 21
8226 data << uint32(0xa81) << uint32(0x0); // 22
8227 data << uint32(0xa80) << uint32(0x0); // 23
8228 data << uint32(0xa7e) << uint32(0x0); // 24
8229 data << uint32(0xa7d) << uint32(0x0); // 25
8230 data << uint32(0xa7c) << uint32(0x0); // 26
8231 data << uint32(0xa7b) << uint32(0x0); // 27
8232 data << uint32(0xa7a) << uint32(0x0); // 28
8233 data << uint32(0xa79) << uint32(0x0); // 29
8234 data << uint32(0x9d0) << uint32(0x5); // 30
8235 data << uint32(0x9ce) << uint32(0x0); // 31
8236 data << uint32(0x9cd) << uint32(0x0); // 32
8237 data << uint32(0x9cc) << uint32(0x0); // 33
8238 data << uint32(0xa88) << uint32(0x0); // 34
8239 data << uint32(0xad0) << uint32(0x0); // 35
8240 data << uint32(0xacf) << uint32(0x1); // 36
8241 break;
8242 case 3521: // Zangarmarsh
8243 data << uint32(0x9e1) << uint32(0x0); // 10
8244 data << uint32(0x9e0) << uint32(0x0); // 11
8245 data << uint32(0x9df) << uint32(0x0); // 12
8246 data << uint32(0xa5d) << uint32(0x1); // 13
8247 data << uint32(0xa5c) << uint32(0x0); // 14
8248 data << uint32(0xa5b) << uint32(0x1); // 15
8249 data << uint32(0xa5a) << uint32(0x0); // 16
8250 data << uint32(0xa59) << uint32(0x1); // 17
8251 data << uint32(0xa58) << uint32(0x0); // 18
8252 data << uint32(0xa57) << uint32(0x0); // 19
8253 data << uint32(0xa56) << uint32(0x0); // 20
8254 data << uint32(0xa55) << uint32(0x1); // 21
8255 data << uint32(0xa54) << uint32(0x0); // 22
8256 data << uint32(0x9e7) << uint32(0x0); // 23
8257 data << uint32(0x9e6) << uint32(0x0); // 24
8258 data << uint32(0x9e5) << uint32(0x0); // 25
8259 data << uint32(0xa00) << uint32(0x0); // 26
8260 data << uint32(0x9ff) << uint32(0x1); // 27
8261 data << uint32(0x9fe) << uint32(0x0); // 28
8262 data << uint32(0x9fd) << uint32(0x0); // 29
8263 data << uint32(0x9fc) << uint32(0x1); // 30
8264 data << uint32(0x9fb) << uint32(0x0); // 31
8265 data << uint32(0xa62) << uint32(0x0); // 32
8266 data << uint32(0xa61) << uint32(0x1); // 33
8267 data << uint32(0xa60) << uint32(0x1); // 34
8268 data << uint32(0xa5f) << uint32(0x0); // 35
8269 break;
8270 case 3698: // Nagrand Arena
8271 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8272 bg->FillInitialWorldStates(data);
8273 else
8275 data << uint32(0xa0f) << uint32(0x0); // 7
8276 data << uint32(0xa10) << uint32(0x0); // 8
8277 data << uint32(0xa11) << uint32(0x0); // 9 show
8279 break;
8280 case 3702: // Blade's Edge Arena
8281 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8282 bg->FillInitialWorldStates(data);
8283 else
8285 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8286 data << uint32(0x9f1) << uint32(0x0); // 8 green
8287 data << uint32(0x9f3) << uint32(0x0); // 9 show
8289 break;
8290 case 3968: // Ruins of Lordaeron
8291 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8292 bg->FillInitialWorldStates(data);
8293 else
8295 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8296 data << uint32(0xbb9) << uint32(0x0); // 8 green
8297 data << uint32(0xbba) << uint32(0x0); // 9 show
8299 break;
8300 case 3703: // Shattrath City
8301 break;
8302 default:
8303 data << uint32(0x914) << uint32(0x0); // 7
8304 data << uint32(0x913) << uint32(0x0); // 8
8305 data << uint32(0x912) << uint32(0x0); // 9
8306 data << uint32(0x915) << uint32(0x0); // 10
8307 break;
8309 GetSession()->SendPacket(&data);
8312 uint32 Player::GetXPRestBonus(uint32 xp)
8314 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8316 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8317 rested_bonus = xp;
8319 SetRestBonus( GetRestBonus() - rested_bonus);
8321 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8322 return rested_bonus;
8325 void Player::SetBindPoint(uint64 guid)
8327 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8328 data << uint64(guid);
8329 GetSession()->SendPacket( &data );
8332 void Player::SendTalentWipeConfirm(uint64 guid)
8334 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8335 data << uint64(guid);
8336 data << uint32(resetTalentsCost());
8337 GetSession()->SendPacket( &data );
8340 void Player::SendPetSkillWipeConfirm()
8342 Pet* pet = GetPet();
8343 if(!pet)
8344 return;
8345 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8346 data << pet->GetGUID();
8347 data << uint32(pet->resetTalentsCost());
8348 GetSession()->SendPacket( &data );
8351 /*********************************************************/
8352 /*** STORAGE SYSTEM ***/
8353 /*********************************************************/
8355 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8357 ASSERT(i < 3);
8358 if(i < 2 && item)
8360 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8361 return;
8362 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8363 if(charges == 0)
8364 return;
8365 if(charges > 1)
8366 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8367 else if(charges <= 1)
8369 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8370 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8375 void Player::SetSheath( SheathState sheathed )
8377 switch (sheathed)
8379 case SHEATH_STATE_UNARMED: // no prepared weapon
8380 SetVirtualItemSlot(0,NULL);
8381 SetVirtualItemSlot(1,NULL);
8382 SetVirtualItemSlot(2,NULL);
8383 break;
8384 case SHEATH_STATE_MELEE: // prepared melee weapon
8386 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8387 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8388 SetVirtualItemSlot(2,NULL);
8389 }; break;
8390 case SHEATH_STATE_RANGED: // prepared ranged weapon
8391 SetVirtualItemSlot(0,NULL);
8392 SetVirtualItemSlot(1,NULL);
8393 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8394 break;
8395 default:
8396 SetVirtualItemSlot(0,NULL);
8397 SetVirtualItemSlot(1,NULL);
8398 SetVirtualItemSlot(2,NULL);
8399 break;
8401 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8404 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8406 uint8 pClass = getClass();
8408 uint8 slots[4];
8409 slots[0] = NULL_SLOT;
8410 slots[1] = NULL_SLOT;
8411 slots[2] = NULL_SLOT;
8412 slots[3] = NULL_SLOT;
8413 switch( proto->InventoryType )
8415 case INVTYPE_HEAD:
8416 slots[0] = EQUIPMENT_SLOT_HEAD;
8417 break;
8418 case INVTYPE_NECK:
8419 slots[0] = EQUIPMENT_SLOT_NECK;
8420 break;
8421 case INVTYPE_SHOULDERS:
8422 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8423 break;
8424 case INVTYPE_BODY:
8425 slots[0] = EQUIPMENT_SLOT_BODY;
8426 break;
8427 case INVTYPE_CHEST:
8428 slots[0] = EQUIPMENT_SLOT_CHEST;
8429 break;
8430 case INVTYPE_ROBE:
8431 slots[0] = EQUIPMENT_SLOT_CHEST;
8432 break;
8433 case INVTYPE_WAIST:
8434 slots[0] = EQUIPMENT_SLOT_WAIST;
8435 break;
8436 case INVTYPE_LEGS:
8437 slots[0] = EQUIPMENT_SLOT_LEGS;
8438 break;
8439 case INVTYPE_FEET:
8440 slots[0] = EQUIPMENT_SLOT_FEET;
8441 break;
8442 case INVTYPE_WRISTS:
8443 slots[0] = EQUIPMENT_SLOT_WRISTS;
8444 break;
8445 case INVTYPE_HANDS:
8446 slots[0] = EQUIPMENT_SLOT_HANDS;
8447 break;
8448 case INVTYPE_FINGER:
8449 slots[0] = EQUIPMENT_SLOT_FINGER1;
8450 slots[1] = EQUIPMENT_SLOT_FINGER2;
8451 break;
8452 case INVTYPE_TRINKET:
8453 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8454 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8455 break;
8456 case INVTYPE_CLOAK:
8457 slots[0] = EQUIPMENT_SLOT_BACK;
8458 break;
8459 case INVTYPE_WEAPON:
8461 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8463 // suggest offhand slot only if know dual wielding
8464 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8465 if(CanDualWield())
8466 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8467 break;
8469 case INVTYPE_SHIELD:
8470 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8471 break;
8472 case INVTYPE_RANGED:
8473 slots[0] = EQUIPMENT_SLOT_RANGED;
8474 break;
8475 case INVTYPE_2HWEAPON:
8476 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8477 if (CanDualWield() && CanTitanGrip())
8478 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8479 break;
8480 case INVTYPE_TABARD:
8481 slots[0] = EQUIPMENT_SLOT_TABARD;
8482 break;
8483 case INVTYPE_WEAPONMAINHAND:
8484 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8485 break;
8486 case INVTYPE_WEAPONOFFHAND:
8487 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8488 break;
8489 case INVTYPE_HOLDABLE:
8490 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8491 break;
8492 case INVTYPE_THROWN:
8493 slots[0] = EQUIPMENT_SLOT_RANGED;
8494 break;
8495 case INVTYPE_RANGEDRIGHT:
8496 slots[0] = EQUIPMENT_SLOT_RANGED;
8497 break;
8498 case INVTYPE_BAG:
8499 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8500 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8501 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8502 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8503 break;
8504 case INVTYPE_RELIC:
8506 switch(proto->SubClass)
8508 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8509 if (pClass == CLASS_PALADIN)
8510 slots[0] = EQUIPMENT_SLOT_RANGED;
8511 break;
8512 case ITEM_SUBCLASS_ARMOR_IDOL:
8513 if (pClass == CLASS_DRUID)
8514 slots[0] = EQUIPMENT_SLOT_RANGED;
8515 break;
8516 case ITEM_SUBCLASS_ARMOR_TOTEM:
8517 if (pClass == CLASS_SHAMAN)
8518 slots[0] = EQUIPMENT_SLOT_RANGED;
8519 break;
8520 case ITEM_SUBCLASS_ARMOR_MISC:
8521 if (pClass == CLASS_WARLOCK)
8522 slots[0] = EQUIPMENT_SLOT_RANGED;
8523 break;
8524 case ITEM_SUBCLASS_ARMOR_SIGIL:
8525 if (pClass == CLASS_DEATH_KNIGHT)
8526 slots[0] = EQUIPMENT_SLOT_RANGED;
8527 break;
8529 break;
8531 default :
8532 return NULL_SLOT;
8535 if( slot != NULL_SLOT )
8537 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8539 for (int i = 0; i < 4; ++i)
8541 if ( slots[i] == slot )
8542 return slot;
8546 else
8548 // search free slot at first
8549 for (int i = 0; i < 4; ++i)
8551 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8553 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8554 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8555 return slots[i];
8559 // if not found free and can swap return first appropriate from used
8560 for (int i = 0; i < 4; ++i)
8562 if ( slots[i] != NULL_SLOT && swap )
8563 return slots[i];
8567 // no free position
8568 return NULL_SLOT;
8571 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8573 Item *pItem;
8574 uint32 tempcount = 0;
8576 uint8 res = EQUIP_ERR_OK;
8578 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8580 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8581 if( pItem && pItem->GetEntry() == item )
8583 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8584 if(ires==EQUIP_ERR_OK)
8586 tempcount += pItem->GetCount();
8587 if( tempcount >= count )
8588 return EQUIP_ERR_OK;
8590 else
8591 res = ires;
8594 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8596 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8597 if( pItem && pItem->GetEntry() == item )
8599 tempcount += pItem->GetCount();
8600 if( tempcount >= count )
8601 return EQUIP_ERR_OK;
8604 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8606 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8607 if( pItem && pItem->GetEntry() == item )
8609 tempcount += pItem->GetCount();
8610 if( tempcount >= count )
8611 return EQUIP_ERR_OK;
8614 Bag *pBag;
8615 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8617 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8618 if( pBag )
8620 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8622 pItem = GetItemByPos( i, j );
8623 if( pItem && pItem->GetEntry() == item )
8625 tempcount += pItem->GetCount();
8626 if( tempcount >= count )
8627 return EQUIP_ERR_OK;
8633 // not found req. item count and have unequippable items
8634 return res;
8637 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8639 uint32 count = 0;
8640 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8642 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8643 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8644 count += pItem->GetCount();
8646 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8648 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8649 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8650 count += pItem->GetCount();
8652 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8654 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8655 if( pBag )
8656 count += pBag->GetItemCount(item,skipItem);
8659 if(skipItem && skipItem->GetProto()->GemProperties)
8661 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8663 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8664 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8665 count += pItem->GetGemCountWithID(item);
8669 if(inBankAlso)
8671 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8673 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8674 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8675 count += pItem->GetCount();
8677 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8679 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8680 if( pBag )
8681 count += pBag->GetItemCount(item,skipItem);
8684 if(skipItem && skipItem->GetProto()->GemProperties)
8686 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8688 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8689 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8690 count += pItem->GetGemCountWithID(item);
8695 return count;
8698 uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory ) const
8700 uint32 count = 0;
8701 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8702 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8703 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8704 count += pItem->GetCount();
8706 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8707 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8708 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8709 count += pItem->GetCount();
8711 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8712 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8713 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8715 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8716 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8717 if (pItem->GetProto()->ItemLimitCategory == limitCategory)
8718 count += pItem->GetCount();
8720 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8721 if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8722 count += pBag->GetItemCountWithLimitCategory(limitCategory);
8724 return count;
8727 Item* Player::GetItemByEntry( uint32 item ) const
8729 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8730 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8731 if (pItem->GetEntry() == item)
8732 return pItem;
8734 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8735 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8736 if (pItem->GetEntry() == item)
8737 return pItem;
8739 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8740 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8741 if (Item* itemPtr = pBag->GetItemByEntry(item))
8742 return itemPtr;
8744 return NULL;
8747 Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const
8749 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8750 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8751 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8752 return pItem;
8754 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8755 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8756 if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
8757 return pItem;
8759 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8760 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
8761 if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory))
8762 return itemPtr;
8764 return NULL;
8767 Item* Player::GetItemByGuid(ObjectGuid guid) const
8769 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8770 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8771 if (pItem->GetObjectGuid() == guid)
8772 return pItem;
8774 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8775 if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8776 if (pItem->GetObjectGuid() == guid)
8777 return pItem;
8779 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8780 if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8781 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8782 if (Item* pItem = pBag->GetItemByPos(j))
8783 if (pItem->GetObjectGuid() == guid)
8784 return pItem;
8786 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8787 if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
8788 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8789 if (Item* pItem = pBag->GetItemByPos(j))
8790 if (pItem->GetObjectGuid() == guid)
8791 return pItem;
8793 return NULL;
8796 Item* Player::GetItemByPos( uint16 pos ) const
8798 uint8 bag = pos >> 8;
8799 uint8 slot = pos & 255;
8800 return GetItemByPos( bag, slot );
8803 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8805 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8806 return m_items[slot];
8807 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8808 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8810 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8811 if ( pBag )
8812 return pBag->GetItemByPos(slot);
8814 return NULL;
8817 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8819 uint8 slot;
8820 switch (attackType)
8822 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8823 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8824 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8825 default: return NULL;
8828 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8829 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8830 return NULL;
8832 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8833 return NULL;
8835 if (nonbroken && item->IsBroken())
8836 return NULL;
8838 return item;
8841 Item* Player::GetShield(bool useable) const
8843 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8844 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8845 return NULL;
8847 if(!useable)
8848 return item;
8850 if( item->IsBroken())
8851 return NULL;
8853 return item;
8856 uint32 Player::GetAttackBySlot( uint8 slot )
8858 switch(slot)
8860 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8861 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8862 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8863 default: return MAX_ATTACK;
8867 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8869 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8870 return true;
8871 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8872 return true;
8873 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8874 return true;
8875 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8876 return true;
8877 return false;
8880 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8882 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8883 return true;
8884 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8885 return true;
8886 return false;
8889 bool Player::IsBankPos( uint8 bag, uint8 slot )
8891 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8892 return true;
8893 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8894 return true;
8895 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8896 return true;
8897 return false;
8900 bool Player::IsBagPos( uint16 pos )
8902 uint8 bag = pos >> 8;
8903 uint8 slot = pos & 255;
8904 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8905 return true;
8906 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8907 return true;
8908 return false;
8911 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const
8913 // post selected
8914 if(bag == NULL_BAG && !explicit_pos)
8915 return true;
8917 if (bag == INVENTORY_SLOT_BAG_0)
8919 // any post selected
8920 if (slot == NULL_SLOT && !explicit_pos)
8921 return true;
8923 // equipment
8924 if (slot < EQUIPMENT_SLOT_END)
8925 return true;
8927 // bag equip slots
8928 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8929 return true;
8931 // backpack slots
8932 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8933 return true;
8935 // keyring slots
8936 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8937 return true;
8939 // bank main slots
8940 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8941 return true;
8943 // bank bag slots
8944 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8945 return true;
8947 return false;
8950 // bag content slots
8951 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8953 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8954 if(!pBag)
8955 return false;
8957 // any post selected
8958 if (slot == NULL_SLOT && !explicit_pos)
8959 return true;
8961 return slot < pBag->GetBagSize();
8964 // bank bag content slots
8965 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8967 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8968 if(!pBag)
8969 return false;
8971 // any post selected
8972 if (slot == NULL_SLOT && !explicit_pos)
8973 return true;
8975 return slot < pBag->GetBagSize();
8978 // where this?
8979 return false;
8983 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8985 uint32 tempcount = 0;
8986 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8988 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8989 if( pItem && pItem->GetEntry() == item )
8991 tempcount += pItem->GetCount();
8992 if( tempcount >= count )
8993 return true;
8996 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8998 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8999 if( pItem && pItem->GetEntry() == item )
9001 tempcount += pItem->GetCount();
9002 if( tempcount >= count )
9003 return true;
9006 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9008 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9010 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9012 Item* pItem = GetItemByPos( i, j );
9013 if( pItem && pItem->GetEntry() == item )
9015 tempcount += pItem->GetCount();
9016 if( tempcount >= count )
9017 return true;
9023 if(inBankAlso)
9025 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
9027 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9028 if( pItem && pItem->GetEntry() == item )
9030 tempcount += pItem->GetCount();
9031 if( tempcount >= count )
9032 return true;
9035 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9037 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9039 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9041 Item* pItem = GetItemByPos( i, j );
9042 if( pItem && pItem->GetEntry() == item )
9044 tempcount += pItem->GetCount();
9045 if( tempcount >= count )
9046 return true;
9053 return false;
9056 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
9058 uint32 tempcount = 0;
9059 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9061 if(i==int(except_slot))
9062 continue;
9064 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9065 if( pItem && pItem->GetEntry() == item)
9067 tempcount += pItem->GetCount();
9068 if( tempcount >= count )
9069 return true;
9073 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
9074 if (pProto && pProto->GemProperties)
9076 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9078 if(i==int(except_slot))
9079 continue;
9081 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9082 if( pItem && pItem->GetProto()->Socket[0].Color)
9084 tempcount += pItem->GetGemCountWithID(item);
9085 if( tempcount >= count )
9086 return true;
9091 return false;
9094 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
9096 uint32 tempcount = 0;
9097 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
9099 if(i==int(except_slot))
9100 continue;
9102 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9103 if (!pItem)
9104 continue;
9106 ItemPrototype const *pProto = pItem->GetProto();
9107 if (!pProto)
9108 continue;
9110 if (pProto->ItemLimitCategory == limitCategory)
9112 tempcount += pItem->GetCount();
9113 if( tempcount >= count )
9114 return true;
9117 if( pProto->Socket[0].Color)
9119 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
9120 if( tempcount >= count )
9121 return true;
9125 return false;
9128 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
9130 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9131 if( !pProto )
9133 if(no_space_count)
9134 *no_space_count = count;
9135 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9138 // no maximum
9139 if(pProto->MaxCount > 0)
9141 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
9143 if (curcount + count > uint32(pProto->MaxCount))
9145 if(no_space_count)
9146 *no_space_count = count +curcount - pProto->MaxCount;
9147 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9151 // check unique-equipped limit
9152 if (pProto->ItemLimitCategory)
9154 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
9155 if (!limitEntry)
9157 if(no_space_count)
9158 *no_space_count = count;
9159 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9162 if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
9164 uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory);
9166 if (curcount + count > uint32(limitEntry->maxCount))
9168 if(no_space_count)
9169 *no_space_count = count + curcount - limitEntry->maxCount;
9170 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
9175 return EQUIP_ERR_OK;
9178 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
9180 Item *pItem;
9181 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9183 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9184 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9185 return true;
9187 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9189 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9190 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9191 return true;
9193 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9195 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9197 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9199 pItem = GetItemByPos( i, j );
9200 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
9201 return true;
9205 return false;
9208 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
9210 Item* pItem2 = GetItemByPos( bag, slot );
9212 // ignore move item (this slot will be empty at move)
9213 if (pItem2==pSrcItem)
9214 pItem2 = NULL;
9216 uint32 need_space;
9218 // empty specific slot - check item fit to slot
9219 if (!pItem2 || swap)
9221 if (bag == INVENTORY_SLOT_BAG_0)
9223 // keyring case
9224 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
9225 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9227 // currencytoken case
9228 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
9229 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9231 // prevent cheating
9232 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
9233 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9235 else
9237 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9238 if (!pBag)
9239 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9241 ItemPrototype const* pBagProto = pBag->GetProto();
9242 if (!pBagProto)
9243 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9245 if (slot >= pBagProto->ContainerSlots)
9246 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9248 if (!ItemCanGoIntoBag(pProto,pBagProto))
9249 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9252 // non empty stack with space
9253 need_space = pProto->GetMaxStackSize();
9255 // non empty slot, check item type
9256 else
9258 // can be merged at least partly
9259 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9260 if (res != EQUIP_ERR_OK)
9261 return res;
9263 // free stack space or infinity
9264 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9267 if (need_space > count)
9268 need_space = count;
9270 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9271 if (!newPosition.isContainedIn(dest))
9273 dest.push_back(newPosition);
9274 count -= need_space;
9276 return EQUIP_ERR_OK;
9279 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
9281 // skip specific bag already processed in first called _CanStoreItem_InBag
9282 if (bag==skip_bag)
9283 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9285 // skip not existed bag or self targeted bag
9286 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9287 if (!pBag || pBag==pSrcItem)
9288 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9290 ItemPrototype const* pBagProto = pBag->GetProto();
9291 if (!pBagProto)
9292 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9294 // specialized bag mode or non-specilized
9295 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9296 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9298 if (!ItemCanGoIntoBag(pProto,pBagProto))
9299 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9301 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9303 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9304 if (j==skip_slot)
9305 continue;
9307 Item* pItem2 = GetItemByPos( bag, j );
9309 // ignore move item (this slot will be empty at move)
9310 if (pItem2 == pSrcItem)
9311 pItem2 = NULL;
9313 // if merge skip empty, if !merge skip non-empty
9314 if ((pItem2 != NULL) != merge)
9315 continue;
9317 uint32 need_space = pProto->GetMaxStackSize();
9319 if (pItem2)
9321 // can be merged at least partly
9322 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9323 if (res != EQUIP_ERR_OK)
9324 continue;
9326 // descrease at current stacksize
9327 need_space -= pItem2->GetCount();
9330 if (need_space > count)
9331 need_space = count;
9333 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9334 if (!newPosition.isContainedIn(dest))
9336 dest.push_back(newPosition);
9337 count -= need_space;
9339 if (count==0)
9340 return EQUIP_ERR_OK;
9343 return EQUIP_ERR_OK;
9346 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
9348 for(uint32 j = slot_begin; j < slot_end; ++j)
9350 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9351 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9352 continue;
9354 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9356 // ignore move item (this slot will be empty at move)
9357 if (pItem2==pSrcItem)
9358 pItem2 = NULL;
9360 // if merge skip empty, if !merge skip non-empty
9361 if ((pItem2 != NULL) != merge)
9362 continue;
9364 uint32 need_space = pProto->GetMaxStackSize();
9366 if (pItem2)
9368 // can be merged at least partly
9369 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9370 if (res != EQUIP_ERR_OK)
9371 continue;
9373 // descrease at current stacksize
9374 need_space -= pItem2->GetCount();
9377 if (need_space > count)
9378 need_space = count;
9380 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9381 if (!newPosition.isContainedIn(dest))
9383 dest.push_back(newPosition);
9384 count -= need_space;
9386 if (count==0)
9387 return EQUIP_ERR_OK;
9390 return EQUIP_ERR_OK;
9393 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9395 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9397 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9398 if (!pProto)
9400 if (no_space_count)
9401 *no_space_count = count;
9402 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9405 if (pItem)
9407 // item used
9408 if(pItem->m_lootGenerated)
9410 if (no_space_count)
9411 *no_space_count = count;
9412 return EQUIP_ERR_ALREADY_LOOTED;
9415 if (pItem->IsBindedNotWith(this))
9417 if (no_space_count)
9418 *no_space_count = count;
9419 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9423 // check count of items (skip for auto move for same player from bank)
9424 uint32 no_similar_count = 0; // can't store this amount similar items
9425 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9426 if (res!=EQUIP_ERR_OK)
9428 if (count==no_similar_count)
9430 if (no_space_count)
9431 *no_space_count = no_similar_count;
9432 return res;
9434 count -= no_similar_count;
9437 // in specific slot
9438 if (bag != NULL_BAG && slot != NULL_SLOT)
9440 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9441 if (res!=EQUIP_ERR_OK)
9443 if (no_space_count)
9444 *no_space_count = count + no_similar_count;
9445 return res;
9448 if (count==0)
9450 if (no_similar_count==0)
9451 return EQUIP_ERR_OK;
9453 if (no_space_count)
9454 *no_space_count = count + no_similar_count;
9455 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9459 // not specific slot or have space for partly store only in specific slot
9461 // in specific bag
9462 if (bag != NULL_BAG)
9464 // search stack in bag for merge to
9465 if (pProto->Stackable != 1)
9467 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9469 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9470 if (res!=EQUIP_ERR_OK)
9472 if (no_space_count)
9473 *no_space_count = count + no_similar_count;
9474 return res;
9477 if (count==0)
9479 if (no_similar_count==0)
9480 return EQUIP_ERR_OK;
9482 if (no_space_count)
9483 *no_space_count = count + no_similar_count;
9484 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9487 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9488 if (res!=EQUIP_ERR_OK)
9490 if (no_space_count)
9491 *no_space_count = count + no_similar_count;
9492 return res;
9495 if (count==0)
9497 if (no_similar_count==0)
9498 return EQUIP_ERR_OK;
9500 if (no_space_count)
9501 *no_space_count = count + no_similar_count;
9502 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9505 else // equipped bag
9507 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9508 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9509 if (res!=EQUIP_ERR_OK)
9510 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9512 if (res!=EQUIP_ERR_OK)
9514 if (no_space_count)
9515 *no_space_count = count + no_similar_count;
9516 return res;
9519 if (count==0)
9521 if (no_similar_count==0)
9522 return EQUIP_ERR_OK;
9524 if (no_space_count)
9525 *no_space_count = count + no_similar_count;
9526 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9531 // search free slot in bag for place to
9532 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9534 // search free slot - keyring case
9535 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9537 uint32 keyringSize = GetMaxKeyringSize();
9538 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9539 if (res!=EQUIP_ERR_OK)
9541 if (no_space_count)
9542 *no_space_count = count + no_similar_count;
9543 return res;
9546 if (count==0)
9548 if (no_similar_count==0)
9549 return EQUIP_ERR_OK;
9551 if (no_space_count)
9552 *no_space_count = count + no_similar_count;
9553 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9556 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9557 if (res!=EQUIP_ERR_OK)
9559 if (no_space_count)
9560 *no_space_count = count + no_similar_count;
9561 return res;
9564 if (count==0)
9566 if (no_similar_count==0)
9567 return EQUIP_ERR_OK;
9569 if (no_space_count)
9570 *no_space_count = count + no_similar_count;
9571 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9574 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9576 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9577 if (res!=EQUIP_ERR_OK)
9579 if (no_space_count)
9580 *no_space_count = count + no_similar_count;
9581 return res;
9584 if (count==0)
9586 if (no_similar_count==0)
9587 return EQUIP_ERR_OK;
9589 if (no_space_count)
9590 *no_space_count = count + no_similar_count;
9591 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9595 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9596 if (res!=EQUIP_ERR_OK)
9598 if (no_space_count)
9599 *no_space_count = count + no_similar_count;
9600 return res;
9603 if (count==0)
9605 if (no_similar_count==0)
9606 return EQUIP_ERR_OK;
9608 if (no_space_count)
9609 *no_space_count = count + no_similar_count;
9610 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9613 else // equipped bag
9615 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9616 if (res!=EQUIP_ERR_OK)
9617 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9619 if (res!=EQUIP_ERR_OK)
9621 if (no_space_count)
9622 *no_space_count = count + no_similar_count;
9623 return res;
9626 if (count==0)
9628 if (no_similar_count==0)
9629 return EQUIP_ERR_OK;
9631 if (no_space_count)
9632 *no_space_count = count + no_similar_count;
9633 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9638 // not specific bag or have space for partly store only in specific bag
9640 // search stack for merge to
9641 if (pProto->Stackable != 1)
9643 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9644 if (res!=EQUIP_ERR_OK)
9646 if (no_space_count)
9647 *no_space_count = count + no_similar_count;
9648 return res;
9651 if (count==0)
9653 if (no_similar_count==0)
9654 return EQUIP_ERR_OK;
9656 if (no_space_count)
9657 *no_space_count = count + no_similar_count;
9658 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9661 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9662 if (res!=EQUIP_ERR_OK)
9664 if (no_space_count)
9665 *no_space_count = count + no_similar_count;
9666 return res;
9669 if (count==0)
9671 if (no_similar_count==0)
9672 return EQUIP_ERR_OK;
9674 if (no_space_count)
9675 *no_space_count = count + no_similar_count;
9676 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9679 if (pProto->BagFamily)
9681 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9683 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9684 if (res!=EQUIP_ERR_OK)
9685 continue;
9687 if (count==0)
9689 if (no_similar_count==0)
9690 return EQUIP_ERR_OK;
9692 if (no_space_count)
9693 *no_space_count = count + no_similar_count;
9694 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9699 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9701 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9702 if (res!=EQUIP_ERR_OK)
9703 continue;
9705 if (count==0)
9707 if (no_similar_count==0)
9708 return EQUIP_ERR_OK;
9710 if (no_space_count)
9711 *no_space_count = count + no_similar_count;
9712 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9717 // search free slot - special bag case
9718 if (pProto->BagFamily)
9720 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9722 uint32 keyringSize = GetMaxKeyringSize();
9723 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9724 if (res!=EQUIP_ERR_OK)
9726 if (no_space_count)
9727 *no_space_count = count + no_similar_count;
9728 return res;
9731 if (count==0)
9733 if (no_similar_count==0)
9734 return EQUIP_ERR_OK;
9736 if (no_space_count)
9737 *no_space_count = count + no_similar_count;
9738 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9741 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9743 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9744 if (res!=EQUIP_ERR_OK)
9746 if (no_space_count)
9747 *no_space_count = count + no_similar_count;
9748 return res;
9751 if (count==0)
9753 if (no_similar_count==0)
9754 return EQUIP_ERR_OK;
9756 if (no_space_count)
9757 *no_space_count = count + no_similar_count;
9758 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9762 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9764 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9765 if (res!=EQUIP_ERR_OK)
9766 continue;
9768 if (count==0)
9770 if (no_similar_count==0)
9771 return EQUIP_ERR_OK;
9773 if (no_space_count)
9774 *no_space_count = count + no_similar_count;
9775 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9780 // search free slot
9781 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9782 if (res!=EQUIP_ERR_OK)
9784 if (no_space_count)
9785 *no_space_count = count + no_similar_count;
9786 return res;
9789 if (count==0)
9791 if (no_similar_count==0)
9792 return EQUIP_ERR_OK;
9794 if (no_space_count)
9795 *no_space_count = count + no_similar_count;
9796 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9799 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9801 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9802 if (res!=EQUIP_ERR_OK)
9803 continue;
9805 if (count==0)
9807 if (no_similar_count==0)
9808 return EQUIP_ERR_OK;
9810 if (no_space_count)
9811 *no_space_count = count + no_similar_count;
9812 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9816 if (no_space_count)
9817 *no_space_count = count + no_similar_count;
9819 return EQUIP_ERR_INVENTORY_FULL;
9822 //////////////////////////////////////////////////////////////////////////
9823 uint8 Player::CanStoreItems( Item **pItems,int count) const
9825 Item *pItem2;
9827 // fill space table
9828 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9829 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9830 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9831 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9833 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9834 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9835 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9836 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9838 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9840 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9842 if (pItem2 && !pItem2->IsInTrade())
9844 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9848 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9850 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9852 if (pItem2 && !pItem2->IsInTrade())
9854 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9858 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9860 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9862 if (pItem2 && !pItem2->IsInTrade())
9864 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9868 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9870 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9872 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9874 pItem2 = GetItemByPos( i, j );
9875 if (pItem2 && !pItem2->IsInTrade())
9877 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9883 // check free space for all items
9884 for (int k = 0; k < count; ++k)
9886 Item *pItem = pItems[k];
9888 // no item
9889 if (!pItem) continue;
9891 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9892 ItemPrototype const *pProto = pItem->GetProto();
9894 // strange item
9895 if( !pProto )
9896 return EQUIP_ERR_ITEM_NOT_FOUND;
9898 // item used
9899 if(pItem->m_lootGenerated)
9900 return EQUIP_ERR_ALREADY_LOOTED;
9902 // item it 'bind'
9903 if(pItem->IsBindedNotWith(this))
9904 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9906 Bag *pBag;
9907 ItemPrototype const *pBagProto;
9909 // item is 'one item only'
9910 uint8 res = CanTakeMoreSimilarItems(pItem);
9911 if(res != EQUIP_ERR_OK)
9912 return res;
9914 // search stack for merge to
9915 if( pProto->Stackable != 1 )
9917 bool b_found = false;
9919 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9921 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9922 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9924 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9925 b_found = true;
9926 break;
9929 if (b_found) continue;
9931 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9933 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9934 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9936 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9937 b_found = true;
9938 break;
9941 if (b_found) continue;
9943 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9945 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9946 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9948 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9949 b_found = true;
9950 break;
9953 if (b_found) continue;
9955 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9957 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9958 if( pBag )
9960 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9962 pItem2 = GetItemByPos( t, j );
9963 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9965 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9966 b_found = true;
9967 break;
9972 if (b_found) continue;
9975 // special bag case
9976 if( pProto->BagFamily )
9978 bool b_found = false;
9979 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9981 uint32 keyringSize = GetMaxKeyringSize();
9982 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9984 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9986 inv_keys[t-KEYRING_SLOT_START] = 1;
9987 b_found = true;
9988 break;
9993 if (b_found) continue;
9995 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9997 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9999 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
10001 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
10002 b_found = true;
10003 break;
10008 if (b_found) continue;
10010 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
10012 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
10013 if( pBag )
10015 pBagProto = pBag->GetProto();
10017 // not plain container check
10018 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
10019 ItemCanGoIntoBag(pProto,pBagProto) )
10021 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10023 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
10025 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
10026 b_found = true;
10027 break;
10033 if (b_found) continue;
10036 // search free slot
10037 bool b_found = false;
10038 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
10040 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
10042 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
10043 b_found = true;
10044 break;
10047 if (b_found) continue;
10049 // search free slot in bags
10050 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
10052 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
10053 if( pBag )
10055 pBagProto = pBag->GetProto();
10057 // special bag already checked
10058 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
10059 continue;
10061 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10063 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
10065 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
10066 b_found = true;
10067 break;
10073 // no free slot found?
10074 if (!b_found)
10075 return EQUIP_ERR_INVENTORY_FULL;
10078 return EQUIP_ERR_OK;
10081 //////////////////////////////////////////////////////////////////////////
10082 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
10084 dest = 0;
10085 Item *pItem = Item::CreateItem( item, 1, this );
10086 if( pItem )
10088 uint8 result = CanEquipItem(slot, dest, pItem, swap );
10089 delete pItem;
10090 return result;
10093 return EQUIP_ERR_ITEM_NOT_FOUND;
10096 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
10098 dest = 0;
10099 if( pItem )
10101 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
10102 ItemPrototype const *pProto = pItem->GetProto();
10103 if( pProto )
10105 // item used
10106 if(pItem->m_lootGenerated)
10107 return EQUIP_ERR_ALREADY_LOOTED;
10109 if(pItem->IsBindedNotWith(this))
10110 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10112 // check count of items (skip for auto move for same player from bank)
10113 uint8 res = CanTakeMoreSimilarItems(pItem);
10114 if(res != EQUIP_ERR_OK)
10115 return res;
10117 // check this only in game
10118 if(not_loading)
10120 // May be here should be more stronger checks; STUNNED checked
10121 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10122 if (hasUnitState(UNIT_STAT_STUNNED))
10123 return EQUIP_ERR_YOU_ARE_STUNNED;
10125 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10126 // - combat
10127 // - in-progress arenas
10128 if( !pProto->CanChangeEquipStateInCombat() )
10130 if( isInCombat() )
10131 return EQUIP_ERR_NOT_IN_COMBAT;
10133 if(BattleGround* bg = GetBattleGround())
10134 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10135 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10138 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
10139 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
10141 if(IsNonMeleeSpellCasted(false))
10142 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
10145 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
10146 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
10147 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
10148 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10150 uint8 eslot = FindEquipSlot( pProto, slot, swap );
10151 if (eslot == NULL_SLOT)
10152 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10154 uint8 msg = CanUseItem(pItem , not_loading);
10155 if (msg != EQUIP_ERR_OK)
10156 return msg;
10157 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
10158 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
10160 // if swap ignore item (equipped also)
10161 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
10162 return res2;
10164 // check unique-equipped special item classes
10165 if (pProto->Class == ITEM_CLASS_QUIVER)
10167 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10169 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
10171 if (pBag != pItem)
10173 if (ItemPrototype const* pBagProto = pBag->GetProto())
10175 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
10176 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
10177 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10178 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
10185 uint32 type = pProto->InventoryType;
10187 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10189 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
10191 if (!CanDualWield())
10192 return EQUIP_ERR_CANT_DUAL_WIELD;
10194 else if (type == INVTYPE_2HWEAPON)
10196 if (!CanDualWield() || !CanTitanGrip())
10197 return EQUIP_ERR_CANT_DUAL_WIELD;
10200 if (IsTwoHandUsed())
10201 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10204 // equip two-hand weapon case (with possible unequip 2 items)
10205 if (type == INVTYPE_2HWEAPON)
10207 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10209 if (!CanTitanGrip())
10210 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10212 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10213 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10215 if (!CanTitanGrip())
10217 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10218 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10219 ItemPosCountVec off_dest;
10220 if (offItem && (!not_loading ||
10221 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10222 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
10223 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10226 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10227 return EQUIP_ERR_OK;
10231 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10234 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10236 // Applied only to equipped items and bank bags
10237 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10238 return EQUIP_ERR_OK;
10240 Item* pItem = GetItemByPos(pos);
10242 // Applied only to existed equipped item
10243 if( !pItem )
10244 return EQUIP_ERR_OK;
10246 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10248 ItemPrototype const *pProto = pItem->GetProto();
10249 if( !pProto )
10250 return EQUIP_ERR_ITEM_NOT_FOUND;
10252 // item used
10253 if(pItem->m_lootGenerated)
10254 return EQUIP_ERR_ALREADY_LOOTED;
10256 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10257 // - combat
10258 // - in-progress arenas
10259 if( !pProto->CanChangeEquipStateInCombat() )
10261 if( isInCombat() )
10262 return EQUIP_ERR_NOT_IN_COMBAT;
10264 if(BattleGround* bg = GetBattleGround())
10265 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10266 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10269 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10270 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10272 return EQUIP_ERR_OK;
10275 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10277 if (!pItem)
10278 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10280 uint32 count = pItem->GetCount();
10282 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10283 ItemPrototype const *pProto = pItem->GetProto();
10284 if (!pProto)
10285 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10287 // item used
10288 if(pItem->m_lootGenerated)
10289 return EQUIP_ERR_ALREADY_LOOTED;
10291 if (pItem->IsBindedNotWith(this))
10292 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10294 // check count of items (skip for auto move for same player from bank)
10295 uint8 res = CanTakeMoreSimilarItems(pItem);
10296 if (res != EQUIP_ERR_OK)
10297 return res;
10299 // in specific slot
10300 if (bag != NULL_BAG && slot != NULL_SLOT)
10302 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10304 if (!pItem->IsBag())
10305 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10307 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10308 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10310 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10311 return cantuse;
10314 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10315 if (res!=EQUIP_ERR_OK)
10316 return res;
10318 if (count==0)
10319 return EQUIP_ERR_OK;
10322 // not specific slot or have space for partly store only in specific slot
10324 // in specific bag
10325 if( bag != NULL_BAG )
10327 if( pProto->InventoryType == INVTYPE_BAG )
10329 Bag *pBag = (Bag*)pItem;
10330 if( pBag && !pBag->IsEmpty() )
10331 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10334 // search stack in bag for merge to
10335 if( pProto->Stackable != 1 )
10337 if( bag == INVENTORY_SLOT_BAG_0 )
10339 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10340 if(res!=EQUIP_ERR_OK)
10341 return res;
10343 if(count==0)
10344 return EQUIP_ERR_OK;
10346 else
10348 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10349 if(res!=EQUIP_ERR_OK)
10350 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10352 if(res!=EQUIP_ERR_OK)
10353 return res;
10355 if(count==0)
10356 return EQUIP_ERR_OK;
10360 // search free slot in bag
10361 if( bag == INVENTORY_SLOT_BAG_0 )
10363 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10364 if(res!=EQUIP_ERR_OK)
10365 return res;
10367 if(count==0)
10368 return EQUIP_ERR_OK;
10370 else
10372 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10373 if(res != EQUIP_ERR_OK)
10374 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10376 if(res != EQUIP_ERR_OK)
10377 return res;
10379 if(count == 0)
10380 return EQUIP_ERR_OK;
10384 // not specific bag or have space for partly store only in specific bag
10386 // search stack for merge to
10387 if( pProto->Stackable != 1 )
10389 // in slots
10390 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10391 if(res != EQUIP_ERR_OK)
10392 return res;
10394 if(count == 0)
10395 return EQUIP_ERR_OK;
10397 // in special bags
10398 if( pProto->BagFamily )
10400 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10402 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10403 if(res!=EQUIP_ERR_OK)
10404 continue;
10406 if(count==0)
10407 return EQUIP_ERR_OK;
10411 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10413 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10414 if(res!=EQUIP_ERR_OK)
10415 continue;
10417 if(count==0)
10418 return EQUIP_ERR_OK;
10422 // search free place in special bag
10423 if( pProto->BagFamily )
10425 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10427 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10428 if(res!=EQUIP_ERR_OK)
10429 continue;
10431 if(count==0)
10432 return EQUIP_ERR_OK;
10436 // search free space
10437 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10438 if(res!=EQUIP_ERR_OK)
10439 return res;
10441 if(count==0)
10442 return EQUIP_ERR_OK;
10444 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10446 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10447 if(res!=EQUIP_ERR_OK)
10448 continue;
10450 if(count==0)
10451 return EQUIP_ERR_OK;
10453 return EQUIP_ERR_BANK_FULL;
10456 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10458 if (pItem)
10460 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10462 if (!isAlive() && not_loading)
10463 return EQUIP_ERR_YOU_ARE_DEAD;
10465 //if (isStunned())
10466 // return EQUIP_ERR_YOU_ARE_STUNNED;
10468 ItemPrototype const *pProto = pItem->GetProto();
10469 if (pProto)
10471 if (pItem->IsBindedNotWith(this))
10472 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10474 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10475 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10477 if (uint32 item_use_skill = pItem->GetSkill())
10479 if (GetSkillValue(item_use_skill) == 0)
10481 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10482 if (pProto->Class != ITEM_CLASS_ARMOR)
10483 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10485 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10486 if (!ssd)
10487 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10489 bool allowScaleSkill = false;
10490 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10492 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10493 if (!skillInfo)
10494 continue;
10496 if (skillInfo->skillId != item_use_skill)
10497 continue;
10499 // can't learn
10500 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10501 continue;
10503 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10504 continue;
10506 allowScaleSkill = true;
10507 break;
10510 if (!allowScaleSkill)
10511 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10515 if (pProto->RequiredSkill != 0)
10517 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10518 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10520 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10521 return EQUIP_ERR_CANT_EQUIP_SKILL;
10524 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10525 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10527 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10528 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10530 if (getLevel() < pProto->RequiredLevel)
10531 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10533 return EQUIP_ERR_OK;
10536 return EQUIP_ERR_ITEM_NOT_FOUND;
10539 bool Player::CanUseItem( ItemPrototype const *pProto )
10541 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10543 if( pProto )
10545 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10546 return false;
10547 if( pProto->RequiredSkill != 0 )
10549 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10550 return false;
10551 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10552 return false;
10554 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10555 return false;
10556 if( getLevel() < pProto->RequiredLevel )
10557 return false;
10558 return true;
10560 return false;
10563 uint8 Player::CanUseAmmo( uint32 item ) const
10565 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10566 if( !isAlive() )
10567 return EQUIP_ERR_YOU_ARE_DEAD;
10568 //if( isStunned() )
10569 // return EQUIP_ERR_YOU_ARE_STUNNED;
10570 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10571 if( pProto )
10573 if( pProto->InventoryType!= INVTYPE_AMMO )
10574 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10575 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10576 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10577 if( pProto->RequiredSkill != 0 )
10579 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10580 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10581 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10582 return EQUIP_ERR_CANT_EQUIP_SKILL;
10584 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10585 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10586 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10587 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10589 if( getLevel() < pProto->RequiredLevel )
10590 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10592 // Requires No Ammo
10593 if(GetDummyAura(46699))
10594 return EQUIP_ERR_BAG_FULL6;
10596 return EQUIP_ERR_OK;
10598 return EQUIP_ERR_ITEM_NOT_FOUND;
10601 void Player::SetAmmo( uint32 item )
10603 if(!item)
10604 return;
10606 // already set
10607 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10608 return;
10610 // check ammo
10611 if (item)
10613 uint8 msg = CanUseAmmo( item );
10614 if (msg != EQUIP_ERR_OK)
10616 SendEquipError(msg, NULL, NULL, item);
10617 return;
10621 SetUInt32Value(PLAYER_AMMO_ID, item);
10623 _ApplyAmmoBonuses();
10626 void Player::RemoveAmmo()
10628 SetUInt32Value(PLAYER_AMMO_ID, 0);
10630 m_ammoDPS = 0.0f;
10632 if (CanModifyStats())
10633 UpdateDamagePhysical(RANGED_ATTACK);
10636 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10637 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10639 uint32 count = 0;
10640 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10641 count += itr->count;
10643 Item *pItem = Item::CreateItem( item, count, this );
10644 if( pItem )
10646 ItemAddedQuestCheck( item, count );
10647 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
10648 if(randomPropertyId)
10649 pItem->SetItemRandomProperties(randomPropertyId);
10650 pItem = StoreItem( dest, pItem, update );
10652 return pItem;
10655 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10657 if( !pItem )
10658 return NULL;
10660 Item* lastItem = pItem;
10661 uint32 entry = pItem->GetEntry();
10662 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10664 uint16 pos = itr->pos;
10665 uint32 count = itr->count;
10667 ++itr;
10669 if(itr == dest.end())
10671 lastItem = _StoreItem(pos,pItem,count,false,update);
10672 break;
10675 lastItem = _StoreItem(pos,pItem,count,true,update);
10677 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10678 return lastItem;
10681 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10682 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10684 if( !pItem )
10685 return NULL;
10687 uint8 bag = pos >> 8;
10688 uint8 slot = pos & 255;
10690 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10692 Item *pItem2 = GetItemByPos( bag, slot );
10694 if (!pItem2)
10696 if (clone)
10697 pItem = pItem->CloneItem(count, this);
10698 else
10699 pItem->SetCount(count);
10701 if (!pItem)
10702 return NULL;
10704 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10705 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10706 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10707 pItem->SetBinding( true );
10709 if (bag == INVENTORY_SLOT_BAG_0)
10711 m_items[slot] = pItem;
10712 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10713 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10714 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10716 pItem->SetSlot( slot );
10717 pItem->SetContainer( NULL );
10719 // need update known currency
10720 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10721 UpdateKnownCurrencies(pItem->GetEntry(), true);
10723 if (IsInWorld() && update)
10725 pItem->AddToWorld();
10726 pItem->SendCreateUpdateToPlayer( this );
10729 pItem->SetState(ITEM_CHANGED, this);
10731 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10733 pBag->StoreItem( slot, pItem, update );
10734 if( IsInWorld() && update )
10736 pItem->AddToWorld();
10737 pItem->SendCreateUpdateToPlayer( this );
10739 pItem->SetState(ITEM_CHANGED, this);
10740 pBag->SetState(ITEM_CHANGED, this);
10743 AddEnchantmentDurations(pItem);
10744 AddItemDurations(pItem);
10746 return pItem;
10748 else
10750 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10751 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10752 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10753 pItem2->SetBinding( true );
10755 pItem2->SetCount( pItem2->GetCount() + count );
10756 if (IsInWorld() && update)
10757 pItem2->SendCreateUpdateToPlayer( this );
10759 if (!clone)
10761 // delete item (it not in any slot currently)
10762 if (IsInWorld() && update)
10764 pItem->RemoveFromWorld();
10765 pItem->DestroyForPlayer( this );
10768 RemoveEnchantmentDurations(pItem);
10769 RemoveItemDurations(pItem);
10771 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10772 pItem->SetState(ITEM_REMOVED, this);
10775 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10776 AddEnchantmentDurations(pItem2);
10778 pItem2->SetState(ITEM_CHANGED, this);
10780 return pItem2;
10784 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10786 if (Item *pItem = Item::CreateItem( item, 1, this ))
10788 ItemAddedQuestCheck( item, 1 );
10789 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
10790 return EquipItem( pos, pItem, update );
10793 return NULL;
10796 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10798 AddEnchantmentDurations(pItem);
10799 AddItemDurations(pItem);
10801 uint8 bag = pos >> 8;
10802 uint8 slot = pos & 255;
10804 Item *pItem2 = GetItemByPos( bag, slot );
10806 if( !pItem2 )
10808 VisualizeItem( slot, pItem);
10810 if(isAlive())
10812 ItemPrototype const *pProto = pItem->GetProto();
10814 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10815 if(pProto && pProto->ItemSet)
10816 AddItemsSetItem(this, pItem);
10818 _ApplyItemMods(pItem, slot, true);
10820 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10822 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10824 if (getClass() == CLASS_ROGUE)
10825 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10827 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10829 if (!spellProto)
10830 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10831 else
10833 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10835 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10836 data << uint64(GetGUID());
10837 data << uint8(1);
10838 data << uint32(cooldownSpell);
10839 data << uint32(0);
10840 GetSession()->SendPacket(&data);
10845 if( IsInWorld() && update )
10847 pItem->AddToWorld();
10848 pItem->SendCreateUpdateToPlayer( this );
10851 ApplyEquipCooldown(pItem);
10853 if( slot == EQUIPMENT_SLOT_MAINHAND )
10855 UpdateExpertise(BASE_ATTACK);
10856 UpdateArmorPenetration();
10858 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10860 UpdateExpertise(OFF_ATTACK);
10861 UpdateArmorPenetration();
10864 else
10866 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10867 if( IsInWorld() && update )
10868 pItem2->SendCreateUpdateToPlayer( this );
10870 // delete item (it not in any slot currently)
10871 //pItem->DeleteFromDB();
10872 if( IsInWorld() && update )
10874 pItem->RemoveFromWorld();
10875 pItem->DestroyForPlayer( this );
10878 RemoveEnchantmentDurations(pItem);
10879 RemoveItemDurations(pItem);
10881 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10882 pItem->SetState(ITEM_REMOVED, this);
10883 pItem2->SetState(ITEM_CHANGED, this);
10885 ApplyEquipCooldown(pItem2);
10887 return pItem2;
10890 // only for full equip instead adding to stack
10891 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10892 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10894 return pItem;
10897 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10899 if( pItem )
10901 AddEnchantmentDurations(pItem);
10902 AddItemDurations(pItem);
10904 uint8 slot = pos & 255;
10905 VisualizeItem( slot, pItem);
10907 if( IsInWorld() )
10909 pItem->AddToWorld();
10910 pItem->SendCreateUpdateToPlayer( this );
10913 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10914 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
10918 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10920 if(pItem)
10922 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10923 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10924 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10926 else
10928 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10929 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10933 void Player::VisualizeItem( uint8 slot, Item *pItem)
10935 if(!pItem)
10936 return;
10938 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10939 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10940 pItem->SetBinding( true );
10942 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10944 m_items[slot] = pItem;
10945 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10946 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10947 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10948 pItem->SetSlot( slot );
10949 pItem->SetContainer( NULL );
10951 if( slot < EQUIPMENT_SLOT_END )
10952 SetVisibleItemSlot(slot, pItem);
10954 pItem->SetState(ITEM_CHANGED, this);
10957 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10959 // note: removeitem does not actually change the item
10960 // it only takes the item out of storage temporarily
10961 // note2: if removeitem is to be used for delinking
10962 // the item must be removed from the player's updatequeue
10964 Item *pItem = GetItemByPos( bag, slot );
10965 if( pItem )
10967 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10969 RemoveEnchantmentDurations(pItem);
10970 RemoveItemDurations(pItem);
10972 if( bag == INVENTORY_SLOT_BAG_0 )
10974 if ( slot < INVENTORY_SLOT_BAG_END )
10976 ItemPrototype const *pProto = pItem->GetProto();
10977 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10979 if(pProto && pProto->ItemSet)
10980 RemoveItemsSetItem(this, pProto);
10982 _ApplyItemMods(pItem, slot, false);
10984 // remove item dependent auras and casts (only weapon and armor slots)
10985 if(slot < EQUIPMENT_SLOT_END)
10987 RemoveItemDependentAurasAndCasts(pItem);
10989 // remove held enchantments, update expertise
10990 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10992 if (pItem->GetItemSuffixFactor())
10994 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10995 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10997 else
10999 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
11000 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
11003 UpdateExpertise(BASE_ATTACK);
11004 UpdateArmorPenetration();
11006 else if( slot == EQUIPMENT_SLOT_OFFHAND )
11008 UpdateExpertise(OFF_ATTACK);
11009 UpdateArmorPenetration();
11013 // need update known currency
11014 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
11015 UpdateKnownCurrencies(pItem->GetEntry(), false);
11017 m_items[slot] = NULL;
11018 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
11020 if ( slot < EQUIPMENT_SLOT_END )
11021 SetVisibleItemSlot(slot, NULL);
11023 else
11025 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
11026 if( pBag )
11027 pBag->RemoveItem(slot, update);
11029 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
11030 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
11031 pItem->SetSlot( NULL_SLOT );
11032 if( IsInWorld() && update )
11033 pItem->SendCreateUpdateToPlayer( this );
11037 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
11038 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
11040 if(Item* it = GetItemByPos(bag,slot))
11042 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
11043 RemoveItem(bag, slot, update);
11044 it->RemoveFromUpdateQueueOf(this);
11045 if(it->IsInWorld())
11047 it->RemoveFromWorld();
11048 it->DestroyForPlayer( this );
11053 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
11054 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
11056 // update quest counters
11057 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
11058 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
11060 // store item
11061 Item* pLastItem = StoreItem(dest, pItem, update);
11063 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
11064 if(pLastItem == pItem)
11066 // update owner for last item (this can be original item with wrong owner
11067 if(pLastItem->GetOwnerGUID() != GetGUID())
11068 pLastItem->SetOwnerGUID(GetGUID());
11070 // if this original item then it need create record in inventory
11071 // in case trade we already have item in other player inventory
11072 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
11076 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
11078 Item *pItem = GetItemByPos( bag, slot );
11079 if( pItem )
11081 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
11083 // start from destroy contained items (only equipped bag can have its)
11084 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
11086 for (int i = 0; i < MAX_BAG_SIZE; ++i)
11087 DestroyItem(slot, i, update);
11090 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
11091 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
11093 RemoveEnchantmentDurations(pItem);
11094 RemoveItemDurations(pItem);
11096 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
11098 if( bag == INVENTORY_SLOT_BAG_0 )
11100 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
11102 // equipment and equipped bags can have applied bonuses
11103 if ( slot < INVENTORY_SLOT_BAG_END )
11105 ItemPrototype const *pProto = pItem->GetProto();
11107 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11108 if(pProto && pProto->ItemSet)
11109 RemoveItemsSetItem(this, pProto);
11111 _ApplyItemMods(pItem, slot, false);
11114 if ( slot < EQUIPMENT_SLOT_END )
11116 // remove item dependent auras and casts (only weapon and armor slots)
11117 RemoveItemDependentAurasAndCasts(pItem);
11119 // update expertise
11120 if( slot == EQUIPMENT_SLOT_MAINHAND )
11122 UpdateExpertise(BASE_ATTACK);
11123 UpdateArmorPenetration();
11125 else if( slot == EQUIPMENT_SLOT_OFFHAND )
11127 UpdateExpertise(OFF_ATTACK);
11128 UpdateArmorPenetration();
11131 // equipment visual show
11132 SetVisibleItemSlot(slot, NULL);
11134 // need update known currency
11135 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
11136 UpdateKnownCurrencies(pItem->GetEntry(), false);
11138 m_items[slot] = NULL;
11140 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
11141 pBag->RemoveItem(slot, update);
11143 if( IsInWorld() && update )
11145 pItem->RemoveFromWorld();
11146 pItem->DestroyForPlayer(this);
11149 //pItem->SetOwnerGUID(0);
11150 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
11151 pItem->SetSlot( NULL_SLOT );
11152 pItem->SetState(ITEM_REMOVED, this);
11156 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
11158 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
11159 uint32 remcount = 0;
11161 // in inventory
11162 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11164 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11166 if (pItem->GetEntry() == item)
11168 if (pItem->GetCount() + remcount <= count)
11170 // all items in inventory can unequipped
11171 remcount += pItem->GetCount();
11172 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11174 if (remcount >= count)
11175 return;
11177 else
11179 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11180 pItem->SetCount( pItem->GetCount() - count + remcount );
11181 if (IsInWorld() & update)
11182 pItem->SendCreateUpdateToPlayer( this );
11183 pItem->SetState(ITEM_CHANGED, this);
11184 return;
11190 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11192 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11194 if (pItem->GetEntry() == item)
11196 if (pItem->GetCount() + remcount <= count)
11198 // all keys can be unequipped
11199 remcount += pItem->GetCount();
11200 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11202 if (remcount >= count)
11203 return;
11205 else
11207 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11208 pItem->SetCount( pItem->GetCount() - count + remcount );
11209 if (IsInWorld() & update)
11210 pItem->SendCreateUpdateToPlayer( this );
11211 pItem->SetState(ITEM_CHANGED, this);
11212 return;
11218 // in inventory bags
11219 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11221 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11223 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11225 if(Item* pItem = pBag->GetItemByPos(j))
11227 if (pItem->GetEntry() == item)
11229 // all items in bags can be unequipped
11230 if (pItem->GetCount() + remcount <= count)
11232 remcount += pItem->GetCount();
11233 DestroyItem( i, j, update );
11235 if (remcount >= count)
11236 return;
11238 else
11240 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11241 pItem->SetCount( pItem->GetCount() - count + remcount );
11242 if (IsInWorld() && update)
11243 pItem->SendCreateUpdateToPlayer( this );
11244 pItem->SetState(ITEM_CHANGED, this);
11245 return;
11253 // in equipment and bag list
11254 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11256 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11258 if (pItem && pItem->GetEntry() == item)
11260 if (pItem->GetCount() + remcount <= count)
11262 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
11264 remcount += pItem->GetCount();
11265 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11267 if (remcount >= count)
11268 return;
11271 else
11273 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11274 pItem->SetCount( pItem->GetCount() - count + remcount );
11275 if (IsInWorld() & update)
11276 pItem->SendCreateUpdateToPlayer( this );
11277 pItem->SetState(ITEM_CHANGED, this);
11278 return;
11285 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11287 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11289 // in inventory
11290 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11291 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11292 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11293 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11295 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11296 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11297 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11298 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11300 // in inventory bags
11301 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11302 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11303 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11304 if (Item* pItem = pBag->GetItemByPos(j))
11305 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11306 DestroyItem(i, j, update);
11308 // in equipment and bag list
11309 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11310 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11311 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11312 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11315 void Player::DestroyConjuredItems( bool update )
11317 // used when entering arena
11318 // destroys all conjured items
11319 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11321 // in inventory
11322 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11323 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11324 if (pItem->IsConjuredConsumable())
11325 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11327 // in inventory bags
11328 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11329 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11330 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11331 if (Item* pItem = pBag->GetItemByPos(j))
11332 if (pItem->IsConjuredConsumable())
11333 DestroyItem( i, j, update);
11335 // in equipment and bag list
11336 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11337 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11338 if (pItem->IsConjuredConsumable())
11339 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11342 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11344 if(!pItem)
11345 return;
11347 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11349 if( pItem->GetCount() <= count )
11351 count -= pItem->GetCount();
11353 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11355 else
11357 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11358 pItem->SetCount( pItem->GetCount() - count );
11359 count = 0;
11360 if( IsInWorld() & update )
11361 pItem->SendCreateUpdateToPlayer( this );
11362 pItem->SetState(ITEM_CHANGED, this);
11366 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11368 uint8 srcbag = src >> 8;
11369 uint8 srcslot = src & 255;
11371 uint8 dstbag = dst >> 8;
11372 uint8 dstslot = dst & 255;
11374 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11375 if( !pSrcItem )
11377 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11378 return;
11381 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11383 //best error message found for attempting to split while looting
11384 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11385 return;
11388 // not let split all items (can be only at cheating)
11389 if(pSrcItem->GetCount() == count)
11391 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11392 return;
11395 // not let split more existed items (can be only at cheating)
11396 if(pSrcItem->GetCount() < count)
11398 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11399 return;
11402 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11403 Item *pNewItem = pSrcItem->CloneItem( count, this );
11404 if( !pNewItem )
11406 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11407 return;
11410 if( IsInventoryPos( dst ) )
11412 // change item amount before check (for unique max count check)
11413 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11415 ItemPosCountVec dest;
11416 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11417 if( msg != EQUIP_ERR_OK )
11419 delete pNewItem;
11420 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11421 SendEquipError( msg, pSrcItem, NULL );
11422 return;
11425 if( IsInWorld() )
11426 pSrcItem->SendCreateUpdateToPlayer( this );
11427 pSrcItem->SetState(ITEM_CHANGED, this);
11428 StoreItem( dest, pNewItem, true);
11430 else if( IsBankPos ( dst ) )
11432 // change item amount before check (for unique max count check)
11433 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11435 ItemPosCountVec dest;
11436 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11437 if( msg != EQUIP_ERR_OK )
11439 delete pNewItem;
11440 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11441 SendEquipError( msg, pSrcItem, NULL );
11442 return;
11445 if( IsInWorld() )
11446 pSrcItem->SendCreateUpdateToPlayer( this );
11447 pSrcItem->SetState(ITEM_CHANGED, this);
11448 BankItem( dest, pNewItem, true);
11450 else if( IsEquipmentPos ( dst ) )
11452 // change item amount before check (for unique max count check), provide space for splitted items
11453 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11455 uint16 dest;
11456 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11457 if( msg != EQUIP_ERR_OK )
11459 delete pNewItem;
11460 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11461 SendEquipError( msg, pSrcItem, NULL );
11462 return;
11465 if( IsInWorld() )
11466 pSrcItem->SendCreateUpdateToPlayer( this );
11467 pSrcItem->SetState(ITEM_CHANGED, this);
11468 EquipItem( dest, pNewItem, true);
11469 AutoUnequipOffhandIfNeed();
11473 void Player::SwapItem( uint16 src, uint16 dst )
11475 uint8 srcbag = src >> 8;
11476 uint8 srcslot = src & 255;
11478 uint8 dstbag = dst >> 8;
11479 uint8 dstslot = dst & 255;
11481 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11482 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11484 if (!pSrcItem)
11485 return;
11487 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11489 if (!isAlive())
11491 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11492 return;
11495 // SRC checks
11497 // check unequip potability for equipped items and bank bags
11498 if (IsEquipmentPos(src) || IsBagPos(src))
11500 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11501 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11502 if (msg != EQUIP_ERR_OK)
11504 SendEquipError( msg, pSrcItem, pDstItem );
11505 return;
11509 // prevent put equipped/bank bag in self
11510 if (IsBagPos(src) && srcslot == dstbag)
11512 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11513 return;
11516 // prevent put equipped/bank bag in self
11517 if (IsBagPos(dst) && dstslot == srcbag)
11519 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11520 return;
11523 // DST checks
11525 if (pDstItem)
11527 // check unequip potability for equipped items and bank bags
11528 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11530 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11531 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11532 if(msg != EQUIP_ERR_OK)
11534 SendEquipError( msg, pSrcItem, pDstItem );
11535 return;
11540 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11541 // or swap empty bag with another empty or not empty bag (with items exchange)
11543 // Move case
11544 if( !pDstItem )
11546 if( IsInventoryPos( dst ) )
11548 ItemPosCountVec dest;
11549 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11550 if( msg != EQUIP_ERR_OK )
11552 SendEquipError( msg, pSrcItem, NULL );
11553 return;
11556 RemoveItem(srcbag, srcslot, true);
11557 StoreItem( dest, pSrcItem, true);
11559 else if( IsBankPos ( dst ) )
11561 ItemPosCountVec dest;
11562 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11563 if( msg != EQUIP_ERR_OK )
11565 SendEquipError( msg, pSrcItem, NULL );
11566 return;
11569 RemoveItem(srcbag, srcslot, true);
11570 BankItem( dest, pSrcItem, true);
11572 else if( IsEquipmentPos ( dst ) )
11574 uint16 dest;
11575 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11576 if( msg != EQUIP_ERR_OK )
11578 SendEquipError( msg, pSrcItem, NULL );
11579 return;
11582 RemoveItem(srcbag, srcslot, true);
11583 EquipItem(dest, pSrcItem, true);
11584 AutoUnequipOffhandIfNeed();
11587 return;
11590 // attempt merge to / fill target item
11591 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11593 uint8 msg;
11594 ItemPosCountVec sDest;
11595 uint16 eDest;
11596 if( IsInventoryPos( dst ) )
11597 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11598 else if( IsBankPos ( dst ) )
11599 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11600 else if( IsEquipmentPos ( dst ) )
11601 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11602 else
11603 return;
11605 // can be merge/fill
11606 if(msg == EQUIP_ERR_OK)
11608 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11610 RemoveItem(srcbag, srcslot, true);
11612 if( IsInventoryPos( dst ) )
11613 StoreItem( sDest, pSrcItem, true);
11614 else if( IsBankPos ( dst ) )
11615 BankItem( sDest, pSrcItem, true);
11616 else if( IsEquipmentPos ( dst ) )
11618 EquipItem( eDest, pSrcItem, true);
11619 AutoUnequipOffhandIfNeed();
11622 else
11624 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11625 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11626 pSrcItem->SetState(ITEM_CHANGED, this);
11627 pDstItem->SetState(ITEM_CHANGED, this);
11628 if( IsInWorld() )
11630 pSrcItem->SendCreateUpdateToPlayer( this );
11631 pDstItem->SendCreateUpdateToPlayer( this );
11634 return;
11638 // impossible merge/fill, do real swap
11639 uint8 msg;
11641 // check src->dest move possibility
11642 ItemPosCountVec sDest;
11643 uint16 eDest = 0;
11644 if( IsInventoryPos( dst ) )
11645 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11646 else if( IsBankPos( dst ) )
11647 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11648 else if( IsEquipmentPos( dst ) )
11650 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11651 if( msg == EQUIP_ERR_OK )
11652 msg = CanUnequipItem( eDest, true );
11655 if( msg != EQUIP_ERR_OK )
11657 SendEquipError( msg, pSrcItem, pDstItem );
11658 return;
11661 // check dest->src move possibility
11662 ItemPosCountVec sDest2;
11663 uint16 eDest2 = 0;
11664 if( IsInventoryPos( src ) )
11665 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11666 else if( IsBankPos( src ) )
11667 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11668 else if( IsEquipmentPos( src ) )
11670 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11671 if( msg == EQUIP_ERR_OK )
11672 msg = CanUnequipItem( eDest2, true);
11675 if( msg != EQUIP_ERR_OK )
11677 SendEquipError( msg, pDstItem, pSrcItem );
11678 return;
11681 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11682 if(pSrcItem->IsBag() && pDstItem->IsBag())
11684 Bag* emptyBag = NULL;
11685 Bag* fullBag = NULL;
11686 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11688 emptyBag = (Bag*)pSrcItem;
11689 fullBag = (Bag*)pDstItem;
11691 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11693 emptyBag = (Bag*)pDstItem;
11694 fullBag = (Bag*)pSrcItem;
11697 // bag swap (with items exchange) case
11698 if(emptyBag && fullBag)
11700 ItemPrototype const* emotyProto = emptyBag->GetProto();
11702 uint32 count = 0;
11704 for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
11706 Item *bagItem = fullBag->GetItemByPos(i);
11707 if (!bagItem)
11708 continue;
11710 ItemPrototype const* bagItemProto = bagItem->GetProto();
11711 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11713 // one from items not go to empty target bag
11714 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11715 return;
11718 ++count;
11722 if (count > emptyBag->GetBagSize())
11724 // too small targeted bag
11725 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11726 return;
11729 // Items swap
11730 count = 0; // will pos in new bag
11731 for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
11733 Item *bagItem = fullBag->GetItemByPos(i);
11734 if (!bagItem)
11735 continue;
11737 fullBag->RemoveItem(i, true);
11738 emptyBag->StoreItem(count, bagItem, true);
11739 bagItem->SetState(ITEM_CHANGED, this);
11741 ++count;
11746 // now do moves, remove...
11747 RemoveItem(dstbag, dstslot, false);
11748 RemoveItem(srcbag, srcslot, false);
11750 // add to dest
11751 if (IsInventoryPos(dst))
11752 StoreItem(sDest, pSrcItem, true);
11753 else if (IsBankPos(dst))
11754 BankItem(sDest, pSrcItem, true);
11755 else if (IsEquipmentPos(dst))
11756 EquipItem(eDest, pSrcItem, true);
11758 // add to src
11759 if (IsInventoryPos(src))
11760 StoreItem(sDest2, pDstItem, true);
11761 else if (IsBankPos(src))
11762 BankItem(sDest2, pDstItem, true);
11763 else if (IsEquipmentPos(src))
11764 EquipItem(eDest2, pDstItem, true);
11766 AutoUnequipOffhandIfNeed();
11769 void Player::AddItemToBuyBackSlot( Item *pItem )
11771 if (pItem)
11773 uint32 slot = m_currentBuybackSlot;
11774 // if current back slot non-empty search oldest or free
11775 if (m_items[slot])
11777 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11778 uint32 oldest_slot = BUYBACK_SLOT_START;
11780 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11782 // found empty
11783 if (!m_items[i])
11785 slot = i;
11786 break;
11789 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11791 if (oldest_time > i_time)
11793 oldest_time = i_time;
11794 oldest_slot = i;
11798 // find oldest
11799 slot = oldest_slot;
11802 RemoveItemFromBuyBackSlot( slot, true );
11803 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11805 m_items[slot] = pItem;
11806 time_t base = time(NULL);
11807 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11808 uint32 eslot = slot - BUYBACK_SLOT_START;
11810 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11811 if (ItemPrototype const *pProto = pItem->GetProto())
11812 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11813 else
11814 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11815 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11817 // move to next (for non filled list is move most optimized choice)
11818 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11819 ++m_currentBuybackSlot;
11823 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11825 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11826 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11827 return m_items[slot];
11828 return NULL;
11831 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11833 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11834 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11836 Item *pItem = m_items[slot];
11837 if (pItem)
11839 pItem->RemoveFromWorld();
11840 if(del) pItem->SetState(ITEM_REMOVED, this);
11843 m_items[slot] = NULL;
11845 uint32 eslot = slot - BUYBACK_SLOT_START;
11846 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11847 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11848 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11850 // if current backslot is filled set to now free slot
11851 if (m_items[m_currentBuybackSlot])
11852 m_currentBuybackSlot = slot;
11856 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ )
11858 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11859 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11860 data << uint8(msg);
11862 if (msg != EQUIP_ERR_OK)
11864 data << uint64(pItem ? pItem->GetGUID() : 0);
11865 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11866 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11868 switch(msg)
11870 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11871 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11873 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11874 data << uint32(proto ? proto->RequiredLevel : 0);
11875 break;
11877 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11879 data << uint64(0);
11880 data << uint32(0);
11881 data << uint64(0);
11882 break;
11884 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11885 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11886 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11888 ItemPrototype const* proto = pItem ? pItem->GetProto() : sObjectMgr.GetItemPrototype(itemid);
11889 data << uint32(proto ? proto->ItemLimitCategory : 0);
11890 break;
11892 default:
11893 break;
11896 GetSession()->SendPacket(&data);
11899 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11901 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11902 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11903 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11904 data << uint32(item);
11905 if (param > 0)
11906 data << uint32(param);
11907 data << uint8(msg);
11908 GetSession()->SendPacket(&data);
11911 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11913 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11914 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11915 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11916 data << uint64(guid);
11917 if (param > 0)
11918 data << uint32(param);
11919 data << uint8(msg);
11920 GetSession()->SendPacket(&data);
11923 void Player::ClearTrade()
11925 tradeGold = 0;
11926 acceptTrade = false;
11927 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11928 tradeItems[i] = NULL_SLOT;
11931 void Player::TradeCancel(bool sendback)
11933 if (pTrader)
11935 // send yellow "Trade canceled" message to both traders
11936 WorldSession* ws;
11937 ws = GetSession();
11938 if (sendback)
11939 ws->SendCancelTrade();
11940 ws = pTrader->GetSession();
11941 if (!ws->PlayerLogout())
11942 ws->SendCancelTrade();
11944 // cleanup
11945 ClearTrade();
11946 pTrader->ClearTrade();
11947 // prevent loss of reference
11948 pTrader->pTrader = NULL;
11949 pTrader = NULL;
11953 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11955 if (m_itemDuration.empty())
11956 return;
11958 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11960 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11962 Item* item = *itr;
11963 ++itr; // current element can be erased in UpdateDuration
11965 if ((realtimeonly && (item->GetProto()->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)) || !realtimeonly)
11966 item->UpdateDuration(this,time);
11970 void Player::UpdateEnchantTime(uint32 time)
11972 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11974 ASSERT(itr->item);
11975 next = itr;
11976 if (!itr->item->GetEnchantmentId(itr->slot))
11978 next = m_enchantDuration.erase(itr);
11980 else if (itr->leftduration <= time)
11982 ApplyEnchantment(itr->item, itr->slot, false, false);
11983 itr->item->ClearEnchantment(itr->slot);
11984 next = m_enchantDuration.erase(itr);
11986 else if (itr->leftduration > time)
11988 itr->leftduration -= time;
11989 ++next;
11994 void Player::AddEnchantmentDurations(Item *item)
11996 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11998 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11999 continue;
12001 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
12002 if (duration > 0)
12003 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
12007 void Player::RemoveEnchantmentDurations(Item *item)
12009 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
12011 if (itr->item == item)
12013 // save duration in item
12014 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
12015 itr = m_enchantDuration.erase(itr);
12017 else
12018 ++itr;
12022 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
12024 // remove enchantments from equipped items first to clean up the m_enchantDuration list
12025 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
12027 next = itr;
12028 if (itr->slot == slot)
12030 if (itr->item && itr->item->GetEnchantmentId(slot))
12032 // remove from stats
12033 ApplyEnchantment(itr->item, slot, false, false);
12034 // remove visual
12035 itr->item->ClearEnchantment(slot);
12037 // remove from update list
12038 next = m_enchantDuration.erase(itr);
12040 else
12041 ++next;
12044 // remove enchants from inventory items
12045 // NOTE: no need to remove these from stats, since these aren't equipped
12046 // in inventory
12047 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
12048 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
12049 if (pItem->GetEnchantmentId(slot))
12050 pItem->ClearEnchantment(slot);
12052 // in inventory bags
12053 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
12054 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
12055 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
12056 if (Item* pItem = pBag->GetItemByPos(j))
12057 if (pItem->GetEnchantmentId(slot))
12058 pItem->ClearEnchantment(slot);
12061 // duration == 0 will remove item enchant
12062 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
12064 if (!item)
12065 return;
12067 if (slot >= MAX_ENCHANTMENT_SLOT)
12068 return;
12070 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12072 if (itr->item == item && itr->slot == slot)
12074 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
12075 m_enchantDuration.erase(itr);
12076 break;
12079 if (item && duration > 0 )
12081 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
12082 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
12086 void Player::ApplyEnchantment(Item *item,bool apply)
12088 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
12089 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
12092 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
12094 if (!item)
12095 return;
12097 if (!item->IsEquipped())
12098 return;
12100 if (slot >= MAX_ENCHANTMENT_SLOT)
12101 return;
12103 uint32 enchant_id = item->GetEnchantmentId(slot);
12104 if (!enchant_id)
12105 return;
12107 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
12108 if (!pEnchant)
12109 return;
12111 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
12112 return;
12114 if (!item->IsBroken())
12116 for (int s = 0; s < 3; ++s)
12118 uint32 enchant_display_type = pEnchant->type[s];
12119 uint32 enchant_amount = pEnchant->amount[s];
12120 uint32 enchant_spell_id = pEnchant->spellid[s];
12122 switch(enchant_display_type)
12124 case ITEM_ENCHANTMENT_TYPE_NONE:
12125 break;
12126 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
12127 // processed in Player::CastItemCombatSpell
12128 break;
12129 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
12130 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12131 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
12132 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
12133 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
12134 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
12135 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12136 break;
12137 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
12138 if (enchant_spell_id)
12140 if (apply)
12142 int32 basepoints = 0;
12143 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12144 if (item->GetItemRandomPropertyId())
12146 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12147 if (item_rand)
12149 // Search enchant_amount
12150 for (int k = 0; k < 3; ++k)
12152 if(item_rand->enchant_id[k] == enchant_id)
12154 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12155 break;
12160 // Cast custom spell vs all equal basepoints getted from enchant_amount
12161 if (basepoints)
12162 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
12163 else
12164 CastSpell(this, enchant_spell_id, true, item);
12166 else
12167 RemoveAurasDueToItemSpell(item, enchant_spell_id);
12169 break;
12170 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
12171 if (!enchant_amount)
12173 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12174 if(item_rand)
12176 for (int k = 0; k < 3; ++k)
12178 if(item_rand->enchant_id[k] == enchant_id)
12180 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12181 break;
12187 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
12188 break;
12189 case ITEM_ENCHANTMENT_TYPE_STAT:
12191 if (!enchant_amount)
12193 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
12194 if(item_rand_suffix)
12196 for (int k = 0; k < 3; ++k)
12198 if(item_rand_suffix->enchant_id[k] == enchant_id)
12200 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
12201 break;
12207 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
12208 switch (enchant_spell_id)
12210 case ITEM_MOD_MANA:
12211 sLog.outDebug("+ %u MANA",enchant_amount);
12212 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
12213 break;
12214 case ITEM_MOD_HEALTH:
12215 sLog.outDebug("+ %u HEALTH",enchant_amount);
12216 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
12217 break;
12218 case ITEM_MOD_AGILITY:
12219 sLog.outDebug("+ %u AGILITY",enchant_amount);
12220 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
12221 ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply);
12222 break;
12223 case ITEM_MOD_STRENGTH:
12224 sLog.outDebug("+ %u STRENGTH",enchant_amount);
12225 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
12226 ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply);
12227 break;
12228 case ITEM_MOD_INTELLECT:
12229 sLog.outDebug("+ %u INTELLECT",enchant_amount);
12230 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
12231 ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply);
12232 break;
12233 case ITEM_MOD_SPIRIT:
12234 sLog.outDebug("+ %u SPIRIT",enchant_amount);
12235 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
12236 ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply);
12237 break;
12238 case ITEM_MOD_STAMINA:
12239 sLog.outDebug("+ %u STAMINA",enchant_amount);
12240 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
12241 ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply);
12242 break;
12243 case ITEM_MOD_DEFENSE_SKILL_RATING:
12244 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
12245 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12246 break;
12247 case ITEM_MOD_DODGE_RATING:
12248 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12249 sLog.outDebug("+ %u DODGE", enchant_amount);
12250 break;
12251 case ITEM_MOD_PARRY_RATING:
12252 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12253 sLog.outDebug("+ %u PARRY", enchant_amount);
12254 break;
12255 case ITEM_MOD_BLOCK_RATING:
12256 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12257 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12258 break;
12259 case ITEM_MOD_HIT_MELEE_RATING:
12260 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12261 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12262 break;
12263 case ITEM_MOD_HIT_RANGED_RATING:
12264 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12265 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12266 break;
12267 case ITEM_MOD_HIT_SPELL_RATING:
12268 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12269 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12270 break;
12271 case ITEM_MOD_CRIT_MELEE_RATING:
12272 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12273 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12274 break;
12275 case ITEM_MOD_CRIT_RANGED_RATING:
12276 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12277 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12278 break;
12279 case ITEM_MOD_CRIT_SPELL_RATING:
12280 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12281 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12282 break;
12283 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12284 // in Enchantments
12285 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12286 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12287 // break;
12288 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12289 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12290 // break;
12291 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12292 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12293 // break;
12294 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12295 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12296 // break;
12297 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12298 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12299 // break;
12300 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12301 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12302 // break;
12303 // case ITEM_MOD_HASTE_MELEE_RATING:
12304 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12305 // break;
12306 // case ITEM_MOD_HASTE_RANGED_RATING:
12307 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12308 // break;
12309 case ITEM_MOD_HASTE_SPELL_RATING:
12310 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12311 break;
12312 case ITEM_MOD_HIT_RATING:
12313 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12314 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12315 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12316 sLog.outDebug("+ %u HIT", enchant_amount);
12317 break;
12318 case ITEM_MOD_CRIT_RATING:
12319 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12320 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12321 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12322 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12323 break;
12324 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12325 // case ITEM_MOD_HIT_TAKEN_RATING:
12326 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12327 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12328 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12329 // break;
12330 // case ITEM_MOD_CRIT_TAKEN_RATING:
12331 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12332 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12333 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12334 // break;
12335 case ITEM_MOD_RESILIENCE_RATING:
12336 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12337 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12338 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12339 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12340 break;
12341 case ITEM_MOD_HASTE_RATING:
12342 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12343 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12344 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12345 sLog.outDebug("+ %u HASTE", enchant_amount);
12346 break;
12347 case ITEM_MOD_EXPERTISE_RATING:
12348 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12349 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12350 break;
12351 case ITEM_MOD_ATTACK_POWER:
12352 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12353 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12354 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12355 break;
12356 case ITEM_MOD_RANGED_ATTACK_POWER:
12357 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12358 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12359 break;
12360 case ITEM_MOD_MANA_REGENERATION:
12361 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12362 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12363 break;
12364 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12365 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12366 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12367 break;
12368 case ITEM_MOD_SPELL_POWER:
12369 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12370 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12371 break;
12372 case ITEM_MOD_BLOCK_VALUE:
12373 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply);
12374 break;
12375 case ITEM_MOD_FERAL_ATTACK_POWER:
12376 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12377 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12378 default:
12379 break;
12381 break;
12383 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12385 if(getClass() == CLASS_SHAMAN)
12387 float addValue = 0.0f;
12388 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12390 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12391 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12393 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12395 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12396 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12399 break;
12401 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12402 // processed in Player::CastItemUseSpell
12403 break;
12404 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12405 // nothing do..
12406 break;
12407 default:
12408 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12409 break;
12410 } /*switch(enchant_display_type)*/
12411 } /*for*/
12414 // visualize enchantment at player and equipped items
12415 if(slot == PERM_ENCHANTMENT_SLOT)
12416 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12418 if(slot == TEMP_ENCHANTMENT_SLOT)
12419 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12422 if(apply_dur)
12424 if(apply)
12426 // set duration
12427 uint32 duration = item->GetEnchantmentDuration(slot);
12428 if(duration > 0)
12429 AddEnchantmentDuration(item, slot, duration);
12431 else
12433 // duration == 0 will remove EnchantDuration
12434 AddEnchantmentDuration(item, slot, 0);
12439 void Player::SendEnchantmentDurations()
12441 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12443 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12447 void Player::SendItemDurations()
12449 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12451 (*itr)->SendTimeUpdate(this);
12455 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12457 if(!item) // prevent crash
12458 return;
12460 // last check 2.0.10
12461 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12462 data << uint64(GetGUID()); // player GUID
12463 data << uint32(received); // 0=looted, 1=from npc
12464 data << uint32(created); // 0=received, 1=created
12465 data << uint32(1); // IsShowChatMessage
12466 data << uint8(item->GetBagSlot()); // bagslot
12467 // item slot, but when added to stack: 0xFFFFFFFF
12468 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12469 data << uint32(item->GetEntry()); // item id
12470 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12471 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12472 data << uint32(count); // count of items
12473 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12475 if (broadcast && GetGroup())
12476 GetGroup()->BroadcastPacket(&data, true);
12477 else
12478 GetSession()->SendPacket(&data);
12481 /*********************************************************/
12482 /*** GOSSIP SYSTEM ***/
12483 /*********************************************************/
12485 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12487 PlayerMenu* pMenu = PlayerTalkClass;
12488 pMenu->ClearMenus();
12490 pMenu->GetGossipMenu().SetMenuId(menuId);
12492 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12494 // if default menuId and no menu options exist for this, use options from default options
12495 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12496 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12498 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12500 bool bCanTalk = true;
12502 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12503 continue;
12505 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12506 continue;
12508 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12509 continue;
12511 if (pSource->GetTypeId() == TYPEID_UNIT)
12513 Creature *pCreature = (Creature*)pSource;
12515 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12517 if (!(itr->second.npc_option_npcflag & npcflags))
12518 continue;
12520 switch(itr->second.option_id)
12522 case GOSSIP_OPTION_QUESTGIVER:
12523 PrepareQuestMenu(pSource->GetGUID());
12524 bCanTalk = false;
12525 break;
12526 case GOSSIP_OPTION_ARMORER:
12527 bCanTalk = false; // added in special mode
12528 break;
12529 case GOSSIP_OPTION_SPIRITHEALER:
12530 if (!isDead())
12531 bCanTalk = false;
12532 break;
12533 case GOSSIP_OPTION_VENDOR:
12535 VendorItemData const* vItems = pCreature->GetVendorItems();
12536 if (!vItems || vItems->Empty())
12538 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12539 bCanTalk = false;
12541 break;
12543 case GOSSIP_OPTION_TRAINER:
12544 if (!pCreature->isCanTrainingOf(this, false))
12545 bCanTalk = false;
12546 break;
12547 case GOSSIP_OPTION_UNLEARNTALENTS:
12548 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12549 bCanTalk = false;
12550 break;
12551 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12552 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12553 bCanTalk = false;
12554 break;
12555 case GOSSIP_OPTION_TAXIVENDOR:
12556 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12557 return;
12558 break;
12559 case GOSSIP_OPTION_BATTLEFIELD:
12560 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12561 bCanTalk = false;
12562 break;
12563 case GOSSIP_OPTION_STABLEPET:
12564 if (getClass() != CLASS_HUNTER)
12565 bCanTalk = false;
12566 break;
12567 case GOSSIP_OPTION_GOSSIP:
12568 case GOSSIP_OPTION_SPIRITGUIDE:
12569 case GOSSIP_OPTION_INNKEEPER:
12570 case GOSSIP_OPTION_BANKER:
12571 case GOSSIP_OPTION_PETITIONER:
12572 case GOSSIP_OPTION_TABARDDESIGNER:
12573 case GOSSIP_OPTION_AUCTIONEER:
12574 break; // no checks
12575 default:
12576 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12577 bCanTalk = false;
12578 break;
12581 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12583 GameObject *pGo = (GameObject*)pSource;
12585 switch(itr->second.option_id)
12587 case GOSSIP_OPTION_QUESTGIVER:
12588 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12589 PrepareQuestMenu(pSource->GetGUID());
12590 bCanTalk = false;
12591 break;
12592 case GOSSIP_OPTION_GOSSIP:
12593 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12594 bCanTalk = false;
12595 break;
12596 default:
12597 bCanTalk = false;
12598 break;
12602 if (bCanTalk)
12604 std::string strOptionText = itr->second.option_text;
12605 std::string strBoxText = itr->second.box_text;
12607 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12609 if (loc_idx >= 0)
12611 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12613 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12615 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12616 strOptionText = no->OptionText[loc_idx];
12618 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12619 strBoxText = no->BoxText[loc_idx];
12623 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12624 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12628 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12629 /*if (pMenu->Empty())
12631 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12633 // output error message if need
12634 pCreature->isCanTrainingOf(this, true);
12637 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12639 // output error message if need
12640 pCreature->isCanInteractWithBattleMaster(this, true);
12645 void Player::SendPreparedGossip(WorldObject *pSource)
12647 if (!pSource)
12648 return;
12650 if (pSource->GetTypeId() == TYPEID_UNIT)
12652 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12653 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12655 SendPreparedQuest(pSource->GetGUID());
12656 return;
12659 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12661 // probably need to find a better way here
12662 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12664 SendPreparedQuest(pSource->GetGUID());
12665 return;
12669 // in case non empty gossip menu (that not included quests list size) show it
12670 // (quest entries from quest menu will be included in list)
12672 uint32 textId = GetGossipTextId(pSource);
12674 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12675 textId = GetGossipTextId(menuId);
12677 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12680 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12682 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12684 if (gossipListId >= gossipmenu.MenuItemCount())
12685 return;
12687 // if not same, then something funky is going on
12688 if (menuId != gossipmenu.GetMenuId())
12689 return;
12691 GossipMenuItem const& menu_item = gossipmenu.GetItem(gossipListId);
12693 uint32 gossipOptionId = menu_item.m_gOptionId;
12694 uint64 guid = pSource->GetGUID();
12695 uint32 moneyTake = menu_item.m_gBoxMoney;
12697 // if this function called and player have money for pay MoneyTake or cheating, proccess both cases
12698 if (moneyTake > 0)
12700 if (GetMoney() >= moneyTake)
12701 ModifyMoney(-int32(moneyTake));
12702 else
12703 return; // cheating
12706 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12708 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12710 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12711 return;
12715 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12717 switch(gossipOptionId)
12719 case GOSSIP_OPTION_GOSSIP:
12721 if (pMenuData.m_gAction_poi)
12722 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12724 if (pMenuData.m_gAction_menu)
12726 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12727 SendPreparedGossip(pSource);
12730 if (pMenuData.m_gAction_script)
12732 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12733 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12734 else if (pSource->GetTypeId() == TYPEID_UNIT)
12735 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12738 break;
12740 case GOSSIP_OPTION_SPIRITHEALER:
12741 if (isDead())
12742 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12743 break;
12744 case GOSSIP_OPTION_QUESTGIVER:
12745 PrepareQuestMenu(guid);
12746 SendPreparedQuest(guid);
12747 break;
12748 case GOSSIP_OPTION_VENDOR:
12749 case GOSSIP_OPTION_ARMORER:
12750 GetSession()->SendListInventory(guid);
12751 break;
12752 case GOSSIP_OPTION_STABLEPET:
12753 GetSession()->SendStablePet(guid);
12754 break;
12755 case GOSSIP_OPTION_TRAINER:
12756 GetSession()->SendTrainerList(guid);
12757 break;
12758 case GOSSIP_OPTION_UNLEARNTALENTS:
12759 PlayerTalkClass->CloseGossip();
12760 SendTalentWipeConfirm(guid);
12761 break;
12762 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12763 PlayerTalkClass->CloseGossip();
12764 SendPetSkillWipeConfirm();
12765 break;
12766 case GOSSIP_OPTION_TAXIVENDOR:
12767 GetSession()->SendTaxiMenu(((Creature*)pSource));
12768 break;
12769 case GOSSIP_OPTION_INNKEEPER:
12770 PlayerTalkClass->CloseGossip();
12771 SetBindPoint(guid);
12772 break;
12773 case GOSSIP_OPTION_BANKER:
12774 GetSession()->SendShowBank(guid);
12775 break;
12776 case GOSSIP_OPTION_PETITIONER:
12777 PlayerTalkClass->CloseGossip();
12778 GetSession()->SendPetitionShowList(guid);
12779 break;
12780 case GOSSIP_OPTION_TABARDDESIGNER:
12781 PlayerTalkClass->CloseGossip();
12782 GetSession()->SendTabardVendorActivate(guid);
12783 break;
12784 case GOSSIP_OPTION_AUCTIONEER:
12785 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12786 break;
12787 case GOSSIP_OPTION_SPIRITGUIDE:
12788 PrepareGossipMenu(pSource);
12789 SendPreparedGossip(pSource);
12790 break;
12791 case GOSSIP_OPTION_BATTLEFIELD:
12793 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12795 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12797 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12798 return;
12801 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12802 break;
12807 uint32 Player::GetGossipTextId(WorldObject *pSource)
12809 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12810 return DEFAULT_GOSSIP_MESSAGE;
12812 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12813 return pos;
12815 return DEFAULT_GOSSIP_MESSAGE;
12818 uint32 Player::GetGossipTextId(uint32 menuId)
12820 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12822 if (!menuId)
12823 return textId;
12825 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12827 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12829 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12830 textId = itr->second.text_id;
12833 return textId;
12836 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12838 if (pSource->GetTypeId() == TYPEID_UNIT)
12839 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12840 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12841 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12843 return 0;
12846 /*********************************************************/
12847 /*** QUEST SYSTEM ***/
12848 /*********************************************************/
12850 void Player::PrepareQuestMenu( uint64 guid )
12852 Object *pObject;
12853 QuestRelations* pObjectQR;
12854 QuestRelations* pObjectQIR;
12856 // pets also can have quests
12857 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12859 pObject = (Object*)pCreature;
12860 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12861 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12863 else
12865 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12866 //only for quests which cast teleport spells on player
12867 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12868 ASSERT(_map);
12869 GameObject *pGameObject = _map->GetGameObject(guid);
12870 if( pGameObject )
12872 pObject = (Object*)pGameObject;
12873 pObjectQR = &sObjectMgr.mGOQuestRelations;
12874 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12876 else
12877 return;
12880 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12881 qm.ClearMenu();
12883 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12885 uint32 quest_id = i->second;
12886 QuestStatus status = GetQuestStatus( quest_id );
12887 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12888 qm.AddMenuItem(quest_id, 4);
12889 else if ( status == QUEST_STATUS_INCOMPLETE )
12890 qm.AddMenuItem(quest_id, 4);
12891 else if (status == QUEST_STATUS_AVAILABLE )
12892 qm.AddMenuItem(quest_id, 2);
12895 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12897 uint32 quest_id = i->second;
12898 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12899 if(!pQuest) continue;
12901 QuestStatus status = GetQuestStatus( quest_id );
12903 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12904 qm.AddMenuItem(quest_id, 4);
12905 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12906 qm.AddMenuItem(quest_id, 2);
12910 void Player::SendPreparedQuest(uint64 guid)
12912 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12914 if (questMenu.Empty())
12915 return;
12917 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12919 uint32 icon = qmi0.m_qIcon;
12921 // single element case
12922 if (questMenu.MenuItemCount() == 1)
12924 // Auto open -- maybe also should verify there is no greeting
12925 uint32 quest_id = qmi0.m_qId;
12926 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12928 if (pQuest)
12930 if (icon == 4 && !GetQuestRewardStatus(quest_id))
12931 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12932 else if (icon == 4)
12933 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12934 // Send completable on repeatable and autoCompletable quest if player don't have quest
12935 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12936 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDailyOrWeekly())
12937 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12938 else
12939 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12942 // multiply entries
12943 else
12945 QEmote qe;
12946 qe._Delay = 0;
12947 qe._Emote = 0;
12948 std::string title = "";
12950 // need pet case for some quests
12951 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12953 uint32 textid = GetGossipTextId(pCreature);
12955 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12956 if (!gossiptext)
12958 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12959 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12960 title = "";
12962 else
12964 qe = gossiptext->Options[0].Emotes[0];
12966 if(!gossiptext->Options[0].Text_0.empty())
12968 title = gossiptext->Options[0].Text_0;
12970 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12971 if (loc_idx >= 0)
12973 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12974 if (nl)
12976 if ((int32)nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12977 title = nl->Text_0[0][loc_idx];
12981 else
12983 title = gossiptext->Options[0].Text_1;
12985 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12986 if (loc_idx >= 0)
12988 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12989 if (nl)
12991 if ((int32)nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12992 title = nl->Text_1[0][loc_idx];
12998 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
13002 bool Player::IsActiveQuest( uint32 quest_id ) const
13004 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
13006 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
13009 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
13011 Object *pObject;
13012 QuestRelations* pObjectQR;
13013 QuestRelations* pObjectQIR;
13015 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
13017 pObject = (Object*)pCreature;
13018 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
13019 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
13021 else
13023 //we should obtain map pointer from GetMap() in 99% of cases. Special case
13024 //only for quests which cast teleport spells on player
13025 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
13026 ASSERT(_map);
13027 GameObject *pGameObject = _map->GetGameObject(guid);
13028 if( pGameObject )
13030 pObject = (Object*)pGameObject;
13031 pObjectQR = &sObjectMgr.mGOQuestRelations;
13032 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
13034 else
13035 return NULL;
13038 uint32 nextQuestID = pQuest->GetNextQuestInChain();
13039 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
13041 if (itr->second == nextQuestID)
13042 return sObjectMgr.GetQuestTemplate(nextQuestID);
13045 return NULL;
13048 bool Player::CanSeeStartQuest( Quest const *pQuest )
13050 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
13051 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
13052 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
13053 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) && SatisfyQuestWeek( pQuest, false ) )
13055 return getLevel() + sWorld.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
13058 return false;
13061 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
13063 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
13064 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
13065 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
13066 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
13067 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
13068 && SatisfyQuestDay( pQuest, msg ) && SatisfyQuestWeek( pQuest, msg );
13071 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
13073 if( !SatisfyQuestLog( msg ) )
13074 return false;
13076 uint32 srcitem = pQuest->GetSrcItemId();
13077 if( srcitem > 0 )
13079 uint32 count = pQuest->GetSrcItemCount();
13080 ItemPosCountVec dest;
13081 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13083 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
13084 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13085 return true;
13086 else if( msg2 != EQUIP_ERR_OK )
13088 SendEquipError(msg2, NULL, NULL, srcitem);
13089 return false;
13092 return true;
13095 bool Player::CanCompleteQuest( uint32 quest_id )
13097 if( quest_id )
13099 QuestStatusData& q_status = mQuestStatus[quest_id];
13100 if( q_status.m_status == QUEST_STATUS_COMPLETE )
13101 return false; // not allow re-complete quest
13103 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13105 if(!qInfo)
13106 return false;
13108 // auto complete quest
13109 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
13110 return true;
13112 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13115 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13117 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13119 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
13120 return false;
13124 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13126 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13128 if( qInfo->ReqCreatureOrGOId[i] == 0 )
13129 continue;
13131 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
13132 return false;
13136 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
13137 return false;
13139 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
13140 return false;
13142 if ( qInfo->GetRewOrReqMoney() < 0 )
13144 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
13145 return false;
13148 uint32 repFacId = qInfo->GetRepObjectiveFaction();
13149 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
13150 return false;
13152 return true;
13155 return false;
13158 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
13160 // Solve problem that player don't have the quest and try complete it.
13161 // if repeatable she must be able to complete event if player don't have it.
13162 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13163 if( !CanTakeQuest(pQuest, false) )
13164 return false;
13166 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
13167 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13168 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
13169 return false;
13171 if( !CanRewardQuest(pQuest, false) )
13172 return false;
13174 return true;
13177 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
13179 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13180 if (!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
13181 return false;
13183 // daily quest can't be rewarded (25 daily quest already completed)
13184 if (!SatisfyQuestDay(pQuest,true) || !SatisfyQuestWeek(pQuest,true))
13185 return false;
13187 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13188 if (GetQuestRewardStatus(pQuest->GetQuestId()))
13189 return false;
13191 // prevent receive reward with quest items in bank
13192 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13194 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13196 if( pQuest->ReqItemCount[i] != 0 &&
13197 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
13199 if(msg)
13200 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]);
13201 return false;
13206 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13207 if (pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
13208 return false;
13210 return true;
13213 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
13215 // prevent receive reward with quest items in bank or for not completed quest
13216 if(!CanRewardQuest(pQuest,msg))
13217 return false;
13219 if ( pQuest->GetRewChoiceItemsCount() > 0 )
13221 if( pQuest->RewChoiceItemId[reward] )
13223 ItemPosCountVec dest;
13224 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
13225 if( res != EQUIP_ERR_OK )
13227 SendEquipError( res, NULL, NULL, pQuest->RewChoiceItemId[reward] );
13228 return false;
13233 if ( pQuest->GetRewItemsCount() > 0 )
13235 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13237 if( pQuest->RewItemId[i] )
13239 ItemPosCountVec dest;
13240 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
13241 if( res != EQUIP_ERR_OK )
13243 SendEquipError( res, NULL, NULL );
13244 return false;
13250 return true;
13253 void Player::SendPetTameFailure(PetTameFailureReason reason)
13255 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
13256 data << uint8(reason);
13257 GetSession()->SendPacket(&data);
13260 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
13262 uint16 log_slot = FindQuestSlot( 0 );
13263 ASSERT(log_slot < MAX_QUEST_LOG_SIZE);
13265 uint32 quest_id = pQuest->GetQuestId();
13267 // if not exist then created with set uState==NEW and rewarded=false
13268 QuestStatusData& questStatusData = mQuestStatus[quest_id];
13270 // check for repeatable quests status reset
13271 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13272 questStatusData.m_explored = false;
13274 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13276 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13277 questStatusData.m_itemcount[i] = 0;
13280 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13282 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13283 questStatusData.m_creatureOrGOcount[i] = 0;
13286 GiveQuestSourceItem( pQuest );
13287 AdjustQuestReqItemCount( pQuest, questStatusData );
13289 if( pQuest->GetRepObjectiveFaction() )
13290 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13291 GetReputationMgr().SetVisible(factionEntry);
13293 uint32 qtime = 0;
13294 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13296 uint32 limittime = pQuest->GetLimitTime();
13298 // shared timed quest
13299 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13300 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILLISECONDS;
13302 AddTimedQuest( quest_id );
13303 questStatusData.m_timer = limittime * IN_MILLISECONDS;
13304 qtime = static_cast<uint32>(time(NULL)) + limittime;
13306 else
13307 questStatusData.m_timer = 0;
13309 SetQuestSlot(log_slot, quest_id, qtime);
13311 if (questStatusData.uState != QUEST_NEW)
13312 questStatusData.uState = QUEST_CHANGED;
13314 //starting initial quest script
13315 if(questGiver && pQuest->GetQuestStartScript()!=0)
13316 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13318 // Some spells applied at quest activation
13319 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13320 if(saBounds.first != saBounds.second)
13322 uint32 zone, area;
13323 GetZoneAndAreaId(zone,area);
13325 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13326 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13327 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) )
13328 CastSpell(this,itr->second->spellId,true);
13331 UpdateForQuestWorldObjects();
13334 void Player::CompleteQuest( uint32 quest_id )
13336 if( quest_id )
13338 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13340 uint16 log_slot = FindQuestSlot( quest_id );
13341 if( log_slot < MAX_QUEST_LOG_SIZE)
13342 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13344 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13346 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13347 RewardQuest(qInfo,0,this,false);
13348 else
13349 SendQuestComplete( quest_id );
13354 void Player::IncompleteQuest( uint32 quest_id )
13356 if( quest_id )
13358 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13360 uint16 log_slot = FindQuestSlot( quest_id );
13361 if( log_slot < MAX_QUEST_LOG_SIZE)
13362 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13366 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13368 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13369 //should work fine, cause far teleport will be executed in Player::Update()
13370 SetCanDelayTeleport(true);
13372 uint32 quest_id = pQuest->GetQuestId();
13374 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13376 if (pQuest->ReqItemId[i])
13377 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13380 RemoveTimedQuest(quest_id);
13382 if (BattleGround* bg = GetBattleGround())
13383 if (bg->GetTypeID() == BATTLEGROUND_AV)
13384 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13386 if (pQuest->GetRewChoiceItemsCount() > 0)
13388 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13390 ItemPosCountVec dest;
13391 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13393 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13394 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13399 if (pQuest->GetRewItemsCount() > 0)
13401 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13403 if (uint32 itemId = pQuest->RewItemId[i])
13405 ItemPosCountVec dest;
13406 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13408 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13409 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13415 RewardReputation( pQuest );
13417 uint16 log_slot = FindQuestSlot( quest_id );
13418 if (log_slot < MAX_QUEST_LOG_SIZE)
13419 SetQuestSlot(log_slot,0);
13421 QuestStatusData& q_status = mQuestStatus[quest_id];
13423 // Not give XP in case already completed once repeatable quest
13424 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST));
13426 if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
13427 GiveXP( XP , NULL );
13428 else
13430 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
13431 ModifyMoney( money );
13432 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13435 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13436 if (pQuest->GetRewOrReqMoney())
13438 ModifyMoney( pQuest->GetRewOrReqMoney() );
13440 if (pQuest->GetRewOrReqMoney() > 0)
13441 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13444 // honor reward
13445 if (pQuest->GetRewHonorAddition())
13446 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
13448 // title reward
13449 if (pQuest->GetCharTitleId())
13451 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13452 SetTitle(titleEntry);
13455 if (pQuest->GetBonusTalents())
13457 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13458 InitTalentForLevel();
13461 // Send reward mail
13462 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13463 MailDraft(mail_template_id).SendMailTo(MailReceiver(this), MailSender(questGiver), MAIL_CHECK_MASK_HAS_BODY, pQuest->GetRewMailDelaySecs());
13465 if (pQuest->IsDaily())
13467 SetDailyQuestStatus(quest_id);
13468 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13471 if (pQuest->IsWeekly())
13472 SetWeeklyQuestStatus(quest_id);
13474 if (!pQuest->IsRepeatable())
13475 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13476 else
13477 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13479 q_status.m_rewarded = true;
13480 if (q_status.uState != QUEST_NEW)
13481 q_status.uState = QUEST_CHANGED;
13483 if (announce)
13484 SendQuestReward( pQuest, XP, questGiver );
13486 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13487 if (pQuest->GetRewSpellCast() > 0)
13488 CastSpell( this, pQuest->GetRewSpellCast(), true);
13489 else if ( pQuest->GetRewSpell() > 0)
13490 CastSpell( this, pQuest->GetRewSpell(), true);
13492 if (pQuest->GetZoneOrSort() > 0)
13493 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13494 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13495 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13497 uint32 zone = 0;
13498 uint32 area = 0;
13500 // remove auras from spells with quest reward state limitations
13501 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13502 if(saEndBounds.first != saEndBounds.second)
13504 GetZoneAndAreaId(zone,area);
13506 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13507 if(!itr->second->IsFitToRequirements(this,zone,area))
13508 RemoveAurasDueToSpell(itr->second->spellId);
13511 // Some spells applied at quest reward
13512 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13513 if(saBounds.first != saBounds.second)
13515 if(!zone || !area)
13516 GetZoneAndAreaId(zone,area);
13518 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13519 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13520 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
13521 CastSpell(this,itr->second->spellId,true);
13524 //lets remove flag for delayed teleports
13525 SetCanDelayTeleport(false);
13528 void Player::FailQuest(uint32 questId)
13530 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13532 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13534 uint16 log_slot = FindQuestSlot(questId);
13536 if (log_slot < MAX_QUEST_LOG_SIZE)
13538 SetQuestSlotTimer(log_slot, 1);
13539 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13542 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13544 QuestStatusData& q_status = mQuestStatus[questId];
13546 RemoveTimedQuest(questId);
13547 q_status.m_timer = 0;
13549 SendQuestTimerFailed(questId);
13551 else
13552 SendQuestFailed(questId);
13556 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13558 int32 zoneOrSort = qInfo->GetZoneOrSort();
13559 int32 skillOrClass = qInfo->GetSkillOrClass();
13561 // skip zone zoneOrSort and 0 case skillOrClass
13562 if( zoneOrSort >= 0 && skillOrClass == 0 )
13563 return true;
13565 int32 questSort = -zoneOrSort;
13566 uint8 reqSortClass = ClassByQuestSort(questSort);
13568 // check class sort cases in zoneOrSort
13569 if( reqSortClass != 0 && getClass() != reqSortClass)
13571 if( msg )
13572 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13573 return false;
13576 // check class
13577 if( skillOrClass < 0 )
13579 uint8 reqClass = -int32(skillOrClass);
13580 if(getClass() != reqClass)
13582 if( msg )
13583 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13584 return false;
13587 // check skill
13588 else if( skillOrClass > 0 )
13590 uint32 reqSkill = skillOrClass;
13591 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13593 if( msg )
13594 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13595 return false;
13599 return true;
13602 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13604 if( getLevel() < qInfo->GetMinLevel() )
13606 if( msg )
13607 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13608 return false;
13610 return true;
13613 bool Player::SatisfyQuestLog( bool msg )
13615 // exist free slot
13616 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13617 return true;
13619 if( msg )
13621 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13622 GetSession()->SendPacket( &data );
13623 sLog.outDebug( "WORLD: Sent SMSG_QUESTLOG_FULL" );
13625 return false;
13628 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13630 // No previous quest (might be first quest in a series)
13631 if( qInfo->prevQuests.empty())
13632 return true;
13634 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13636 uint32 prevId = abs(*iter);
13638 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13639 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13641 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13643 // If any of the positive previous quests completed, return true
13644 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13646 // skip one-from-all exclusive group
13647 if(qPrevInfo->GetExclusiveGroup() >= 0)
13648 return true;
13650 // each-from-all exclusive group ( < 0)
13651 // can be start if only all quests in prev quest exclusive group completed and rewarded
13652 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13653 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13655 ASSERT(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13657 for(; iter2 != end; ++iter2)
13659 uint32 exclude_Id = iter2->second;
13661 // skip checked quest id, only state of other quests in group is interesting
13662 if(exclude_Id == prevId)
13663 continue;
13665 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13667 // alternative quest from group also must be completed and rewarded(reported)
13668 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13670 if( msg )
13671 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13672 return false;
13675 return true;
13677 // If any of the negative previous quests active, return true
13678 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13679 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13681 // skip one-from-all exclusive group
13682 if(qPrevInfo->GetExclusiveGroup() >= 0)
13683 return true;
13685 // each-from-all exclusive group ( < 0)
13686 // can be start if only all quests in prev quest exclusive group active
13687 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13688 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13690 ASSERT(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13692 for(; iter2 != end; ++iter2)
13694 uint32 exclude_Id = iter2->second;
13696 // skip checked quest id, only state of other quests in group is interesting
13697 if(exclude_Id == prevId)
13698 continue;
13700 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13702 // alternative quest from group also must be active
13703 if( i_exstatus == mQuestStatus.end() ||
13704 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13705 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13707 if( msg )
13708 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13709 return false;
13712 return true;
13717 // Has only positive prev. quests in non-rewarded state
13718 // and negative prev. quests in non-active state
13719 if( msg )
13720 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13722 return false;
13725 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13727 uint32 reqraces = qInfo->GetRequiredRaces();
13728 if ( reqraces == 0 )
13729 return true;
13730 if( (reqraces & getRaceMask()) == 0 )
13732 if( msg )
13733 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13734 return false;
13736 return true;
13739 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13741 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13742 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13744 if( msg )
13745 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13746 return false;
13749 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13750 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13752 if( msg )
13753 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13754 return false;
13757 return true;
13760 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13762 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13763 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13765 if( msg )
13766 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13767 return false;
13769 return true;
13772 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13774 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13776 if (msg)
13777 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13779 return false;
13781 return true;
13784 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13786 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13787 if (qInfo->GetExclusiveGroup() <= 0)
13788 return true;
13790 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13791 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13793 ASSERT(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13795 for(; iter != end; ++iter)
13797 uint32 exclude_Id = iter->second;
13799 // skip checked quest id, only state of other quests in group is interesting
13800 if (exclude_Id == qInfo->GetQuestId())
13801 continue;
13803 // not allow have daily quest if daily quest from exclusive group already recently completed
13804 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13805 if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false))
13807 if( msg )
13808 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13809 return false;
13812 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13814 // alternative quest already started or completed
13815 if (i_exstatus != mQuestStatus.end()
13816 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE))
13818 if( msg )
13819 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13820 return false;
13823 return true;
13826 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13828 if(!qInfo->GetNextQuestInChain())
13829 return true;
13831 // next quest in chain already started or completed
13832 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13833 if( itr != mQuestStatus.end()
13834 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13836 if( msg )
13837 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13838 return false;
13841 // check for all quests further up the chain
13842 // only necessary if there are quest chains with more than one quest that can be skipped
13843 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13844 return true;
13847 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13849 // No previous quest in chain
13850 if( qInfo->prevChainQuests.empty())
13851 return true;
13853 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13855 uint32 prevId = *iter;
13857 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13859 if( i_prevstatus != mQuestStatus.end() )
13861 // If any of the previous quests in chain active, return false
13862 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13863 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13865 if( msg )
13866 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13867 return false;
13871 // check for all quests further down the chain
13872 // only necessary if there are quest chains with more than one quest that can be skipped
13873 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13874 // return false;
13877 // No previous quest in chain active
13878 return true;
13881 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13883 if (!qInfo->IsDaily())
13884 return true;
13886 bool have_slot = false;
13887 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13889 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13890 if (qInfo->GetQuestId()==id)
13891 return false;
13893 if(!id)
13894 have_slot = true;
13897 if (!have_slot)
13899 if( msg )
13900 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13901 return false;
13904 return true;
13907 bool Player::SatisfyQuestWeek( Quest const* qInfo, bool msg )
13909 if (!qInfo->IsWeekly() || m_weeklyquests.empty())
13910 return true;
13912 // if not found in cooldown list
13913 return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end();
13916 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13918 uint32 srcitem = pQuest->GetSrcItemId();
13919 if (srcitem > 0)
13921 uint32 count = pQuest->GetSrcItemCount();
13922 if( count <= 0 )
13923 count = 1;
13925 ItemPosCountVec dest;
13926 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13927 if (msg == EQUIP_ERR_OK)
13929 Item * item = StoreNewItem(dest, srcitem, true);
13930 SendNewItem(item, count, true, false);
13931 return true;
13933 // player already have max amount required item, just report success
13934 else if (msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS)
13935 return true;
13936 else
13937 SendEquipError( msg, NULL, NULL, srcitem );
13938 return false;
13941 return true;
13944 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13946 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13947 if( qInfo )
13949 uint32 srcitem = qInfo->GetSrcItemId();
13950 if( srcitem > 0 )
13952 uint32 count = qInfo->GetSrcItemCount();
13953 if( count <= 0 )
13954 count = 1;
13956 // exist one case when destroy source quest item not possible:
13957 // non un-equippable item (equipped non-empty bag, for example)
13958 uint8 res = CanUnequipItems(srcitem,count);
13959 if(res != EQUIP_ERR_OK)
13961 if(msg)
13962 SendEquipError( res, NULL, NULL, srcitem );
13963 return false;
13966 DestroyItemCount(srcitem, count, true, true);
13969 return true;
13972 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13974 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13975 if( qInfo )
13977 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13978 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13979 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13980 && !qInfo->IsRepeatable() )
13981 return itr->second.m_rewarded;
13983 return false;
13985 return false;
13988 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13990 if( quest_id )
13992 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13993 if( itr != mQuestStatus.end() )
13994 return itr->second.m_status;
13996 return QUEST_STATUS_NONE;
13999 bool Player::CanShareQuest(uint32 quest_id) const
14001 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
14002 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
14004 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
14005 if( itr != mQuestStatus.end() )
14006 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
14008 return false;
14011 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
14013 if (sObjectMgr.GetQuestTemplate(quest_id))
14015 QuestStatusData& q_status = mQuestStatus[quest_id];
14017 q_status.m_status = status;
14019 if (q_status.uState != QUEST_NEW)
14020 q_status.uState = QUEST_CHANGED;
14023 UpdateForQuestWorldObjects();
14026 // not used in MaNGOS, but used in scripting code
14027 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
14029 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
14030 if( !qInfo )
14031 return 0;
14033 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14034 if ( qInfo->ReqCreatureOrGOId[j] == entry )
14035 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
14037 return 0;
14040 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
14042 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14044 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
14046 uint32 reqitemcount = pQuest->ReqItemCount[i];
14047 if( reqitemcount != 0 )
14049 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
14051 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
14052 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
14058 uint16 Player::FindQuestSlot( uint32 quest_id ) const
14060 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14061 if ( GetQuestSlotQuestId(i) == quest_id )
14062 return i;
14064 return MAX_QUEST_LOG_SIZE;
14067 void Player::AreaExploredOrEventHappens( uint32 questId )
14069 if( questId )
14071 uint16 log_slot = FindQuestSlot( questId );
14072 if( log_slot < MAX_QUEST_LOG_SIZE)
14074 QuestStatusData& q_status = mQuestStatus[questId];
14076 if(!q_status.m_explored)
14078 q_status.m_explored = true;
14079 if (q_status.uState != QUEST_NEW)
14080 q_status.uState = QUEST_CHANGED;
14083 if( CanCompleteQuest( questId ) )
14084 CompleteQuest( questId );
14088 //not used in mangosd, function for external script library
14089 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
14091 if( Group *pGroup = GetGroup() )
14093 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
14095 Player *pGroupGuy = itr->getSource();
14097 // for any leave or dead (with not released body) group member at appropriate distance
14098 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14099 pGroupGuy->AreaExploredOrEventHappens(questId);
14102 else
14103 AreaExploredOrEventHappens(questId);
14106 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
14108 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14110 uint32 questid = GetQuestSlotQuestId(i);
14111 if ( questid == 0 )
14112 continue;
14114 QuestStatusData& q_status = mQuestStatus[questid];
14116 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
14117 continue;
14119 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14120 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14121 continue;
14123 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14125 uint32 reqitem = qInfo->ReqItemId[j];
14126 if ( reqitem == entry )
14128 uint32 reqitemcount = qInfo->ReqItemCount[j];
14129 uint32 curitemcount = q_status.m_itemcount[j];
14130 if ( curitemcount < reqitemcount )
14132 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
14133 q_status.m_itemcount[j] += additemcount;
14134 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14136 SendQuestUpdateAddItem( qInfo, j, additemcount );
14138 if ( CanCompleteQuest( questid ) )
14139 CompleteQuest( questid );
14140 return;
14144 UpdateForQuestWorldObjects();
14147 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
14149 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14151 uint32 questid = GetQuestSlotQuestId(i);
14152 if(!questid)
14153 continue;
14154 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14155 if ( !qInfo )
14156 continue;
14157 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
14158 continue;
14160 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14162 uint32 reqitem = qInfo->ReqItemId[j];
14163 if ( reqitem == entry )
14165 QuestStatusData& q_status = mQuestStatus[questid];
14167 uint32 reqitemcount = qInfo->ReqItemCount[j];
14168 uint32 curitemcount;
14169 if( q_status.m_status != QUEST_STATUS_COMPLETE )
14170 curitemcount = q_status.m_itemcount[j];
14171 else
14172 curitemcount = GetItemCount(entry, true);
14173 if ( curitemcount < reqitemcount + count )
14175 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
14176 q_status.m_itemcount[j] = curitemcount - remitemcount;
14177 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14179 IncompleteQuest( questid );
14181 return;
14185 UpdateForQuestWorldObjects();
14188 void Player::KilledMonster( CreatureInfo const* cInfo, ObjectGuid guid )
14190 if(cInfo->Entry)
14191 KilledMonsterCredit(cInfo->Entry, guid);
14193 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
14194 if(cInfo->KillCredit[i])
14195 KilledMonsterCredit(cInfo->KillCredit[i], guid);
14198 void Player::KilledMonsterCredit( uint32 entry, ObjectGuid guid )
14200 uint32 addkillcount = 1;
14201 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
14202 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14204 uint32 questid = GetQuestSlotQuestId(i);
14205 if(!questid)
14206 continue;
14208 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14209 if( !qInfo )
14210 continue;
14211 // just if !ingroup || !noraidgroup || raidgroup
14212 QuestStatusData& q_status = mQuestStatus[questid];
14213 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
14215 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
14217 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14219 // skip GO activate objective or none
14220 if(qInfo->ReqCreatureOrGOId[j] <=0)
14221 continue;
14223 // skip Cast at creature objective
14224 if(qInfo->ReqSpell[j] !=0 )
14225 continue;
14227 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
14229 if ( reqkill == entry )
14231 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
14232 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
14233 if ( curkillcount < reqkillcount )
14235 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
14236 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14238 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
14240 if ( CanCompleteQuest( questid ) )
14241 CompleteQuest( questid );
14243 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14244 continue;
14252 void Player::CastedCreatureOrGO( uint32 entry, ObjectGuid guid, uint32 spell_id )
14254 bool isCreature = guid.IsCreature();
14256 uint32 addCastCount = 1;
14257 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
14259 uint32 questid = GetQuestSlotQuestId(i);
14260 if(!questid)
14261 continue;
14263 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14264 if ( !qInfo )
14265 continue;
14267 QuestStatusData& q_status = mQuestStatus[questid];
14269 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14271 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
14273 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14275 // skip kill creature objective (0) or wrong spell casts
14276 if(qInfo->ReqSpell[j] != spell_id )
14277 continue;
14279 uint32 reqTarget = 0;
14281 if(isCreature)
14283 // creature activate objectives
14284 if(qInfo->ReqCreatureOrGOId[j] > 0)
14285 // checked at quest_template loading
14286 reqTarget = qInfo->ReqCreatureOrGOId[j];
14288 else
14290 // GO activate objective
14291 if(qInfo->ReqCreatureOrGOId[j] < 0)
14292 // checked at quest_template loading
14293 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14296 // other not this creature/GO related objectives
14297 if( reqTarget != entry )
14298 continue;
14300 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14301 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14302 if ( curCastCount < reqCastCount )
14304 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14305 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14307 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14310 if ( CanCompleteQuest( questid ) )
14311 CompleteQuest( questid );
14313 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14314 break;
14321 void Player::TalkedToCreature( uint32 entry, ObjectGuid guid )
14323 uint32 addTalkCount = 1;
14324 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14326 uint32 questid = GetQuestSlotQuestId(i);
14327 if(!questid)
14328 continue;
14330 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14331 if ( !qInfo )
14332 continue;
14334 QuestStatusData& q_status = mQuestStatus[questid];
14336 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14338 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14340 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14342 // skip spell casts and Gameobject objectives
14343 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14344 continue;
14346 uint32 reqTarget = 0;
14348 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14349 // checked at quest_template loading
14350 reqTarget = qInfo->ReqCreatureOrGOId[j];
14351 else
14352 continue;
14354 if ( reqTarget == entry )
14356 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14357 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14358 if ( curTalkCount < reqTalkCount )
14360 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14361 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14363 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14365 if ( CanCompleteQuest( questid ) )
14366 CompleteQuest( questid );
14368 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14369 continue;
14377 void Player::MoneyChanged( uint32 count )
14379 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14381 uint32 questid = GetQuestSlotQuestId(i);
14382 if (!questid)
14383 continue;
14385 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14386 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14388 QuestStatusData& q_status = mQuestStatus[questid];
14390 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14392 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14394 if ( CanCompleteQuest( questid ) )
14395 CompleteQuest( questid );
14398 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14400 if(int32(count) < -qInfo->GetRewOrReqMoney())
14401 IncompleteQuest( questid );
14407 void Player::ReputationChanged(FactionEntry const* factionEntry )
14409 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14411 if(uint32 questid = GetQuestSlotQuestId(i))
14413 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14415 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14417 QuestStatusData& q_status = mQuestStatus[questid];
14418 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14420 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14421 if ( CanCompleteQuest( questid ) )
14422 CompleteQuest( questid );
14424 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14426 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14427 IncompleteQuest( questid );
14435 bool Player::HasQuestForItem( uint32 itemid ) const
14437 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14439 uint32 questid = GetQuestSlotQuestId(i);
14440 if ( questid == 0 )
14441 continue;
14443 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14444 if(qs_itr == mQuestStatus.end())
14445 continue;
14447 QuestStatusData const& q_status = qs_itr->second;
14449 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14451 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14452 if(!qinfo)
14453 continue;
14455 // hide quest if player is in raid-group and quest is no raid quest
14456 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14457 && !InBattleGround())
14458 continue;
14460 // There should be no mixed ReqItem/ReqSource drop
14461 // This part for ReqItem drop
14462 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14464 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14465 return true;
14467 // This part - for ReqSource
14468 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14470 // examined item is a source item
14471 if (qinfo->ReqSourceId[j] == itemid)
14473 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14475 // 'unique' item
14476 if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
14477 return true;
14479 // allows custom amount drop when not 0
14480 if (qinfo->ReqSourceCount[j])
14482 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14483 return true;
14484 } else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
14485 return true;
14490 return false;
14493 void Player::SendQuestComplete( uint32 quest_id )
14495 if( quest_id )
14497 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14498 data << uint32(quest_id);
14499 GetSession()->SendPacket( &data );
14500 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14504 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14506 uint32 questid = pQuest->GetQuestId();
14507 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14508 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14509 data << uint32(questid);
14511 if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
14513 data << uint32(XP);
14514 data << uint32(pQuest->GetRewOrReqMoney());
14516 else
14518 data << uint32(0);
14519 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)));
14522 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
14523 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14524 data << uint32(0); // arena points
14525 GetSession()->SendPacket( &data );
14527 if (pQuest->GetQuestCompleteScript() != 0)
14528 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14531 void Player::SendQuestFailed( uint32 quest_id )
14533 if( quest_id )
14535 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14536 data << uint32(quest_id);
14537 data << uint32(0); // failed reason (4 for inventory is full)
14538 GetSession()->SendPacket( &data );
14539 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14543 void Player::SendQuestTimerFailed( uint32 quest_id )
14545 if( quest_id )
14547 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14548 data << uint32(quest_id);
14549 GetSession()->SendPacket( &data );
14550 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14554 void Player::SendCanTakeQuestResponse( uint32 msg )
14556 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14557 data << uint32(msg);
14558 GetSession()->SendPacket( &data );
14559 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14562 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14564 if (pReceiver)
14566 std::string strTitle = pQuest->GetTitle();
14568 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14570 if (loc_idx >= 0)
14572 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14574 if ((int32)pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14575 strTitle = pLocale->Title[loc_idx];
14579 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14580 data << uint32(pQuest->GetQuestId());
14581 data << strTitle;
14582 data << uint64(GetGUID());
14583 pReceiver->GetSession()->SendPacket(&data);
14585 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14589 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14591 if( pPlayer )
14593 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14594 data << uint64(pPlayer->GetGUID());
14595 data << uint8(msg); // valid values: 0-8
14596 GetSession()->SendPacket( &data );
14597 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14601 void Player::SendQuestUpdateAddItem( Quest const* /*pQuest*/, uint32 /*item_idx*/, uint32 /*count*/ )
14603 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14604 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14605 //data << pQuest->ReqItemId[item_idx];
14606 //data << count;
14607 GetSession()->SendPacket( &data );
14610 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, ObjectGuid guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14612 ASSERT(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14614 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14615 if (entry < 0)
14616 // client expected gameobject template id in form (id|0x80000000)
14617 entry = (-entry) | 0x80000000;
14619 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14620 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14621 data << uint32(pQuest->GetQuestId());
14622 data << uint32(entry);
14623 data << uint32(old_count + add_count);
14624 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14625 data << guid;
14626 GetSession()->SendPacket(&data);
14628 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14629 if( log_slot < MAX_QUEST_LOG_SIZE)
14630 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14633 /*********************************************************/
14634 /*** LOAD SYSTEM ***/
14635 /*********************************************************/
14637 void Player::_LoadDeclinedNames(QueryResult* result)
14639 if(!result)
14640 return;
14642 if(m_declinedname)
14643 delete m_declinedname;
14645 m_declinedname = new DeclinedName;
14646 Field *fields = result->Fetch();
14647 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14648 m_declinedname->name[i] = fields[i].GetCppString();
14650 delete result;
14653 void Player::_LoadArenaTeamInfo(QueryResult *result)
14655 // arenateamid, played_week, played_season, personal_rating
14656 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14657 if (!result)
14658 return;
14662 Field *fields = result->Fetch();
14664 uint32 arenateamid = fields[0].GetUInt32();
14665 uint32 played_week = fields[1].GetUInt32();
14666 uint32 played_season = fields[2].GetUInt32();
14667 uint32 wons_season = fields[3].GetUInt32();
14668 uint32 personal_rating = fields[4].GetUInt32();
14670 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14671 if(!aTeam)
14673 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14674 continue;
14676 uint8 arenaSlot = aTeam->GetSlot();
14678 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
14679 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
14680 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptain() == GetGUID()) ? 0 : 1);
14681 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
14682 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
14683 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
14684 SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
14686 } while (result->NextRow());
14687 delete result;
14690 void Player::_LoadEquipmentSets(QueryResult *result)
14692 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
14693 if (!result)
14694 return;
14696 uint32 count = 0;
14699 Field *fields = result->Fetch();
14701 EquipmentSet eqSet;
14703 eqSet.Guid = fields[0].GetUInt64();
14704 uint32 index = fields[1].GetUInt32();
14705 eqSet.Name = fields[2].GetCppString();
14706 eqSet.IconName = fields[3].GetCppString();
14707 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14709 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14710 eqSet.Items[i] = fields[4+i].GetUInt32();
14712 m_EquipmentSets[index] = eqSet;
14714 ++count;
14716 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14717 break;
14718 } while (result->NextRow());
14719 delete result;
14722 void Player::_LoadBGData(QueryResult* result)
14724 if (!result)
14725 return;
14727 // Expecting only one row
14728 Field *fields = result->Fetch();
14729 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14730 m_bgData.bgInstanceID = fields[0].GetUInt32();
14731 m_bgData.bgTeam = fields[1].GetUInt32();
14732 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14733 fields[2].GetFloat(), // X
14734 fields[3].GetFloat(), // Y
14735 fields[4].GetFloat(), // Z
14736 fields[5].GetFloat()); // Orientation
14737 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14738 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14739 m_bgData.mountSpell = fields[9].GetUInt32();
14741 delete result;
14744 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14746 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14747 if(!result)
14748 return false;
14750 Field *fields = result->Fetch();
14752 x = fields[0].GetFloat();
14753 y = fields[1].GetFloat();
14754 z = fields[2].GetFloat();
14755 o = fields[3].GetFloat();
14756 mapid = fields[4].GetUInt32();
14757 in_flight = !fields[5].GetCppString().empty();
14759 delete result;
14760 return true;
14763 void Player::_LoadIntoDataField(const char* data, uint32 startOffset, uint32 count)
14765 if(!data)
14766 return;
14768 Tokens tokens = StrSplit(data, " ");
14770 if(tokens.size() != count)
14771 return;
14773 Tokens::iterator iter;
14774 uint32 index;
14775 for (iter = tokens.begin(), index = 0; index < count; ++iter, ++index)
14777 m_uint32Values[startOffset + index] = atol((*iter).c_str());
14781 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14783 // 0 1 2 3 4 5 6 7 8 9 10 11
14784 //SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14785 // 12 13 14 15 16 17 18 19 20 21 22 23 24
14786 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14787 // 25 26 27 28 29 30 31 32 33 34 35 36 37 38
14788 //"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,"
14789 // 39 40 41 42 43 44 45 46 47 48 49
14790 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14791 // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
14792 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14793 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14795 if(!result)
14797 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14798 return false;
14801 Field *fields = result->Fetch();
14803 uint32 dbAccountId = fields[1].GetUInt32();
14805 // check if the character's account in the db and the logged in account match.
14806 // player should be able to load/delete character only with correct account!
14807 if( dbAccountId != GetSession()->GetAccountId() )
14809 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14810 delete result;
14811 return false;
14814 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14816 m_name = fields[2].GetCppString();
14818 // check name limitations
14819 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14820 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14822 delete result;
14823 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14824 return false;
14827 // overwrite possible wrong/corrupted guid
14828 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14830 // overwrite some data fields
14831 uint32 bytes0 = 0;
14832 bytes0 |= fields[3].GetUInt8(); // race
14833 bytes0 |= fields[4].GetUInt8() << 8; // class
14834 bytes0 |= fields[5].GetUInt8() << 16; // gender
14835 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14837 SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
14838 SetUInt32Value(PLAYER_XP, fields[7].GetUInt32());
14840 _LoadIntoDataField(fields[60].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE);
14841 _LoadIntoDataField(fields[63].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2);
14843 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
14844 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
14845 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f);
14847 uint32 money = fields[8].GetUInt32();
14848 if(money > MAX_MONEY_AMOUNT)
14849 money = MAX_MONEY_AMOUNT;
14850 SetMoney(money);
14852 SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32());
14853 SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32());
14854 SetUInt32Value(PLAYER_BYTES_3, (fields[49].GetUInt16() & 0xFFFE) | fields[5].GetUInt8());
14855 SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32());
14856 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetInt32());
14858 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64());
14860 SetUInt32Value(PLAYER_AMMO_ID, fields[62].GetUInt32());
14861 SetByteValue(PLAYER_FIELD_BYTES, 2, fields[64].GetUInt8());
14864 InitDisplayIds();
14866 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14867 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14869 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14870 SetVisibleItemSlot(slot, NULL);
14872 if (m_items[slot])
14874 delete m_items[slot];
14875 m_items[slot] = NULL;
14879 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14880 outDebugValues();
14882 //Need to call it to initialize m_team (m_team can be calculated from race)
14883 //Other way is to saves m_team into characters table.
14884 setFactionForRace(getRace());
14885 SetCharm(NULL);
14887 // load home bind and check in same time class/race pair, it used later for restore broken positions
14888 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14890 delete result;
14891 return false;
14894 InitPrimaryProfessions(); // to max set before any spell loaded
14896 // init saved position, and fix it later if problematic
14897 uint32 transGUID = fields[30].GetUInt32();
14898 Relocate(fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat());
14899 SetLocationMapId(fields[15].GetUInt32());
14901 uint32 difficulty = fields[38].GetUInt32();
14902 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14903 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14904 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14906 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14908 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14910 uint32 arena_currency = fields[39].GetUInt32();
14911 if (arena_currency > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
14912 arena_currency = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS);
14914 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14916 // check arena teams integrity
14917 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14919 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14920 if(!arena_team_id)
14921 continue;
14923 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14924 if(at->HaveMember(GetGUID()))
14925 continue;
14927 // arena team not exist or not member, cleanup fields
14928 for(int j = 0; j < ARENA_TEAM_END; ++j)
14929 SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
14932 uint32 honor_currency = fields[40].GetUInt32();
14933 if (honor_currency > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
14934 honor_currency = sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS);
14935 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, honor_currency);
14937 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32());
14938 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32());
14939 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[43].GetUInt32());
14940 SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16());
14941 SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16());
14943 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14945 if(!IsPositionValid())
14947 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());
14948 RelocateToHomebind();
14950 transGUID = 0;
14952 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14955 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14957 if(m_bgData.bgInstanceID) //saved in BattleGround
14959 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14961 bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
14963 if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
14965 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14966 AddBattleGroundQueueId(bgQueueTypeId);
14968 m_bgData.bgTypeID = currentBg->GetTypeID();
14970 //join player to battleground group
14971 currentBg->EventPlayerLoggedIn(this, GetGUID());
14972 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14974 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14976 else
14978 // leave bg
14979 if (player_at_bg)
14980 currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
14982 // move to bg enter point
14983 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14984 SetLocationMapId(_loc.mapid);
14985 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14987 // We are not in BG anymore
14988 m_bgData.bgInstanceID = 0;
14991 else
14993 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14994 // if server restart after player save in BG or area
14995 // player can have current coordinates in to BG/Arena map, fix this
14996 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14998 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14999 SetLocationMapId(_loc.mapid);
15000 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
15004 if (transGUID != 0)
15006 m_movementInfo.SetTransportData(transGUID, fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), 0, -1);
15008 if( !MaNGOS::IsValidMapCoord(
15009 GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
15010 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
15011 // transport size limited
15012 m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
15014 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
15015 guid, GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
15016 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
15018 RelocateToHomebind();
15020 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
15022 transGUID = 0;
15026 if (transGUID != 0)
15028 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
15030 if( (*iter)->GetGUIDLow() == transGUID)
15032 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
15033 // client without expansion support
15034 if(GetSession()->Expansion() < transMapEntry->Expansion())
15036 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
15037 break;
15040 m_transport = *iter;
15041 m_transport->AddPassenger(this);
15042 SetLocationMapId(m_transport->GetMapId());
15043 break;
15047 if(!m_transport)
15049 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
15050 guid,transGUID);
15052 RelocateToHomebind();
15054 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
15056 transGUID = 0;
15059 else // not transport case
15061 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
15062 // client without expansion support
15063 if(GetSession()->Expansion() < mapEntry->Expansion())
15065 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
15066 RelocateToHomebind();
15070 // NOW player must have valid map
15071 // load the player's map here if it's not already loaded
15072 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15074 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
15075 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
15077 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
15078 if(at)
15079 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
15080 else
15081 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
15084 SaveRecallPosition();
15086 time_t now = time(NULL);
15087 time_t logoutTime = time_t(fields[22].GetUInt64());
15089 // since last logout (in seconds)
15090 uint32 time_diff = uint32(now - logoutTime);
15092 // set value, including drunk invisibility detection
15093 // calculate sobering. after 15 minutes logged out, the player will be sober again
15094 float soberFactor;
15095 if(time_diff > 15*MINUTE)
15096 soberFactor = 0;
15097 else
15098 soberFactor = 1-time_diff/(15.0f*MINUTE);
15099 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
15100 SetDrunkValue(newDrunkenValue);
15102 m_cinematic = fields[18].GetUInt32();
15103 m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
15104 m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();
15106 m_resetTalentsCost = fields[24].GetUInt32();
15107 m_resetTalentsTime = time_t(fields[25].GetUInt64());
15109 // reserve some flags
15110 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
15112 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
15113 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
15115 m_taxi.LoadTaxiMask( fields[17].GetString() ); // must be before InitTaxiNodesForLevel
15117 uint32 extraflags = fields[31].GetUInt32();
15119 m_stableSlots = fields[32].GetUInt32();
15120 if(m_stableSlots > MAX_PET_STABLES)
15122 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
15123 m_stableSlots = MAX_PET_STABLES;
15126 m_atLoginFlags = fields[33].GetUInt32();
15128 // Honor system
15129 // Update Honor kills data
15130 m_lastHonorUpdateTime = logoutTime;
15131 UpdateHonorFields();
15133 m_deathExpireTime = (time_t)fields[36].GetUInt64();
15134 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
15135 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
15137 std::string taxi_nodes = fields[37].GetCppString();
15139 // clear channel spell data (if saved at channel spell casting)
15140 SetChannelObjectGUID(0);
15141 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
15143 // clear charm/summon related fields
15144 SetCharm(NULL);
15145 SetPet(NULL);
15146 SetTargetGUID(0);
15147 SetChannelObjectGUID(0);
15148 SetCharmerGUID(0);
15149 SetOwnerGUID(0);
15150 SetCreatorGUID(0);
15152 // reset some aura modifiers before aura apply
15153 SetFarSightGUID(0);
15154 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
15155 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
15157 // cleanup aura list explicitly before skill load wher some spells can be applied
15158 RemoveAllAuras();
15160 // make sure the unit is considered out of combat for proper loading
15161 ClearInCombat();
15163 // make sure the unit is considered not in duel for proper loading
15164 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
15165 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
15167 // reset stats before loading any modifiers
15168 InitStatsForLevel();
15169 InitGlyphsForLevel();
15170 InitTaxiNodesForLevel();
15171 InitRunes();
15173 // rest bonus can only be calculated after InitStatsForLevel()
15174 m_rest_bonus = fields[21].GetFloat();
15176 if(time_diff > 0)
15178 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15179 float bubble0 = 0.031f;
15180 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15181 float bubble1 = 0.125f;
15182 float bubble = fields[23].GetUInt32() > 0
15183 ? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
15184 : bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS);
15186 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
15189 // load skills after InitStatsForLevel because it triggering aura apply also
15190 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
15192 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15194 // Mail
15195 _LoadMails(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS));
15196 _LoadMailedItems(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS));
15197 UpdateNextMailTimeAndUnreads();
15199 m_specsCount = fields[58].GetUInt8();
15200 m_activeSpec = fields[59].GetUInt8();
15202 _LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
15204 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
15205 ApplyGlyphs(true);
15207 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15208 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
15209 m_deathState = DEAD;
15211 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
15213 // after spell load, learn rewarded spell if need also
15214 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
15215 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
15216 _LoadWeeklyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADWEKLYQUESTSTATUS));
15218 _LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
15220 // after spell and quest load
15221 InitTalentForLevel();
15222 learnDefaultSpells();
15224 // must be before inventory (some items required reputation check)
15225 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
15227 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
15229 // update items with duration and realtime
15230 UpdateItemDuration(time_diff, true);
15232 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
15234 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
15236 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15237 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15238 uint32 curTitle = fields[46].GetUInt32();
15239 if (curTitle && !HasTitle(curTitle))
15240 curTitle = 0;
15242 SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
15244 // Not finish taxi flight path
15245 if(m_bgData.HasTaxiPath())
15247 m_taxi.ClearTaxiDestinations();
15248 for (int i = 0; i < 2; ++i)
15249 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
15251 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
15253 // problems with taxi path loading
15254 TaxiNodesEntry const* nodeEntry = NULL;
15255 if(uint32 node_id = m_taxi.GetTaxiSource())
15256 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15258 if(!nodeEntry) // don't know taxi start node, to homebind
15260 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15261 RelocateToHomebind();
15263 else // have start node, to it
15265 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15266 SetLocationMapId(nodeEntry->map_id);
15267 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15270 //we can be relocated from taxi and still have an outdated Map pointer!
15271 //so we need to get a new Map pointer!
15272 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15273 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15275 m_taxi.ClearTaxiDestinations();
15278 if(uint32 node_id = m_taxi.GetTaxiSource())
15280 // save source node as recall coord to prevent recall and fall from sky
15281 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15282 ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15283 m_recallMap = nodeEntry->map_id;
15284 m_recallX = nodeEntry->x;
15285 m_recallY = nodeEntry->y;
15286 m_recallZ = nodeEntry->z;
15288 // flight will started later
15291 // has to be called after last Relocate() in Player::LoadFromDB
15292 SetFallInformation(0, GetPositionZ());
15294 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15296 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15297 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15298 if(!isAlive())
15299 RemoveAllAurasOnDeath();
15301 //apply all stat bonuses from items and auras
15302 SetCanModifyStats(true);
15303 UpdateAllStats();
15305 // restore remembered power/health values (but not more max values)
15306 uint32 savedhealth = fields[50].GetUInt32();
15307 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
15308 for(uint32 i = 0; i < MAX_POWERS; ++i)
15310 uint32 savedpower = fields[51+i].GetUInt32();
15311 SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
15314 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15315 outDebugValues();
15317 // all fields read
15318 delete result;
15320 // GM state
15321 if(GetSession()->GetSecurity() > SEC_PLAYER)
15323 switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE))
15325 default:
15326 case 0: break; // disable
15327 case 1: SetGameMaster(true); break; // enable
15328 case 2: // save state
15329 if(extraflags & PLAYER_EXTRA_GM_ON)
15330 SetGameMaster(true);
15331 break;
15334 switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE))
15336 default:
15337 case 0: SetGMVisible(false); break; // invisible
15338 case 1: break; // visible
15339 case 2: // save state
15340 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15341 SetGMVisible(false);
15342 break;
15345 switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS))
15347 default:
15348 case 0: break; // disable
15349 case 1: SetAcceptTicket(true); break; // enable
15350 case 2: // save state
15351 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15352 SetAcceptTicket(true);
15353 break;
15356 switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT))
15358 default:
15359 case 0: break; // disable
15360 case 1: SetGMChat(true); break; // enable
15361 case 2: // save state
15362 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15363 SetGMChat(true);
15364 break;
15367 switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO))
15369 default:
15370 case 0: break; // disable
15371 case 1: SetAcceptWhispers(true); break; // enable
15372 case 2: // save state
15373 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15374 SetAcceptWhispers(true);
15375 break;
15379 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15381 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15382 m_achievementMgr.CheckAllAchievementCriteria();
15384 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15386 return true;
15389 bool Player::isAllowedToLoot(Creature* creature)
15391 if(Player* recipient = creature->GetLootRecipient())
15393 if (recipient == this)
15394 return true;
15395 if( Group* otherGroup = recipient->GetGroup())
15397 Group* thisGroup = GetGroup();
15398 if(!thisGroup)
15399 return false;
15400 return thisGroup == otherGroup;
15402 return false;
15404 else
15405 // prevent other players from looting if the recipient got disconnected
15406 return !creature->hasLootRecipient();
15409 void Player::_LoadActions(QueryResult *result)
15411 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
15412 m_actionButtons[i].clear();
15414 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15416 if(result)
15420 Field *fields = result->Fetch();
15422 uint8 spec = fields[0].GetUInt8();
15423 uint8 button = fields[1].GetUInt8();
15424 uint32 action = fields[2].GetUInt32();
15425 uint8 type = fields[3].GetUInt8();
15427 if(ActionButton* ab = addActionButton(spec, button, action, type))
15428 ab->uState = ACTIONBUTTON_UNCHANGED;
15429 else
15431 sLog.outError( " ...at loading, and will deleted in DB also");
15433 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15434 m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
15437 while( result->NextRow() );
15439 delete result;
15443 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15445 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15447 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15449 if(result)
15453 Field *fields = result->Fetch();
15454 uint64 caster_guid = fields[0].GetUInt64();
15455 uint32 spellid = fields[1].GetUInt32();
15456 SpellEffectIndex effindex = SpellEffectIndex(fields[2].GetUInt32());
15457 uint32 stackcount = fields[3].GetUInt32();
15458 int32 damage = fields[4].GetInt32();
15459 int32 maxduration = fields[5].GetInt32();
15460 int32 remaintime = fields[6].GetInt32();
15461 int32 remaincharges = fields[7].GetInt32();
15463 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15464 if (!spellproto)
15466 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15467 continue;
15470 if (effindex >= MAX_EFFECT_INDEX)
15472 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15473 continue;
15476 // negative effects should continue counting down after logout
15477 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15479 if (remaintime/IN_MILLISECONDS <= int32(timediff))
15480 continue;
15482 remaintime -= timediff*IN_MILLISECONDS;
15485 // prevent wrong values of remaincharges
15486 if (spellproto->procCharges)
15488 if (remaincharges <= 0 || remaincharges > (int32)spellproto->procCharges)
15489 remaincharges = spellproto->procCharges;
15491 else
15492 remaincharges = 0;
15495 for(uint32 i = 0; i < stackcount; ++i)
15497 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15498 if (!damage)
15499 damage = aura->GetModifier()->m_amount;
15501 // reset stolen single target auras
15502 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15503 aura->SetIsSingleTarget(false);
15505 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15506 AddAura(aura);
15507 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15510 while( result->NextRow() );
15512 delete result;
15515 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15516 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15519 void Player::_LoadGlyphs(QueryResult *result)
15521 if(!result)
15522 return;
15524 // 0 1 2
15525 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15529 Field *fields = result->Fetch();
15530 uint8 spec = fields[0].GetUInt8();
15531 uint8 slot = fields[1].GetUInt8();
15532 uint32 glyph = fields[2].GetUInt32();
15534 GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph);
15535 if(!gp)
15537 sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec);
15538 continue;
15541 GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot));
15542 if (!gs)
15544 sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec);
15545 continue;
15548 if(gp->TypeFlags != gs->TypeFlags)
15550 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15551 continue;
15554 m_glyphs[spec][slot].id = glyph;
15556 } while( result->NextRow() );
15558 delete result;
15563 void Player::LoadCorpse()
15565 if( isAlive() )
15567 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15569 else
15571 if(Corpse *corpse = GetCorpse())
15573 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15575 else
15577 //Prevent Dead Player login without corpse
15578 ResurrectPlayer(0.5f);
15583 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15585 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,text,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());
15586 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15587 //NOTE: the "order by `bag`" is important because it makes sure
15588 //the bagMap is filled before items in the bags are loaded
15589 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15590 //expected to be equipped before offhand items (TODO: fixme)
15592 uint32 zone = GetZoneId();
15594 if (result)
15596 std::list<Item*> problematicItems;
15598 // prevent items from being added to the queue when stored
15599 m_itemUpdateQueueBlocked = true;
15602 Field *fields = result->Fetch();
15603 uint32 bag_guid = fields[2].GetUInt32();
15604 uint8 slot = fields[3].GetUInt8();
15605 uint32 item_guid = fields[4].GetUInt32();
15606 uint32 item_id = fields[5].GetUInt32();
15608 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15610 if(!proto)
15612 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15613 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15614 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15615 continue;
15618 Item *item = NewItemOrBag(proto);
15620 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15622 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15623 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15624 item->FSetState(ITEM_REMOVED);
15625 item->SaveToDB(); // it also deletes item object !
15626 continue;
15629 // not allow have in alive state item limited to another map/zone
15630 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15632 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15633 item->FSetState(ITEM_REMOVED);
15634 item->SaveToDB(); // it also deletes item object !
15635 continue;
15638 // "Conjured items disappear if you are logged out for more than 15 minutes"
15639 if (timediff > 15*MINUTE && item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED))
15641 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15642 item->FSetState(ITEM_REMOVED);
15643 item->SaveToDB(); // it also deletes item object !
15644 continue;
15647 bool success = true;
15649 // the item/bag is not in a bag
15650 if (!bag_guid)
15652 item->SetContainer( NULL );
15653 item->SetSlot(slot);
15655 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15657 ItemPosCountVec dest;
15658 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15659 item = StoreItem(dest, item, true);
15660 else
15661 success = false;
15663 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15665 uint16 dest;
15666 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15667 QuickEquipItem(dest, item);
15668 else
15669 success = false;
15671 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15673 ItemPosCountVec dest;
15674 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15675 item = BankItem(dest, item, true);
15676 else
15677 success = false;
15680 if(success)
15682 // store bags that may contain items in them
15683 if(item->IsBag() && IsBagPos(item->GetPos()))
15684 bagMap[item_guid] = (Bag*)item;
15687 // the item/bag in a bag
15688 else
15690 item->SetSlot(NULL_SLOT);
15691 // the item is in a bag, find the bag
15692 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15693 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15695 ItemPosCountVec dest;
15696 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15697 item = StoreItem(dest, item, true);
15698 else
15699 success = false;
15701 else
15702 success = false;
15705 // item's state may have changed after stored
15706 if (success)
15708 item->SetState(ITEM_UNCHANGED, this);
15710 // recharged mana gem
15711 if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM)
15712 item->RestoreCharges();
15714 else
15716 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);
15717 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15718 problematicItems.push_back(item);
15720 } while (result->NextRow());
15722 delete result;
15723 m_itemUpdateQueueBlocked = false;
15725 // send by mail problematic items
15726 while(!problematicItems.empty())
15728 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15730 // fill mail
15731 MailDraft draft(subject, "There's were problems with equipping item(s).");
15733 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15735 Item* item = problematicItems.front();
15736 problematicItems.pop_front();
15738 draft.AddItem(item);
15741 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15744 //if(isAlive())
15745 _ApplyAllItemMods();
15748 // load mailed item which should receive current player
15749 void Player::_LoadMailedItems(QueryResult *result)
15751 // data needs to be at first place for Item::LoadFromDB
15752 // 0 1 2 3 4
15753 // "SELECT data, text, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid)
15754 if(!result)
15755 return;
15759 Field *fields = result->Fetch();
15760 uint32 mail_id = fields[2].GetUInt32();
15761 uint32 item_guid_low = fields[3].GetUInt32();
15762 uint32 item_template = fields[4].GetUInt32();
15764 Mail* mail = GetMail(mail_id);
15765 if(!mail)
15766 continue;
15767 mail->AddItem(item_guid_low, item_template);
15769 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15771 if(!proto)
15773 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
15774 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15775 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15776 continue;
15779 Item *item = NewItemOrBag(proto);
15781 if(!item->LoadFromDB(item_guid_low, 0, result))
15783 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15784 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15785 item->FSetState(ITEM_REMOVED);
15786 item->SaveToDB(); // it also deletes item object !
15787 continue;
15790 AddMItem(item);
15791 } while (result->NextRow());
15793 delete result;
15796 void Player::_LoadMails(QueryResult *result)
15798 m_mail.clear();
15799 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15800 //"SELECT id,messageType,sender,receiver,subject,body,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC", GetGUIDLow()
15801 if(!result)
15802 return;
15806 Field *fields = result->Fetch();
15807 Mail *m = new Mail;
15808 m->messageID = fields[0].GetUInt32();
15809 m->messageType = fields[1].GetUInt8();
15810 m->sender = fields[2].GetUInt32();
15811 m->receiver = fields[3].GetUInt32();
15812 m->subject = fields[4].GetCppString();
15813 m->body = fields[5].GetCppString();
15814 bool has_items = fields[6].GetBool();
15815 m->expire_time = (time_t)fields[7].GetUInt64();
15816 m->deliver_time = (time_t)fields[8].GetUInt64();
15817 m->money = fields[9].GetUInt32();
15818 m->COD = fields[10].GetUInt32();
15819 m->checked = fields[11].GetUInt32();
15820 m->stationery = fields[12].GetUInt8();
15821 m->mailTemplateId = fields[13].GetInt16();
15823 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15825 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15826 m->mailTemplateId = 0;
15829 m->state = MAIL_STATE_UNCHANGED;
15831 m_mail.push_back(m);
15832 } while( result->NextRow() );
15833 delete result;
15836 void Player::LoadPet()
15838 // fixme: the pet should still be loaded if the player is not in world
15839 // just not added to the map
15840 if(IsInWorld())
15842 Pet *pet = new Pet;
15843 if(!pet->LoadPetFromDB(this, 0, 0, true))
15844 delete pet;
15848 void Player::_LoadQuestStatus(QueryResult *result)
15850 mQuestStatus.clear();
15852 uint32 slot = 0;
15854 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15855 //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());
15857 if(result)
15861 Field *fields = result->Fetch();
15863 uint32 quest_id = fields[0].GetUInt32();
15864 // used to be new, no delete?
15865 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15866 if( pQuest )
15868 // find or create
15869 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15871 uint32 qstatus = fields[1].GetUInt32();
15872 if(qstatus < MAX_QUEST_STATUS)
15873 questStatusData.m_status = QuestStatus(qstatus);
15874 else
15876 questStatusData.m_status = QUEST_STATUS_NONE;
15877 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15880 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15881 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15883 time_t quest_time = time_t(fields[4].GetUInt64());
15885 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15887 AddTimedQuest( quest_id );
15889 if (quest_time <= sWorld.GetGameTime())
15890 questStatusData.m_timer = 1;
15891 else
15892 questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILLISECONDS;
15894 else
15895 quest_time = 0;
15897 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15898 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15899 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15900 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15901 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15902 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15903 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15904 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15906 questStatusData.uState = QUEST_UNCHANGED;
15908 // add to quest log
15909 if (slot < MAX_QUEST_LOG_SIZE &&
15910 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15911 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15912 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15913 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15915 SetQuestSlot(slot, quest_id, uint32(quest_time));
15917 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15918 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15920 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15921 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15923 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15924 if(questStatusData.m_creatureOrGOcount[idx])
15925 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15927 ++slot;
15930 if(questStatusData.m_rewarded)
15932 // learn rewarded spell if unknown
15933 learnQuestRewardedSpells(pQuest);
15935 // set rewarded title if any
15936 if(pQuest->GetCharTitleId())
15938 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15939 SetTitle(titleEntry);
15942 if(pQuest->GetBonusTalents())
15943 m_questRewardTalentCount += pQuest->GetBonusTalents();
15946 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15949 while( result->NextRow() );
15951 delete result;
15954 // clear quest log tail
15955 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15956 SetQuestSlot(i, 0);
15959 void Player::_LoadDailyQuestStatus(QueryResult *result)
15961 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15962 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15964 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15966 if(result)
15968 uint32 quest_daily_idx = 0;
15972 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15974 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15975 break;
15978 Field *fields = result->Fetch();
15980 uint32 quest_id = fields[0].GetUInt32();
15982 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15983 if( !pQuest )
15984 continue;
15986 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15987 ++quest_daily_idx;
15989 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15991 while( result->NextRow() );
15993 delete result;
15996 m_DailyQuestChanged = false;
15999 void Player::_LoadWeeklyQuestStatus(QueryResult *result)
16001 m_weeklyquests.clear();
16003 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
16005 if (result)
16009 Field *fields = result->Fetch();
16011 uint32 quest_id = fields[0].GetUInt32();
16013 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
16014 if (!pQuest)
16015 continue;
16017 m_weeklyquests.insert(quest_id);
16019 sLog.outDebug("Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
16021 while( result->NextRow() );
16023 delete result;
16025 m_WeeklyQuestChanged = false;
16028 void Player::_LoadSpells(QueryResult *result)
16030 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
16032 if(result)
16036 Field *fields = result->Fetch();
16038 uint32 spell_id = fields[0].GetUInt32();
16040 // skip talents & drop unneeded data
16041 if(GetTalentSpellPos(spell_id))
16043 sLog.outError("Player::_LoadSpells: Player (GUID: %u) has talent spell in character_spell, removing it.", GetGUIDLow(), spell_id);
16044 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'", spell_id);
16045 continue;
16048 addSpell(spell_id, fields[1].GetBool(), false, false, fields[2].GetBool());
16050 while( result->NextRow() );
16052 delete result;
16056 void Player::_LoadTalents(QueryResult *result)
16058 //QueryResult *result = CharacterDatabase.PQuery("SELECT talent_id, current_rank, spec FROM character_talent WHERE guid = '%u'",GetGUIDLow());
16059 if (result)
16063 Field *fields = result->Fetch();
16065 uint32 talent_id = fields[0].GetUInt32();
16066 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talent_id );
16068 if (!talentInfo)
16070 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent_id: %u , this talent will be deleted from character_talent",GetGUIDLow(), talent_id );
16071 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
16072 continue;
16075 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
16077 if (!talentTabInfo)
16079 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talentTabInfo: %u for talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentInfo->TalentTab, talentInfo->TalentID );
16080 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
16081 continue;
16084 // prevent load talent for different class (cheating)
16085 if ((getClassMask() & talentTabInfo->ClassMask) == 0)
16087 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has talent with ClassMask: %u , but Player's ClassMask is: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentTabInfo->ClassMask, getClassMask() ,talentInfo->TalentID );
16088 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
16089 continue;
16092 uint32 currentRank = fields[1].GetUInt32();
16094 if (currentRank > MAX_TALENT_RANK || talentInfo->RankID[currentRank] == 0)
16096 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent rank: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), currentRank, talentInfo->TalentID );
16097 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
16098 continue;
16101 uint32 spec = fields[2].GetUInt32();
16103 if (spec > MAX_TALENT_SPEC_COUNT)
16105 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u, spec will be deleted from character_talent", GetGUIDLow(), spec);
16106 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spec = '%u' ", spec);
16107 continue;
16110 if (spec >= m_specsCount)
16112 sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u , this spec will be deleted from character_talent.", GetGUIDLow(), spec);
16113 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND spec = '%u' ", GetGUIDLow(), spec);
16114 continue;
16117 if (m_activeSpec == spec)
16118 addSpell(talentInfo->RankID[currentRank], true,false,false,false);
16119 else
16121 PlayerTalent talent;
16122 talent.currentRank = currentRank;
16123 talent.m_talentEntry = talentInfo;
16124 talent.state = PLAYERSPELL_UNCHANGED;
16125 m_talents[spec][talentInfo->TalentID] = talent;
16128 while (result->NextRow());
16129 delete result;
16132 void Player::_LoadGroup(QueryResult *result)
16134 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
16135 if (result)
16137 uint32 groupId = (*result)[0].GetUInt32();
16138 delete result;
16140 if (Group* group = sObjectMgr.GetGroupById(groupId))
16142 uint8 subgroup = group->GetMemberGroup(GetGUID());
16143 SetGroup(group, subgroup);
16144 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
16146 // the group leader may change the instance difficulty while the player is offline
16147 SetDungeonDifficulty(group->GetDungeonDifficulty());
16148 SetRaidDifficulty(group->GetRaidDifficulty());
16154 void Player::_LoadBoundInstances(QueryResult *result)
16156 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16157 m_boundInstances[i].clear();
16159 Group *group = GetGroup();
16161 //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));
16162 if(result)
16166 Field *fields = result->Fetch();
16167 bool perm = fields[1].GetBool();
16168 uint32 mapId = fields[2].GetUInt32();
16169 uint32 instanceId = fields[0].GetUInt32();
16170 uint8 difficulty = fields[3].GetUInt8();
16172 time_t resetTime = (time_t)fields[4].GetUInt64();
16173 // the resettime for normal instances is only saved when the InstanceSave is unloaded
16174 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
16175 // and in that case it is not used
16177 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
16178 if(!mapEntry || !mapEntry->IsDungeon())
16180 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
16181 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16182 continue;
16185 if(difficulty >= MAX_DIFFICULTY)
16187 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
16188 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16189 continue;
16192 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
16193 if(!mapDiff)
16195 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
16196 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16197 continue;
16200 if(!perm && group)
16202 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);
16203 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
16204 continue;
16207 // since non permanent binds are always solo bind, they can always be reset
16208 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
16209 if(save) BindToInstance(save, perm, true);
16210 } while(result->NextRow());
16211 delete result;
16215 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
16217 // some instances only have one difficulty
16218 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
16219 if(!mapDiff)
16220 return NULL;
16222 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16223 if(itr != m_boundInstances[difficulty].end())
16224 return &itr->second;
16225 else
16226 return NULL;
16229 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
16231 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
16232 UnbindInstance(itr, difficulty, unload);
16235 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
16237 if(itr != m_boundInstances[difficulty].end())
16239 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
16240 itr->second.save->RemovePlayer(this); // save can become invalid
16241 m_boundInstances[difficulty].erase(itr++);
16245 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
16247 if(save)
16249 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
16250 if(bind.save)
16252 // update the save when the group kills a boss
16253 if(permanent != bind.perm || save != bind.save)
16254 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());
16256 else
16257 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
16259 if(bind.save != save)
16261 if(bind.save) bind.save->RemovePlayer(this);
16262 save->AddPlayer(this);
16265 if(permanent) save->SetCanReset(false);
16267 bind.save = save;
16268 bind.perm = permanent;
16269 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());
16270 return &bind;
16272 else
16273 return NULL;
16276 void Player::SendRaidInfo()
16278 uint32 counter = 0;
16280 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
16282 size_t p_counter = data.wpos();
16283 data << uint32(counter); // placeholder
16285 time_t now = time(NULL);
16287 for(int i = 0; i < MAX_DIFFICULTY; ++i)
16289 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16291 if(itr->second.perm)
16293 InstanceSave *save = itr->second.save;
16294 data << uint32(save->GetMapId()); // map id
16295 data << uint32(save->GetDifficulty()); // difficulty
16296 data << uint64(save->GetInstanceId()); // instance id
16297 data << uint8(1); // expired = 0
16298 data << uint8(0); // extended = 1
16299 data << uint32(save->GetResetTime() - now); // reset time
16300 ++counter;
16304 data.put<uint32>(p_counter, counter);
16305 GetSession()->SendPacket(&data);
16309 - called on every successful teleportation to a map
16311 void Player::SendSavedInstances()
16313 bool hasBeenSaved = false;
16314 WorldPacket data;
16316 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16318 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16320 if(itr->second.perm) // only permanent binds are sent
16322 hasBeenSaved = true;
16323 break;
16328 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16329 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
16330 data << uint32(hasBeenSaved);
16331 GetSession()->SendPacket(&data);
16333 if(!hasBeenSaved)
16334 return;
16336 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16338 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
16340 if(itr->second.perm)
16342 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
16343 data << uint32(itr->second.save->GetMapId());
16344 GetSession()->SendPacket(&data);
16350 /// convert the player's binds to the group
16351 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
16353 bool has_binds = false;
16354 bool has_solo = false;
16356 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
16357 ASSERT(player_guid);
16359 // copy all binds to the group, when changing leader it's assumed the character
16360 // will not have any solo binds
16362 if(player)
16364 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16366 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
16368 has_binds = true;
16369 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
16370 // permanent binds are not removed
16371 if(!itr->second.perm)
16373 // increments itr in call
16374 player->UnbindInstance(itr, Difficulty(i), true);
16375 has_solo = true;
16377 else
16378 ++itr;
16383 // if the player's not online we don't know what binds it has
16384 if(!player || !group || has_binds)
16385 CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
16387 // the following should not get executed when changing leaders
16388 if(!player || has_solo)
16389 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
16392 bool Player::_LoadHomeBind(QueryResult *result)
16394 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16395 if(!info)
16397 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16398 return false;
16401 bool ok = false;
16402 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16403 if (result)
16405 Field *fields = result->Fetch();
16406 m_homebindMapId = fields[0].GetUInt32();
16407 m_homebindAreaId = fields[1].GetUInt16();
16408 m_homebindX = fields[2].GetFloat();
16409 m_homebindY = fields[3].GetFloat();
16410 m_homebindZ = fields[4].GetFloat();
16411 delete result;
16413 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16415 // accept saved data only for valid position (and non instanceable), and accessable
16416 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16417 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16419 ok = true;
16421 else
16422 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16425 if(!ok)
16427 m_homebindMapId = info->mapId;
16428 m_homebindAreaId = info->areaId;
16429 m_homebindX = info->positionX;
16430 m_homebindY = info->positionY;
16431 m_homebindZ = info->positionZ;
16433 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_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
16436 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16437 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
16439 return true;
16442 /*********************************************************/
16443 /*** SAVE SYSTEM ***/
16444 /*********************************************************/
16446 void Player::SaveToDB()
16448 // we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16449 // delay auto save at any saves (manual, in code, or autosave)
16450 m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
16452 //lets allow only players in world to be saved
16453 if(IsBeingTeleportedFar())
16455 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16456 return;
16459 // first save/honor gain after midnight will also update the player's honor fields
16460 UpdateHonorFields();
16462 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16463 outDebugValues();
16465 CharacterDatabase.BeginTransaction();
16467 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16469 std::string sql_name = m_name;
16470 CharacterDatabase.escape_string(sql_name);
16472 std::ostringstream ss;
16473 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16474 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, "
16475 "taximask, online, cinematic, "
16476 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16477 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16478 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16479 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16480 "power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars) VALUES ("
16481 << GetGUIDLow() << ", "
16482 << GetSession()->GetAccountId() << ", '"
16483 << sql_name << "', "
16484 << (uint32)getRace() << ", "
16485 << (uint32)getClass() << ", "
16486 << (uint32)getGender() << ", "
16487 << getLevel() << ", "
16488 << GetUInt32Value(PLAYER_XP) << ", "
16489 << GetMoney() << ", "
16490 << GetUInt32Value(PLAYER_BYTES) << ", "
16491 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16492 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16494 if(!IsBeingTeleported())
16496 ss << GetMapId() << ", "
16497 << (uint32)GetDungeonDifficulty() << ", "
16498 << finiteAlways(GetPositionX()) << ", "
16499 << finiteAlways(GetPositionY()) << ", "
16500 << finiteAlways(GetPositionZ()) << ", "
16501 << finiteAlways(GetOrientation()) << ", ";
16503 else
16505 ss << GetTeleportDest().mapid << ", "
16506 << (uint32)GetDungeonDifficulty() << ", "
16507 << finiteAlways(GetTeleportDest().coord_x) << ", "
16508 << finiteAlways(GetTeleportDest().coord_y) << ", "
16509 << finiteAlways(GetTeleportDest().coord_z) << ", "
16510 << finiteAlways(GetTeleportDest().orientation) << ", ";
16513 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16515 ss << (IsInWorld() ? 1 : 0) << ", ";
16517 ss << m_cinematic << ", ";
16519 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16520 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16522 ss << finiteAlways(m_rest_bonus) << ", ";
16523 ss << (uint64)time(NULL) << ", ";
16524 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16525 //save, far from tavern/city
16526 //save, but in tavern/city
16527 ss << m_resetTalentsCost << ", ";
16528 ss << (uint64)m_resetTalentsTime << ", ";
16530 ss << finiteAlways(m_movementInfo.GetTransportPos()->x) << ", ";
16531 ss << finiteAlways(m_movementInfo.GetTransportPos()->y) << ", ";
16532 ss << finiteAlways(m_movementInfo.GetTransportPos()->z) << ", ";
16533 ss << finiteAlways(m_movementInfo.GetTransportPos()->o) << ", ";
16534 if (m_transport)
16535 ss << m_transport->GetGUIDLow();
16536 else
16537 ss << "0";
16538 ss << ", ";
16540 ss << m_ExtraFlags << ", ";
16542 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16544 ss << uint32(m_atLoginFlags) << ", ";
16546 ss << GetZoneId() << ", ";
16548 ss << (uint64)m_deathExpireTime << ", '";
16550 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16552 ss << GetArenaPoints() << ", ";
16554 ss << GetHonorPoints() << ", ";
16556 ss << GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) << ", ";
16558 ss << GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION) << ", ";
16560 ss << GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS) << ", ";
16562 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 0) << ", ";
16564 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 1) << ", ";
16566 ss << GetUInt32Value(PLAYER_CHOSEN_TITLE) << ", ";
16568 ss << GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES) << ", ";
16570 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16571 ss << GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX) << ", ";
16573 ss << (uint16)(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE) << ", ";
16575 ss << GetHealth();
16577 for(uint32 i = 0; i < MAX_POWERS; ++i)
16578 ss << "," << GetPower(Powers(i));
16580 ss << ", ";
16581 ss << uint32(m_specsCount) << ", ";
16582 ss << uint32(m_activeSpec) << ", '";
16583 for(uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i )
16585 ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << " ";
16588 ss << "', '";
16589 for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i )
16591 ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " ";
16594 ss << "',";
16595 ss << GetUInt32Value(PLAYER_AMMO_ID) << ", '";
16596 for(uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i )
16598 ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << " ";
16600 ss << "',";
16601 ss << uint32(GetByteValue(PLAYER_FIELD_BYTES, 2));
16602 ss << ")";
16604 CharacterDatabase.Execute( ss.str().c_str() );
16606 if (m_mailsUpdated) //save mails only when needed
16607 _SaveMail();
16609 _SaveBGData();
16610 _SaveInventory();
16611 _SaveQuestStatus();
16612 _SaveDailyQuestStatus();
16613 _SaveWeeklyQuestStatus();
16614 _SaveSpells();
16615 _SaveSpellCooldowns();
16616 _SaveActions();
16617 _SaveAuras();
16618 _SaveSkills();
16619 m_achievementMgr.SaveToDB();
16620 m_reputationMgr.SaveToDB();
16621 _SaveEquipmentSets();
16622 GetSession()->SaveTutorialsData(); // changed only while character in game
16623 _SaveGlyphs();
16624 _SaveTalents();
16626 CharacterDatabase.CommitTransaction();
16628 // check if stats should only be saved on logout
16629 // save stats can be out of transaction
16630 if (m_session->isLogingOut() || !sWorld.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT))
16631 _SaveStats();
16633 // save pet (hunter pet level and experience and all type pets health/mana).
16634 if (Pet* pet = GetPet())
16635 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16638 // fast save function for item/money cheating preventing - save only inventory and money state
16639 void Player::SaveInventoryAndGoldToDB()
16641 _SaveInventory();
16642 SaveGoldToDB();
16645 void Player::SaveGoldToDB()
16647 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16650 void Player::_SaveActions()
16652 for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
16654 for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
16656 switch (itr->second.uState)
16658 case ACTIONBUTTON_NEW:
16659 CharacterDatabase.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16660 GetGUIDLow(), i, (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16661 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16662 ++itr;
16663 break;
16664 case ACTIONBUTTON_CHANGED:
16665 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16666 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first, i );
16667 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16668 ++itr;
16669 break;
16670 case ACTIONBUTTON_DELETED:
16671 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32)itr->first, i);
16672 m_actionButtons[i].erase(itr++);
16673 break;
16674 default:
16675 ++itr;
16676 break;
16682 void Player::_SaveAuras()
16684 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16686 AuraMap const& auras = GetAuras();
16688 if (auras.empty())
16689 return;
16691 spellEffectPair lastEffectPair = auras.begin()->first;
16692 uint32 stackCounter = 1;
16694 /* copied following sql-code partly from achievementmgr */
16695 bool first_round = true;
16696 std::ostringstream ss;
16697 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16699 if(itr == auras.end() || lastEffectPair != itr->first)
16701 AuraMap::const_iterator itr2 = itr;
16702 // save previous spellEffectPair to db
16703 itr2--;
16705 //skip all auras from spells that are passive
16706 //do not save single target auras (unless they were cast by the player)
16707 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16709 if (first_round)
16711 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16712 first_round = false;
16714 // next new/changed record prefix
16715 else
16716 ss << ", ";
16718 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16719 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16720 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16721 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16722 << int(itr2->second->GetAuraCharges()) << ")";
16725 if(itr == auras.end())
16726 break;
16729 if (lastEffectPair == itr->first)
16730 stackCounter++;
16731 else
16733 lastEffectPair = itr->first;
16734 stackCounter = 1;
16738 // if something changed execute
16739 if (!first_round)
16740 CharacterDatabase.Execute( ss.str().c_str() );
16743 void Player::_SaveGlyphs()
16746 for (uint8 spec = 0; spec < m_specsCount; ++spec)
16748 for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
16750 switch(m_glyphs[spec][slot].uState)
16752 case GLYPH_NEW:
16753 CharacterDatabase.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId());
16754 break;
16755 case GLYPH_CHANGED:
16756 CharacterDatabase.PExecute("UPDATE character_glyphs SET glyph = '%u' WHERE guid='%u' AND spec = '%u' AND slot = '%u'", m_glyphs[spec][slot].GetId(), GetGUIDLow(), spec, slot);
16757 break;
16758 case GLYPH_DELETED:
16759 CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec, slot);
16760 break;
16761 case GLYPH_UNCHANGED:
16762 break;
16764 m_glyphs[spec][slot].uState = GLYPH_UNCHANGED;
16769 void Player::_SaveInventory()
16771 // force items in buyback slots to new state
16772 // and remove those that aren't already
16773 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16775 Item *item = m_items[i];
16776 if (!item || item->GetState() == ITEM_NEW) continue;
16777 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16778 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16779 m_items[i]->FSetState(ITEM_NEW);
16782 // update enchantment durations
16783 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16785 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16788 // if no changes
16789 if (m_itemUpdateQueue.empty()) return;
16791 // do not save if the update queue is corrupt
16792 bool error = false;
16793 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16795 Item *item = m_itemUpdateQueue[i];
16796 if(!item || item->GetState() == ITEM_REMOVED) continue;
16797 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16799 if (test == NULL)
16801 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());
16802 error = true;
16804 else if (test != item)
16806 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());
16807 error = true;
16811 if (error)
16813 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16814 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16815 return;
16818 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16820 Item *item = m_itemUpdateQueue[i];
16821 if(!item) continue;
16823 Bag *container = item->GetContainer();
16824 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16826 switch(item->GetState())
16828 case ITEM_NEW:
16829 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());
16830 break;
16831 case ITEM_CHANGED:
16832 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());
16833 break;
16834 case ITEM_REMOVED:
16835 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16836 break;
16837 case ITEM_UNCHANGED:
16838 break;
16841 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16843 m_itemUpdateQueue.clear();
16846 void Player::_SaveMail()
16848 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16850 Mail *m = (*itr);
16851 if (m->state == MAIL_STATE_CHANGED)
16853 CharacterDatabase.PExecute("UPDATE mail SET has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
16854 m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16855 if(m->removedItems.size())
16857 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16858 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16859 m->removedItems.clear();
16861 m->state = MAIL_STATE_UNCHANGED;
16863 else if (m->state == MAIL_STATE_DELETED)
16865 if (m->HasItems())
16866 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16867 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16869 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16870 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16874 //deallocate deleted mails...
16875 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16877 if ((*itr)->state == MAIL_STATE_DELETED)
16879 Mail* m = *itr;
16880 m_mail.erase(itr);
16881 delete m;
16882 itr = m_mail.begin();
16884 else
16885 ++itr;
16888 m_mailsUpdated = false;
16891 void Player::_SaveQuestStatus()
16893 // we don't need transactions here.
16894 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16896 switch (i->second.uState)
16898 case QUEST_NEW :
16899 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16900 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16901 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILLISECONDS+ 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]);
16902 break;
16903 case QUEST_CHANGED :
16904 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
16905 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILLISECONDS + 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 );
16906 break;
16907 case QUEST_UNCHANGED:
16908 break;
16910 i->second.uState = QUEST_UNCHANGED;
16914 void Player::_SaveDailyQuestStatus()
16916 if (!m_DailyQuestChanged)
16917 return;
16919 // we don't need transactions here.
16920 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16921 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16922 if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16923 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest) VALUES ('%u', '%u')",
16924 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx));
16926 m_DailyQuestChanged = false;
16929 void Player::_SaveWeeklyQuestStatus()
16931 if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
16932 return;
16934 // we don't need transactions here.
16935 CharacterDatabase.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'",GetGUIDLow());
16937 for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
16939 uint32 quest_id = *iter;
16941 CharacterDatabase.PExecute("INSERT INTO character_queststatus_weekly (guid,quest) VALUES ('%u', '%u')", GetGUIDLow(), quest_id);
16944 m_WeeklyQuestChanged = false;
16947 void Player::_SaveSkills()
16949 // we don't need transactions here.
16950 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16952 if(itr->second.uState == SKILL_UNCHANGED)
16954 ++itr;
16955 continue;
16958 if(itr->second.uState == SKILL_DELETED)
16960 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16961 mSkillStatus.erase(itr++);
16962 continue;
16965 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16966 uint16 value = SKILL_VALUE(valueData);
16967 uint16 max = SKILL_MAX(valueData);
16969 switch (itr->second.uState)
16971 case SKILL_NEW:
16972 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16973 GetGUIDLow(), itr->first, value, max);
16974 break;
16975 case SKILL_CHANGED:
16976 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16977 value, max, GetGUIDLow(), itr->first );
16978 break;
16980 itr->second.uState = SKILL_UNCHANGED;
16982 ++itr;
16986 void Player::_SaveSpells()
16988 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16990 uint32 talentCosts = GetTalentSpellCost(itr->first);
16992 if (!talentCosts)
16994 if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
16995 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16997 // add only changed/new not dependent spells
16998 if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
16999 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);
17002 if (itr->second.state == PLAYERSPELL_REMOVED)
17003 m_spells.erase(itr++);
17004 else
17006 itr->second.state = PLAYERSPELL_UNCHANGED;
17007 ++itr;
17013 void Player::_SaveTalents()
17015 for (int32 i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
17017 for (PlayerTalentMap::iterator itr = m_talents[i].begin(); itr != m_talents[i].end();)
17019 if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
17020 CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' and talent_id = '%u' and spec = '%u'", GetGUIDLow(),itr->first, i);
17022 // add only changed/new talents
17023 if (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED)
17024 CharacterDatabase.PExecute("INSERT INTO character_talent (guid, talent_id, current_rank , spec) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second.currentRank, i);
17026 if (itr->second.state == PLAYERSPELL_REMOVED)
17027 m_talents[i].erase(itr++);
17028 else
17030 itr->second.state = PLAYERSPELL_UNCHANGED;
17031 ++itr;
17037 // save player stats -- only for external usage
17038 // real stats will be recalculated on player login
17039 void Player::_SaveStats()
17041 // check if stat saving is enabled and if char level is high enough
17042 if(!sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE))
17043 return;
17045 CharacterDatabase.PExecute("DELETE FROM character_stats WHERE guid = '%u'", GetGUIDLow());
17046 std::ostringstream ss;
17047 ss << "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, "
17048 "strength, agility, stamina, intellect, spirit, armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, "
17049 "blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, spellPower) VALUES ("
17050 << GetGUIDLow() << ", "
17051 << GetMaxHealth() << ", ";
17052 for(int i = 0; i < MAX_POWERS; ++i)
17053 ss << GetMaxPower(Powers(i)) << ", ";
17054 for(int i = 0; i < MAX_STATS; ++i)
17055 ss << GetStat(Stats(i)) << ", ";
17056 // armor + school resistances
17057 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
17058 ss << GetResistance(SpellSchools(i)) << ",";
17059 ss << GetFloatValue(PLAYER_BLOCK_PERCENTAGE) << ", "
17060 << GetFloatValue(PLAYER_DODGE_PERCENTAGE) << ", "
17061 << GetFloatValue(PLAYER_PARRY_PERCENTAGE) << ", "
17062 << GetFloatValue(PLAYER_CRIT_PERCENTAGE) << ", "
17063 << GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE) << ", "
17064 << GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1) << ", "
17065 << GetUInt32Value(UNIT_FIELD_ATTACK_POWER) << ", "
17066 << GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) << ", "
17067 << GetBaseSpellPowerBonus() << ")";
17068 CharacterDatabase.Execute( ss.str().c_str() );
17071 void Player::outDebugValues() const
17073 if(!sLog.IsOutDebug()) // optimize disabled debug output
17074 return;
17076 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
17077 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
17078 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
17079 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
17080 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
17081 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
17082 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
17083 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
17084 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
17085 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
17086 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
17087 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
17090 /*********************************************************/
17091 /*** FLOOD FILTER SYSTEM ***/
17092 /*********************************************************/
17094 void Player::UpdateSpeakTime()
17096 // ignore chat spam protection for GMs in any mode
17097 if(GetSession()->GetSecurity() > SEC_PLAYER)
17098 return;
17100 time_t current = time (NULL);
17101 if(m_speakTime > current)
17103 uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT);
17104 if(!max_count)
17105 return;
17107 ++m_speakCount;
17108 if(m_speakCount >= max_count)
17110 // prevent overwrite mute time, if message send just before mutes set, for example.
17111 time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME);
17112 if(GetSession()->m_muteTime < new_mute)
17113 GetSession()->m_muteTime = new_mute;
17115 m_speakCount = 0;
17118 else
17119 m_speakCount = 0;
17121 m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY);
17124 bool Player::CanSpeak() const
17126 return GetSession()->m_muteTime <= time (NULL);
17129 /*********************************************************/
17130 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
17131 /*********************************************************/
17133 void Player::SendAttackSwingNotInRange()
17135 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
17136 GetSession()->SendPacket( &data );
17139 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
17141 std::ostringstream ss;
17142 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
17143 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
17144 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
17145 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
17146 sLog.outDebug("%s", ss.str().c_str());
17147 CharacterDatabase.Execute(ss.str().c_str());
17150 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
17152 char buf[11];
17153 snprintf(buf,11,"%u",value);
17155 if(index >= tokens.size())
17156 return;
17158 tokens[index] = buf;
17161 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
17163 // 0
17164 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
17165 if(!result)
17166 return;
17168 Field* fields = result->Fetch();
17170 uint32 player_bytes2 = fields[0].GetUInt32();
17171 player_bytes2 &= ~0xFF;
17172 player_bytes2 |= facialHair;
17174 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
17176 delete result;
17179 void Player::SendAttackSwingDeadTarget()
17181 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
17182 GetSession()->SendPacket( &data );
17185 void Player::SendAttackSwingCantAttack()
17187 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
17188 GetSession()->SendPacket( &data );
17191 void Player::SendAttackSwingCancelAttack()
17193 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
17194 GetSession()->SendPacket( &data );
17197 void Player::SendAttackSwingBadFacingAttack()
17199 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
17200 GetSession()->SendPacket( &data );
17203 void Player::SendAutoRepeatCancel(Unit *target)
17205 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
17206 data << target->GetPackGUID(); // may be it's target guid
17207 GetSession()->SendPacket( &data );
17210 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
17212 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
17213 data << uint32(Area);
17214 data << uint32(Experience);
17215 GetSession()->SendPacket(&data);
17218 void Player::SendDungeonDifficulty(bool IsInGroup)
17220 uint8 val = 0x00000001;
17221 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
17222 data << uint32(GetDungeonDifficulty());
17223 data << uint32(val);
17224 data << uint32(IsInGroup);
17225 GetSession()->SendPacket(&data);
17228 void Player::SendRaidDifficulty(bool IsInGroup)
17230 uint8 val = 0x00000001;
17231 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
17232 data << uint32(GetRaidDifficulty());
17233 data << uint32(val);
17234 data << uint32(IsInGroup);
17235 GetSession()->SendPacket(&data);
17238 void Player::SendResetFailedNotify(uint32 mapid)
17240 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
17241 data << uint32(mapid);
17242 GetSession()->SendPacket(&data);
17245 /// Reset all solo instances and optionally send a message on success for each
17246 void Player::ResetInstances(uint8 method, bool isRaid)
17248 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
17250 // we assume that when the difficulty changes, all instances that can be reset will be
17251 Difficulty diff = GetDifficulty(isRaid);
17253 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
17255 InstanceSave *p = itr->second.save;
17256 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
17257 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
17259 ++itr;
17260 continue;
17263 if(method == INSTANCE_RESET_ALL)
17265 // the "reset all instances" method can only reset normal maps
17266 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
17268 ++itr;
17269 continue;
17273 // if the map is loaded, reset it
17274 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
17275 if(map && map->IsDungeon())
17276 ((InstanceMap*)map)->Reset(method);
17278 // since this is a solo instance there should not be any players inside
17279 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
17280 SendResetInstanceSuccess(p->GetMapId());
17282 p->DeleteFromDB();
17283 m_boundInstances[diff].erase(itr++);
17285 // the following should remove the instance save from the manager and delete it as well
17286 p->RemovePlayer(this);
17290 void Player::SendResetInstanceSuccess(uint32 MapId)
17292 WorldPacket data(SMSG_INSTANCE_RESET, 4);
17293 data << uint32(MapId);
17294 GetSession()->SendPacket(&data);
17297 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
17299 // TODO: find what other fail reasons there are besides players in the instance
17300 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
17301 data << uint32(reason);
17302 data << uint32(MapId);
17303 GetSession()->SendPacket(&data);
17306 /*********************************************************/
17307 /*** Update timers ***/
17308 /*********************************************************/
17310 ///checks the 15 afk reports per 5 minutes limit
17311 void Player::UpdateAfkReport(time_t currTime)
17313 if(m_bgData.bgAfkReportedTimer <= currTime)
17315 m_bgData.bgAfkReportedCount = 0;
17316 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
17320 void Player::UpdateContestedPvP(uint32 diff)
17322 if(!m_contestedPvPTimer||isInCombat())
17323 return;
17324 if(m_contestedPvPTimer <= diff)
17326 ResetContestedPvP();
17328 else
17329 m_contestedPvPTimer -= diff;
17332 void Player::UpdatePvPFlag(time_t currTime)
17334 if(!IsPvP())
17335 return;
17336 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
17337 return;
17339 UpdatePvP(false);
17342 void Player::UpdateDuelFlag(time_t currTime)
17344 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
17345 return;
17347 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
17348 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
17350 duel->startTimer = 0;
17351 duel->startTime = currTime;
17352 duel->opponent->duel->startTimer = 0;
17353 duel->opponent->duel->startTime = currTime;
17356 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
17358 if (!pet)
17359 pet = GetPet();
17361 if (!pet || pet->GetOwnerGUID() != GetGUID())
17362 return;
17364 // not save secondary permanent pet as current
17365 if (pet && m_temporaryUnsummonedPetNumber && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
17366 mode = PET_SAVE_NOT_IN_SLOT;
17368 if (returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
17370 //returning of reagents only for players, so best done here
17371 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
17372 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
17374 if(spellInfo)
17376 for(uint32 i = 0; i < 7; ++i)
17378 if(spellInfo->Reagent[i] > 0)
17380 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17381 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
17382 if( msg == EQUIP_ERR_OK )
17384 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
17385 if(IsInWorld())
17386 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
17393 // only if current pet in slot
17394 switch(pet->getPetType())
17396 case MINI_PET:
17397 m_miniPet = 0;
17398 break;
17399 case GUARDIAN_PET:
17400 RemoveGuardian(pet);
17401 break;
17402 default:
17403 if (GetPetGUID() == pet->GetGUID())
17404 SetPet(NULL);
17405 break;
17408 pet->CombatStop();
17410 pet->SavePetToDB(mode);
17412 pet->AddObjectToRemoveList();
17413 pet->m_removed = true;
17415 if (pet->isControlled())
17417 RemovePetActionBar();
17419 if(GetGroup())
17420 SetGroupUpdateFlag(GROUP_UPDATE_PET);
17424 void Player::RemoveMiniPet()
17426 if (Pet* pet = GetMiniPet())
17428 pet->Remove(PET_SAVE_AS_DELETED);
17429 m_miniPet = 0;
17433 Pet* Player::GetMiniPet()
17435 if (!m_miniPet)
17436 return NULL;
17438 return GetMap()->GetPet(m_miniPet);
17441 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
17443 *data << (uint8)msgtype;
17444 *data << (uint32)language;
17445 *data << (uint64)GetGUID();
17446 *data << (uint32)language; //language 2.1.0 ?
17447 *data << (uint64)GetGUID();
17448 *data << (uint32)(text.length()+1);
17449 *data << text;
17450 *data << (uint8)chatTag();
17453 void Player::Say(const std::string& text, const uint32 language)
17455 WorldPacket data(SMSG_MESSAGECHAT, 200);
17456 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
17457 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
17460 void Player::Yell(const std::string& text, const uint32 language)
17462 WorldPacket data(SMSG_MESSAGECHAT, 200);
17463 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
17464 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
17467 void Player::TextEmote(const std::string& text)
17469 WorldPacket data(SMSG_MESSAGECHAT, 200);
17470 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
17471 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
17474 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
17476 if (language != LANG_ADDON) // if not addon data
17477 language = LANG_UNIVERSAL; // whispers should always be readable
17479 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
17481 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17482 if(!rPlayer->isDND() || isGameMaster())
17484 WorldPacket data(SMSG_MESSAGECHAT, 200);
17485 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
17486 rPlayer->GetSession()->SendPacket(&data);
17488 // not send confirmation for addon messages
17489 if (language != LANG_ADDON)
17491 data.Initialize(SMSG_MESSAGECHAT, 200);
17492 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
17493 GetSession()->SendPacket(&data);
17496 else
17498 // announce to player that player he is whispering to is dnd and cannot receive his message
17499 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17502 if(!isAcceptWhispers())
17504 SetAcceptWhispers(true);
17505 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17508 // announce to player that player he is whispering to is afk
17509 if(rPlayer->isAFK())
17510 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17512 // if player whisper someone, auto turn of dnd to be able to receive an answer
17513 if(isDND() && !rPlayer->isGameMaster())
17514 ToggleDND();
17517 void Player::PetSpellInitialize()
17519 Pet* pet = GetPet();
17521 if(!pet)
17522 return;
17524 sLog.outDebug("Pet Spells Groups");
17526 CharmInfo *charmInfo = pet->GetCharmInfo();
17528 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17529 data << uint64(pet->GetGUID());
17530 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17531 data << uint32(0);
17532 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17534 // action bar loop
17535 charmInfo->BuildActionBar(&data);
17537 size_t spellsCountPos = data.wpos();
17539 // spells count
17540 uint8 addlist = 0;
17541 data << uint8(addlist); // placeholder
17543 if (pet->IsPermanentPetFor(this))
17545 // spells loop
17546 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17548 if(itr->second.state == PETSPELL_REMOVED)
17549 continue;
17551 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17552 ++addlist;
17556 data.put<uint8>(spellsCountPos, addlist);
17558 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17559 data << uint8(cooldownsCount);
17561 time_t curTime = time(NULL);
17563 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17565 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
17567 data << uint32(itr->first); // spellid
17568 data << uint16(0); // spell category?
17569 data << uint32(cooldown); // cooldown
17570 data << uint32(0); // category cooldown
17573 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17575 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
17577 data << uint32(itr->first); // spellid
17578 data << uint16(0); // spell category?
17579 data << uint32(0); // cooldown
17580 data << uint32(cooldown); // category cooldown
17583 GetSession()->SendPacket(&data);
17586 void Player::SendPetGUIDs()
17588 if(!GetPetGUID())
17589 return;
17591 // Later this function might get modified for multiple guids
17592 WorldPacket data(SMSG_PET_GUIDS, 12);
17593 data << uint32(1); // count
17594 data << uint64(GetPetGUID());
17595 GetSession()->SendPacket(&data);
17598 void Player::PossessSpellInitialize()
17600 Unit* charm = GetCharm();
17602 if(!charm)
17603 return;
17605 CharmInfo *charmInfo = charm->GetCharmInfo();
17607 if(!charmInfo)
17609 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17610 return;
17613 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17614 data << uint64(charm->GetGUID());
17615 data << uint16(0);
17616 data << uint32(0);
17617 data << uint32(0);
17619 charmInfo->BuildActionBar(&data);
17621 data << uint8(0); // spells count
17622 data << uint8(0); // cooldowns count
17624 GetSession()->SendPacket(&data);
17627 void Player::CharmSpellInitialize()
17629 Unit* charm = GetCharm();
17631 if(!charm)
17632 return;
17634 CharmInfo *charmInfo = charm->GetCharmInfo();
17635 if(!charmInfo)
17637 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17638 return;
17641 uint8 addlist = 0;
17643 if(charm->GetTypeId() != TYPEID_PLAYER)
17645 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17647 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17649 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17651 if(charmInfo->GetCharmSpell(i)->GetAction())
17652 ++addlist;
17657 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17658 data << uint64(charm->GetGUID());
17659 data << uint16(0);
17660 data << uint32(0);
17662 if(charm->GetTypeId() != TYPEID_PLAYER)
17663 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17664 else
17665 data << uint8(0) << uint8(0) << uint16(0);
17667 charmInfo->BuildActionBar(&data);
17669 data << uint8(addlist);
17671 if(addlist)
17673 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17675 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17676 if(cspell->GetAction())
17677 data << uint32(cspell->packedData);
17681 data << uint8(0); // cooldowns count
17683 GetSession()->SendPacket(&data);
17686 void Player::RemovePetActionBar()
17688 WorldPacket data(SMSG_PET_SPELLS, 8);
17689 data << uint64(0);
17690 SendDirectMessage(&data);
17693 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17695 if (!mod || !spellInfo)
17696 return false;
17698 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17700 // prevent apply to any spell except spell that trigger expire
17701 if(spell)
17703 if(mod->lastAffected != spell)
17704 return false;
17706 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17707 return false;
17710 return mod->isAffectedOnSpell(spellInfo);
17713 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17715 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17717 for(int eff = 0; eff < 96; ++eff)
17719 uint64 _mask = 0;
17720 uint32 _mask2= 0;
17722 if (eff < 64)
17723 _mask = uint64(1) << (eff - 0);
17724 else
17725 _mask2= uint32(1) << (eff - 64);
17727 if ( mod->mask & _mask || mod->mask2 & _mask2)
17729 int32 val = 0;
17730 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17732 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17733 val += (*itr)->value;
17735 val += apply ? mod->value : -(mod->value);
17736 WorldPacket data(Opcode, (1+1+4));
17737 data << uint8(eff);
17738 data << uint8(mod->op);
17739 data << int32(val);
17740 SendDirectMessage(&data);
17744 if (apply)
17745 m_spellMods[mod->op].push_back(mod);
17746 else
17748 if (mod->charges == -1)
17749 --m_SpellModRemoveCount;
17750 m_spellMods[mod->op].remove(mod);
17751 delete mod;
17755 void Player::RemoveSpellMods(Spell const* spell)
17757 if(!spell || (m_SpellModRemoveCount == 0))
17758 return;
17760 for(int i=0;i<MAX_SPELLMOD;++i)
17762 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17764 SpellModifier *mod = *itr;
17765 ++itr;
17767 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17769 RemoveAurasDueToSpell(mod->spellId);
17770 if (m_spellMods[i].empty())
17771 break;
17772 else
17773 itr = m_spellMods[i].begin();
17779 // send Proficiency
17780 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17782 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17783 data << uint8(pr1) << uint32(pr2);
17784 GetSession()->SendPacket (&data);
17787 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17789 QueryResult *result = NULL;
17790 if(type == 10)
17791 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17792 else
17793 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17794 if(result)
17796 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.
17797 { // and SendPetitionQueryOpcode reads data from the DB
17798 Field *fields = result->Fetch();
17799 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17800 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17802 // send update if charter owner in game
17803 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17804 if(owner)
17805 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17807 } while ( result->NextRow() );
17809 delete result;
17811 if(type==10)
17812 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17813 else
17814 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17817 CharacterDatabase.BeginTransaction();
17818 if(type == 10)
17820 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17821 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17823 else
17825 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17826 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17828 CharacterDatabase.CommitTransaction();
17831 void Player::LeaveAllArenaTeams(uint64 guid)
17833 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));
17834 if(!result)
17835 return;
17839 Field *fields = result->Fetch();
17840 uint32 at_id = fields[0].GetUInt32();
17841 if(at_id != 0)
17843 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17844 if(at)
17845 at->DelMember(guid);
17847 } while (result->NextRow());
17849 delete result;
17852 void Player::SetRestBonus (float rest_bonus_new)
17854 // Prevent resting on max level
17855 if(getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
17856 rest_bonus_new = 0;
17858 if(rest_bonus_new < 0)
17859 rest_bonus_new = 0;
17861 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f;
17863 if(rest_bonus_new > rest_bonus_max)
17864 m_rest_bonus = rest_bonus_max;
17865 else
17866 m_rest_bonus = rest_bonus_new;
17868 // update data for client
17869 if(m_rest_bonus>10)
17870 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17871 else if(m_rest_bonus<=1)
17872 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17874 //RestTickUpdate
17875 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17878 void Player::HandleStealthedUnitsDetection()
17880 std::list<Unit*> stealthedUnits;
17882 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17883 Cell cell(p);
17884 cell.data.Part.reserved = ALL_DISTRICT;
17885 cell.SetNoCreate();
17887 MaNGOS::AnyStealthedCheck u_check;
17888 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17890 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17891 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17893 cell.Visit(p, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17894 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17896 WorldObject const* viewPoint = GetViewPoint();
17898 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17900 if((*i)==this)
17901 continue;
17903 bool hasAtClient = HaveAtClient((*i));
17904 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17906 if (hasDetected)
17908 if(!hasAtClient)
17910 ObjectGuid i_guid = (*i)->GetGUID();
17911 (*i)->SendCreateUpdateToPlayer(this);
17912 m_clientGUIDs.insert(i_guid);
17914 #ifdef MANGOS_DEBUG
17915 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17916 sLog.outDebug("%s is detected in stealth by player %u. Distance = %f",i_guid.GetString().c_str(),GetGUIDLow(),GetDistance(*i));
17917 #endif
17919 // target aura duration for caster show only if target exist at caster client
17920 // send data at target visibility change (adding to client)
17921 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17922 SendAurasForTarget(*i);
17925 else
17927 if(hasAtClient)
17929 (*i)->DestroyForPlayer(this);
17930 m_clientGUIDs.erase((*i)->GetGUID());
17936 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17938 if(nodes.size() < 2)
17939 return false;
17941 // 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
17942 if(GetSession()->isLogingOut() || isInCombat())
17944 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17945 data << uint32(ERR_TAXIPLAYERBUSY);
17946 GetSession()->SendPacket(&data);
17947 return false;
17950 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17951 return false;
17953 // taximaster case
17954 if(npc)
17956 // not let cheating with start flight mounted
17957 if(IsMounted())
17959 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17960 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17961 GetSession()->SendPacket(&data);
17962 return false;
17965 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17967 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17968 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17969 GetSession()->SendPacket(&data);
17970 return false;
17973 // 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
17974 if(IsNonMeleeSpellCasted(false))
17976 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17977 data << uint32(ERR_TAXIPLAYERBUSY);
17978 GetSession()->SendPacket(&data);
17979 return false;
17982 // cast case or scripted call case
17983 else
17985 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17987 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17988 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17990 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17991 if (spell->m_spellInfo->Id != spellid)
17992 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17994 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17996 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17997 if (spell->m_spellInfo->Id != spellid)
17998 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
18001 uint32 sourcenode = nodes[0];
18003 // starting node too far away (cheat?)
18004 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
18005 if (!node)
18007 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18008 data << uint32(ERR_TAXINOSUCHPATH);
18009 GetSession()->SendPacket(&data);
18010 return false;
18013 // check node starting pos data set case if provided
18014 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
18016 if (node->map_id != GetMapId() ||
18017 (node->x - GetPositionX())*(node->x - GetPositionX())+
18018 (node->y - GetPositionY())*(node->y - GetPositionY())+
18019 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
18020 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
18022 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18023 data << uint32(ERR_TAXITOOFARAWAY);
18024 GetSession()->SendPacket(&data);
18025 return false;
18028 // node must have pos if taxi master case (npc != NULL)
18029 else if (npc)
18031 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18032 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
18033 GetSession()->SendPacket(&data);
18034 return false;
18037 // Prepare to flight start now
18039 // stop combat at start taxi flight if any
18040 CombatStop();
18042 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
18043 TradeCancel(true);
18045 // clean not finished taxi path if any
18046 m_taxi.ClearTaxiDestinations();
18048 // 0 element current node
18049 m_taxi.AddTaxiDestination(sourcenode);
18051 // fill destinations path tail
18052 uint32 sourcepath = 0;
18053 uint32 totalcost = 0;
18055 uint32 prevnode = sourcenode;
18056 uint32 lastnode = 0;
18058 for(uint32 i = 1; i < nodes.size(); ++i)
18060 uint32 path, cost;
18062 lastnode = nodes[i];
18063 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
18065 if(!path)
18067 m_taxi.ClearTaxiDestinations();
18068 return false;
18071 totalcost += cost;
18073 if(prevnode == sourcenode)
18074 sourcepath = path;
18076 m_taxi.AddTaxiDestination(lastnode);
18078 prevnode = lastnode;
18081 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
18082 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
18084 // in spell case allow 0 model
18085 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
18087 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18088 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
18089 GetSession()->SendPacket(&data);
18090 m_taxi.ClearTaxiDestinations();
18091 return false;
18094 uint32 money = GetMoney();
18096 if (npc)
18097 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
18099 if(money < totalcost)
18101 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18102 data << uint32(ERR_TAXINOTENOUGHMONEY);
18103 GetSession()->SendPacket(&data);
18104 m_taxi.ClearTaxiDestinations();
18105 return false;
18108 //Checks and preparations done, DO FLIGHT
18109 ModifyMoney(-(int32)totalcost);
18110 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
18111 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
18113 // prevent stealth flight
18114 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
18116 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
18117 data << uint32(ERR_TAXIOK);
18118 GetSession()->SendPacket(&data);
18120 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
18122 GetSession()->SendDoFlight(mount_display_id, sourcepath);
18124 return true;
18127 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
18129 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
18130 if(!entry)
18131 return false;
18133 std::vector<uint32> nodes;
18135 nodes.resize(2);
18136 nodes[0] = entry->from;
18137 nodes[1] = entry->to;
18139 return ActivateTaxiPathTo(nodes,NULL,spellid);
18142 void Player::ContinueTaxiFlight()
18144 uint32 sourceNode = m_taxi.GetTaxiSource();
18145 if (!sourceNode)
18146 return;
18148 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
18150 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
18151 uint32 path = m_taxi.GetCurrentTaxiPath();
18153 // search appropriate start path node
18154 uint32 startNode = 0;
18156 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
18158 float distPrev = MAP_SIZE*MAP_SIZE;
18159 float distNext =
18160 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
18161 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
18162 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
18164 for(uint32 i = 1; i < nodeList.size(); ++i)
18166 TaxiPathNode const& node = nodeList[i];
18167 TaxiPathNode const& prevNode = nodeList[i-1];
18169 // skip nodes at another map
18170 if(node.mapid != GetMapId())
18171 continue;
18173 distPrev = distNext;
18175 distNext =
18176 (node.x-GetPositionX())*(node.x-GetPositionX())+
18177 (node.y-GetPositionY())*(node.y-GetPositionY())+
18178 (node.z-GetPositionZ())*(node.z-GetPositionZ());
18180 float distNodes =
18181 (node.x-prevNode.x)*(node.x-prevNode.x)+
18182 (node.y-prevNode.y)*(node.y-prevNode.y)+
18183 (node.z-prevNode.z)*(node.z-prevNode.z);
18185 if(distNext + distPrev < distNodes)
18187 startNode = i;
18188 break;
18192 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
18195 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
18197 // last check 2.0.10
18198 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
18199 data << uint64(GetGUID());
18200 data << uint8(0x0); // flags (0x1, 0x2)
18201 time_t curTime = time(NULL);
18202 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18204 if (itr->second.state == PLAYERSPELL_REMOVED)
18205 continue;
18206 uint32 unSpellId = itr->first;
18207 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
18208 if (!spellInfo)
18210 ASSERT(spellInfo);
18211 continue;
18214 // Not send cooldown for this spells
18215 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
18216 continue;
18218 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
18220 data << uint32(unSpellId);
18221 data << uint32(unTimeMs); // in m.secs
18222 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS);
18225 GetSession()->SendPacket(&data);
18228 void Player::InitDataForForm(bool reapplyMods)
18230 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
18231 if(ssEntry && ssEntry->attackSpeed)
18233 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
18234 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
18235 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
18237 else
18238 SetRegularAttackTime();
18240 switch(m_form)
18242 case FORM_CAT:
18244 if(getPowerType()!=POWER_ENERGY)
18245 setPowerType(POWER_ENERGY);
18246 break;
18248 case FORM_BEAR:
18249 case FORM_DIREBEAR:
18251 if(getPowerType()!=POWER_RAGE)
18252 setPowerType(POWER_RAGE);
18253 break;
18255 default: // 0, for example
18257 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
18258 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
18259 setPowerType(Powers(cEntry->powerType));
18260 break;
18264 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
18265 if (!reapplyMods)
18266 UpdateEquipSpellsAtFormChange();
18268 UpdateAttackPowerAndDamage();
18269 UpdateAttackPowerAndDamage(true);
18272 void Player::InitDisplayIds()
18274 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
18275 if(!info)
18277 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
18278 return;
18281 uint8 gender = getGender();
18282 switch(gender)
18284 case GENDER_FEMALE:
18285 SetDisplayId(info->displayId_f );
18286 SetNativeDisplayId(info->displayId_f );
18287 break;
18288 case GENDER_MALE:
18289 SetDisplayId(info->displayId_m );
18290 SetNativeDisplayId(info->displayId_m );
18291 break;
18292 default:
18293 sLog.outError("Invalid gender %u for player",gender);
18294 return;
18298 // Return true is the bought item has a max count to force refresh of window by caller
18299 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
18301 // cheating attempt
18302 if (count < 1) count = 1;
18304 if (!isAlive())
18305 return false;
18307 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
18308 if (!pProto)
18310 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
18311 return false;
18314 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
18315 if (!pCreature)
18317 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
18318 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
18319 return false;
18322 VendorItemData const* vItems = pCreature->GetVendorItems();
18323 if(!vItems || vItems->Empty())
18325 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18326 return false;
18329 size_t vendor_slot = vItems->FindItemSlot(item);
18330 if (vendor_slot >= vItems->GetItemCount())
18332 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
18333 return false;
18336 VendorItem const* crItem = vItems->m_items[vendor_slot];
18338 // check current item amount if it limited
18339 if (crItem->maxcount != 0)
18341 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
18343 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
18344 return false;
18348 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
18350 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
18351 return false;
18354 if (crItem->ExtendedCost)
18356 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18357 if (!iece)
18359 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
18360 return false;
18363 // honor points price
18364 if (GetHonorPoints() < (iece->reqhonorpoints * count))
18366 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
18367 return false;
18370 // arena points price
18371 if (GetArenaPoints() < (iece->reqarenapoints * count))
18373 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
18374 return false;
18377 // item base price
18378 for (uint8 i = 0; i < 5; ++i)
18380 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
18382 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
18383 return false;
18387 // check for personal arena rating requirement
18388 if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
18390 // probably not the proper equip err
18391 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
18392 return false;
18396 uint32 price = pProto->BuyPrice * count;
18398 // reputation discount
18399 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
18401 if (GetMoney() < price)
18403 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
18404 return false;
18407 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
18409 ItemPosCountVec dest;
18410 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
18411 if (msg != EQUIP_ERR_OK)
18413 SendEquipError( msg, NULL, NULL, item );
18414 return false;
18417 ModifyMoney( -(int32)price );
18418 if (crItem->ExtendedCost) // case for new honor system
18420 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18421 if (iece->reqhonorpoints)
18422 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
18423 if (iece->reqarenapoints)
18424 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
18425 for (uint8 i = 0; i < 5; ++i)
18427 if (iece->reqitem[i])
18428 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
18432 if (Item *it = StoreNewItem( dest, item, true ))
18434 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18436 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18437 data << uint64(pCreature->GetGUID());
18438 data << uint32(vendor_slot+1); // numbered from 1 at client
18439 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18440 data << uint32(count);
18441 GetSession()->SendPacket(&data);
18443 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18446 else if (IsEquipmentPos(bag, slot))
18448 if (pProto->BuyCount * count != 1)
18450 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
18451 return false;
18454 uint16 dest;
18455 uint8 msg = CanEquipNewItem( slot, dest, item, false );
18456 if (msg != EQUIP_ERR_OK)
18458 SendEquipError( msg, NULL, NULL, item );
18459 return false;
18462 ModifyMoney( -(int32)price );
18463 if (crItem->ExtendedCost) // case for new honor system
18465 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18466 if (iece->reqhonorpoints)
18467 ModifyHonorPoints( - int32(iece->reqhonorpoints));
18468 if (iece->reqarenapoints)
18469 ModifyArenaPoints( - int32(iece->reqarenapoints));
18470 for (uint8 i = 0; i < 5; ++i)
18472 if(iece->reqitem[i])
18473 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
18477 if (Item *it = EquipNewItem( dest, item, true ))
18479 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18481 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18482 data << uint64(pCreature->GetGUID());
18483 data << uint32(vendor_slot + 1); // numbered from 1 at client
18484 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18485 data << uint32(count);
18486 GetSession()->SendPacket(&data);
18488 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18490 AutoUnequipOffhandIfNeed();
18493 else
18495 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
18496 return false;
18499 return crItem->maxcount != 0;
18502 uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
18504 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18505 // the personal rating of the arena team must match the required limit as well
18506 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18507 uint32 max_personal_rating = 0;
18508 for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
18510 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18512 uint32 p_rating = GetArenaPersonalRating(i);
18513 uint32 t_rating = at->GetRating();
18514 p_rating = p_rating < t_rating ? p_rating : t_rating;
18515 if(max_personal_rating < p_rating)
18516 max_personal_rating = p_rating;
18519 return max_personal_rating;
18522 void Player::UpdateHomebindTime(uint32 time)
18524 // GMs never get homebind timer online
18525 if (m_InstanceValid || isGameMaster())
18527 if(m_HomebindTimer) // instance valid, but timer not reset
18529 // hide reminder
18530 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18531 data << uint32(0);
18532 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18533 GetSession()->SendPacket(&data);
18535 // instance is valid, reset homebind timer
18536 m_HomebindTimer = 0;
18538 else if (m_HomebindTimer > 0)
18540 if (time >= m_HomebindTimer)
18542 // teleport to nearest graveyard
18543 RepopAtGraveyard();
18545 else
18546 m_HomebindTimer -= time;
18548 else
18550 // instance is invalid, start homebind timer
18551 m_HomebindTimer = 60000;
18552 // send message to player
18553 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18554 data << uint32(m_HomebindTimer);
18555 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18556 GetSession()->SendPacket(&data);
18557 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18561 void Player::UpdatePvP(bool state, bool ovrride)
18563 if(!state || ovrride)
18565 SetPvP(state);
18566 pvpInfo.endTimer = 0;
18568 else
18570 if(pvpInfo.endTimer != 0)
18571 pvpInfo.endTimer = time(NULL);
18572 else
18573 SetPvP(state);
18577 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18579 // init cooldown values
18580 uint32 cat = 0;
18581 int32 rec = -1;
18582 int32 catrec = -1;
18584 // some special item spells without correct cooldown in SpellInfo
18585 // cooldown information stored in item prototype
18586 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18588 if(itemId)
18590 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18592 for(int idx = 0; idx < 5; ++idx)
18594 if(proto->Spells[idx].SpellId == spellInfo->Id)
18596 cat = proto->Spells[idx].SpellCategory;
18597 rec = proto->Spells[idx].SpellCooldown;
18598 catrec = proto->Spells[idx].SpellCategoryCooldown;
18599 break;
18605 // if no cooldown found above then base at DBC data
18606 if(rec < 0 && catrec < 0)
18608 cat = spellInfo->Category;
18609 rec = spellInfo->RecoveryTime;
18610 catrec = spellInfo->CategoryRecoveryTime;
18613 time_t curTime = time(NULL);
18615 time_t catrecTime;
18616 time_t recTime;
18618 // overwrite time for selected category
18619 if(infinityCooldown)
18621 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18622 // but not allow ignore until reset or re-login
18623 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18624 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18626 else
18628 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18629 // prevent 0 cooldowns set by another way
18630 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18631 rec = GetAttackTime(RANGED_ATTACK);
18633 // Now we have cooldown data (if found any), time to apply mods
18634 if(rec > 0)
18635 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18637 if(catrec > 0)
18638 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18640 // replace negative cooldowns by 0
18641 if (rec < 0) rec = 0;
18642 if (catrec < 0) catrec = 0;
18644 // no cooldown after applying spell mods
18645 if( rec == 0 && catrec == 0)
18646 return;
18648 catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0;
18649 recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime;
18652 // self spell cooldown
18653 if(recTime > 0)
18654 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18656 // category spells
18657 if (cat && catrec > 0)
18659 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18660 if(i_scstore != sSpellCategoryStore.end())
18662 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18664 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18665 continue;
18667 AddSpellCooldown(*i_scset, itemId, catrecTime);
18673 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18675 SpellCooldown sc;
18676 sc.end = end_time;
18677 sc.itemid = itemid;
18678 m_spellCooldowns[spellid] = sc;
18681 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18683 // start cooldowns at server side, if any
18684 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18686 // Send activate cooldown timer (possible 0) at client side
18687 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18688 data << uint32(spellInfo->Id);
18689 data << uint64(GetGUID());
18690 SendDirectMessage(&data);
18693 void Player::UpdatePotionCooldown(Spell* spell)
18695 // no potion used i combat or still in combat
18696 if(!m_lastPotionId || isInCombat())
18697 return;
18699 // Call not from spell cast, send cooldown event for item spells if no in combat
18700 if(!spell)
18702 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18703 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18704 for(int idx = 0; idx < 5; ++idx)
18705 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18706 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18707 SendCooldownEvent(spellInfo,m_lastPotionId);
18709 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18710 else
18711 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18713 m_lastPotionId = 0;
18716 //slot to be excluded while counting
18717 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18719 if(!enchantmentcondition)
18720 return true;
18722 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18724 if(!Condition)
18725 return true;
18727 uint8 curcount[4] = {0, 0, 0, 0};
18729 //counting current equipped gem colors
18730 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18732 if(i == slot)
18733 continue;
18734 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18735 if(pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color)
18737 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18739 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18740 if(!enchant_id)
18741 continue;
18743 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18744 if(!enchantEntry)
18745 continue;
18747 uint32 gemid = enchantEntry->GemID;
18748 if(!gemid)
18749 continue;
18751 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18752 if(!gemProto)
18753 continue;
18755 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18756 if(!gemProperty)
18757 continue;
18759 uint8 GemColor = gemProperty->color;
18761 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18763 if(tmpcolormask & GemColor)
18764 ++curcount[b];
18770 bool activate = true;
18772 for(int i = 0; i < 5; ++i)
18774 if(!Condition->Color[i])
18775 continue;
18777 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18779 // if have <CompareColor> use them as count, else use <value> from Condition
18780 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18782 switch(Condition->Comparator[i])
18784 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18785 activate &= (_cur_gem < _cmp_gem) ? true : false;
18786 break;
18787 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18788 activate &= (_cur_gem > _cmp_gem) ? true : false;
18789 break;
18790 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18791 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18792 break;
18796 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");
18798 return activate;
18801 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18803 //cycle all equipped items
18804 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18806 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18807 if(slot == exceptslot)
18808 continue;
18810 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18812 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18813 continue;
18815 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18817 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18818 if(!enchant_id)
18819 continue;
18821 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18822 if(!enchantEntry)
18823 continue;
18825 uint32 condition = enchantEntry->EnchantmentCondition;
18826 if(condition)
18828 //was enchant active with/without item?
18829 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18830 //should it now be?
18831 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18833 // ignore item gem conditions
18834 //if state changed, (dis)apply enchant
18835 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18842 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18843 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18845 //cycle all equipped items
18846 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18848 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18849 if(slot == exceptslot)
18850 continue;
18852 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18854 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18855 continue;
18857 //cycle all (gem)enchants
18858 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18860 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18861 if(!enchant_id) //if no enchant go to next enchant(slot)
18862 continue;
18864 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18865 if(!enchantEntry)
18866 continue;
18868 //only metagems to be (de)activated, so only enchants with condition
18869 uint32 condition = enchantEntry->EnchantmentCondition;
18870 if(condition)
18871 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18876 void Player::SetBattleGroundEntryPoint()
18878 // Taxi path store
18879 if (!m_taxi.empty())
18881 m_bgData.mountSpell = 0;
18882 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18883 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18885 // On taxi we don't need check for dungeon
18886 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18887 return;
18889 else
18891 m_bgData.ClearTaxiPath();
18893 // Mount spell id storing
18894 if (IsMounted())
18896 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18897 if (!auras.empty())
18898 m_bgData.mountSpell = (*auras.begin())->GetId();
18900 else
18901 m_bgData.mountSpell = 0;
18903 // If map is dungeon find linked graveyard
18904 if(GetMap()->IsDungeon())
18906 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18908 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18909 return;
18911 else
18912 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18914 // If new entry point is not BG or arena set it
18915 else if (!GetMap()->IsBattleGroundOrArena())
18917 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18918 return;
18922 // In error cases use homebind position
18923 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18926 void Player::LeaveBattleground(bool teleportToEntryPoint)
18928 if(BattleGround *bg = GetBattleGround())
18930 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18932 // call after remove to be sure that player resurrected for correct cast
18933 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) )
18935 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18937 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18938 if(IsBeingTeleportedFar())
18940 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18941 return;
18944 CastSpell(this, 26013, true); // Deserter
18950 bool Player::CanJoinToBattleground() const
18952 // check Deserter debuff
18953 if(GetDummyAura(26013))
18954 return false;
18956 return true;
18959 bool Player::CanReportAfkDueToLimit()
18961 // a player can complain about 15 people per 5 minutes
18962 if(m_bgData.bgAfkReportedCount++ >= 15)
18963 return false;
18965 return true;
18968 ///This player has been blamed to be inactive in a battleground
18969 void Player::ReportedAfkBy(Player* reporter)
18971 BattleGround *bg = GetBattleGround();
18972 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18973 return;
18975 // check if player has 'Idle' or 'Inactive' debuff
18976 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit())
18978 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18979 // 3 players have to complain to apply debuff
18980 if(m_bgData.bgAfkReporter.size() >= 3)
18982 // cast 'Idle' spell
18983 CastSpell(this, 43680, true);
18984 m_bgData.bgAfkReporter.clear();
18989 WorldObject const* Player::GetViewPoint() const
18991 if(uint64 far_sight = GetFarSight())
18993 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18994 return viewPoint ? viewPoint : this; // always expected not NULL
18996 else
18997 return this;
19000 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
19002 // gamemaster in GM mode see all, including ghosts
19003 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
19004 return true;
19006 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
19007 if (InBattleGround())
19009 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
19010 return false;
19011 return true;
19014 // Live player see live player or dead player with not realized corpse
19015 if(pl->isAlive() || pl->m_deathTimer > 0)
19017 return isAlive() || m_deathTimer > 0;
19020 // Ghost see other friendly ghosts, that's for sure
19021 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
19022 return true;
19024 // Dead player see live players near own corpse
19025 if(isAlive())
19027 Corpse *corpse = pl->GetCorpse();
19028 if(corpse)
19030 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
19031 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
19032 return true;
19036 // and not see any other
19037 return false;
19040 bool Player::IsVisibleGloballyFor( Player* u ) const
19042 if(!u)
19043 return false;
19045 // Always can see self
19046 if (u==this)
19047 return true;
19049 // Visible units, always are visible for all players
19050 if (GetVisibility() == VISIBILITY_ON)
19051 return true;
19053 // GMs are visible for higher gms (or players are visible for gms)
19054 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
19055 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
19057 // non faction visibility non-breakable for non-GMs
19058 if (GetVisibility() == VISIBILITY_OFF)
19059 return false;
19061 // non-gm stealth/invisibility not hide from global player lists
19062 return true;
19065 template<class T>
19066 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
19070 template<>
19071 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
19073 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
19074 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
19077 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
19079 if(HaveAtClient(target))
19081 if(!target->isVisibleForInState(this, viewPoint, true))
19083 if (target->GetTypeId()==TYPEID_UNIT)
19084 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
19086 ObjectGuid t_guid = target->GetGUID();
19088 target->DestroyForPlayer(this);
19089 m_clientGUIDs.erase(t_guid);
19091 #ifdef MANGOS_DEBUG
19092 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
19093 sLog.outDebug("%s out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
19094 #endif
19097 else
19099 if(target->isVisibleForInState(this, viewPoint, false))
19101 target->SendCreateUpdateToPlayer(this);
19102 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
19103 m_clientGUIDs.insert(target->GetGUID());
19105 #ifdef MANGOS_DEBUG
19106 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
19107 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
19108 #endif
19110 // target aura duration for caster show only if target exist at caster client
19111 // send data at target visibility change (adding to client)
19112 if(target!=this && target->isType(TYPEMASK_UNIT))
19113 SendAurasForTarget((Unit*)target);
19115 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
19116 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
19121 template<class T>
19122 inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, T* target)
19124 s64.insert(target->GetGUID());
19127 template<>
19128 inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, GameObject* target)
19130 if(!target->IsTransport())
19131 s64.insert(target->GetGUID());
19134 template<class T>
19135 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& /*data_updates*/, std::set<WorldObject*>& visibleNow)
19137 if(HaveAtClient(target))
19139 if(!target->isVisibleForInState(this,viewPoint,true))
19141 BeforeVisibilityDestroy<T>(target,this);
19143 ObjectGuid t_guid = target->GetGUID();
19145 target->BuildOutOfRangeUpdateBlock(&data);
19146 m_clientGUIDs.erase(t_guid);
19148 #ifdef MANGOS_DEBUG
19149 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
19150 sLog.outDebug("%s is out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
19151 #endif
19154 else
19156 if(target->isVisibleForInState(this,viewPoint,false))
19158 visibleNow.insert(target);
19159 target->BuildCreateUpdateBlockForPlayer(&data, this);
19160 UpdateVisibilityOf_helper(m_clientGUIDs,target);
19162 #ifdef MANGOS_DEBUG
19163 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
19164 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));
19165 #endif
19170 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
19171 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
19172 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
19173 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
19174 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
19176 void Player::InitPrimaryProfessions()
19178 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL));
19181 void Player::SendComboPoints()
19183 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
19184 if (combotarget)
19186 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
19187 data << combotarget->GetPackGUID();
19188 data << uint8(m_comboPoints);
19189 GetSession()->SendPacket(&data);
19193 void Player::AddComboPoints(Unit* target, int8 count)
19195 if(!count)
19196 return;
19198 // without combo points lost (duration checked in aura)
19199 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
19201 if(target->GetGUID() == m_comboTarget)
19203 m_comboPoints += count;
19205 else
19207 if(m_comboTarget)
19208 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
19209 target2->RemoveComboPointHolder(GetGUIDLow());
19211 m_comboTarget = target->GetGUID();
19212 m_comboPoints = count;
19214 target->AddComboPointHolder(GetGUIDLow());
19217 if (m_comboPoints > 5) m_comboPoints = 5;
19218 if (m_comboPoints < 0) m_comboPoints = 0;
19220 SendComboPoints();
19223 void Player::ClearComboPoints()
19225 if(!m_comboTarget)
19226 return;
19228 // without combopoints lost (duration checked in aura)
19229 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
19231 m_comboPoints = 0;
19233 SendComboPoints();
19235 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
19236 target->RemoveComboPointHolder(GetGUIDLow());
19238 m_comboTarget = 0;
19241 void Player::SetGroup(Group *group, int8 subgroup)
19243 if(group == NULL)
19244 m_group.unlink();
19245 else
19247 // never use SetGroup without a subgroup unless you specify NULL for group
19248 ASSERT(subgroup >= 0);
19249 m_group.link(group, this);
19250 m_group.setSubGroup((uint8)subgroup);
19254 void Player::SendInitialPacketsBeforeAddToMap()
19256 GetSocial()->SendSocialList();
19258 // Homebind
19259 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
19260 data << m_homebindX << m_homebindY << m_homebindZ;
19261 data << (uint32) m_homebindMapId;
19262 data << (uint32) m_homebindAreaId;
19263 GetSession()->SendPacket(&data);
19265 // SMSG_SET_PROFICIENCY
19266 // SMSG_SET_PCT_SPELL_MODIFIER
19267 // SMSG_SET_FLAT_SPELL_MODIFIER
19269 SendTalentsInfoData(false);
19271 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
19272 data << uint32(0);
19273 data << uint32(0);
19274 GetSession()->SendPacket(&data);
19276 SendInitialSpells();
19278 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
19279 data << uint32(0); // count, for(count) uint32;
19280 GetSession()->SendPacket(&data);
19282 SendInitialActionButtons();
19283 m_reputationMgr.SendInitialReputations();
19285 if(!isAlive())
19286 SendCorpseReclaimDelay(true);
19288 SendInitWorldStates(GetZoneId(), GetAreaId());
19290 SendEquipmentSetList();
19292 m_achievementMgr.SendAllAchievementData();
19294 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
19295 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
19296 data << (float)0.01666667f; // game speed
19297 data << uint32(0); // added in 3.1.2
19298 GetSession()->SendPacket( &data );
19300 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
19301 // SMSG_PET_GUIDS
19302 // SMSG_POWER_UPDATE
19304 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
19305 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
19306 m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
19308 m_mover = this;
19311 void Player::SendInitialPacketsAfterAddToMap()
19313 // update zone
19314 uint32 newzone, newarea;
19315 GetZoneAndAreaId(newzone,newarea);
19316 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
19318 ResetTimeSync();
19319 SendTimeSync();
19321 CastSpell(this, 836, true); // LOGINEFFECT
19323 // set some aura effects that send packet to player client after add player to map
19324 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19325 // same auras state lost at far teleport, send it one more time in this case also
19326 static const AuraType auratypes[] =
19328 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
19329 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
19330 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
19332 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
19334 Unit::AuraList const& auraList = GetAurasByType(*itr);
19335 if(!auraList.empty())
19336 auraList.front()->ApplyModifier(true,true);
19339 if(HasAuraType(SPELL_AURA_MOD_STUN))
19340 SetMovement(MOVE_ROOT);
19342 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19343 if(HasAuraType(SPELL_AURA_MOD_ROOT))
19345 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
19346 data2 << GetPackGUID();
19347 data2 << (uint32)2;
19348 SendMessageToSet(&data2,true);
19351 SendAurasForTarget(this);
19352 SendEnchantmentDurations(); // must be after add to map
19353 SendItemDurations(); // must be after add to map
19356 void Player::SendUpdateToOutOfRangeGroupMembers()
19358 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
19359 return;
19360 if(Group* group = GetGroup())
19361 group->UpdatePlayerOutOfRange(this);
19363 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
19364 m_auraUpdateMask = 0;
19365 if(Pet *pet = GetPet())
19366 pet->ResetAuraUpdateMask();
19369 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
19371 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
19372 data << uint32(mapid);
19373 data << uint8(reason); // transfer abort reason
19374 switch(reason)
19376 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
19377 case TRANSFER_ABORT_DIFFICULTY:
19378 case TRANSFER_ABORT_UNIQUE_MESSAGE:
19379 data << uint8(arg);
19380 break;
19382 GetSession()->SendPacket(&data);
19385 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
19387 // type of warning, based on the time remaining until reset
19388 uint32 type;
19389 if(time > 3600)
19390 type = RAID_INSTANCE_WELCOME;
19391 else if(time > 900 && time <= 3600)
19392 type = RAID_INSTANCE_WARNING_HOURS;
19393 else if(time > 300 && time <= 900)
19394 type = RAID_INSTANCE_WARNING_MIN;
19395 else
19396 type = RAID_INSTANCE_WARNING_MIN_SOON;
19398 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
19399 data << uint32(type);
19400 data << uint32(mapid);
19401 data << uint32(difficulty); // difficulty
19402 data << uint32(time);
19403 if(type == RAID_INSTANCE_WELCOME)
19405 data << uint8(0); // is your (1)
19406 data << uint8(0); // is extended (1), ignored if prev field is 0
19408 GetSession()->SendPacket(&data);
19411 void Player::ApplyEquipCooldown( Item * pItem )
19413 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
19415 _Spell const& spellData = pItem->GetProto()->Spells[i];
19417 // no spell
19418 if( !spellData.SpellId )
19419 continue;
19421 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19422 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
19423 continue;
19425 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
19427 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
19428 data << pItem->GetGUID();
19429 data << uint32(spellData.SpellId);
19430 GetSession()->SendPacket(&data);
19434 void Player::resetSpells()
19436 // not need after this call
19437 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
19438 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
19440 // make full copy of map (spells removed and marked as deleted at another spell remove
19441 // and we can't use original map for safe iterative with visit each spell at loop end
19442 PlayerSpellMap smap = GetSpellMap();
19444 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
19445 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19447 learnDefaultSpells();
19448 learnQuestRewardedSpells();
19451 void Player::learnDefaultSpells()
19453 // learn default race/class spells
19454 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
19455 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
19457 uint32 tspell = *itr;
19458 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
19459 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19460 addSpell(tspell, true, true, true, false);
19461 else // but send in normal spell in game learn case
19462 learnSpell(tspell, true);
19466 void Player::learnQuestRewardedSpells(Quest const* quest)
19468 uint32 spell_id = quest->GetRewSpellCast();
19470 // skip quests without rewarded spell
19471 if( !spell_id )
19472 return;
19474 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
19475 if(!spellInfo)
19476 return;
19478 // check learned spells state
19479 bool found = false;
19480 for(int i=0; i < MAX_EFFECT_INDEX; ++i)
19482 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
19484 found = true;
19485 break;
19489 // skip quests with not teaching spell or already known spell
19490 if(!found)
19491 return;
19493 // prevent learn non first rank unknown profession and second specialization for same profession)
19494 uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0];
19495 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
19497 // not have first rank learned (unlearned prof?)
19498 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
19499 if( !HasSpell(first_spell) )
19500 return;
19502 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
19503 if(!learnedInfo)
19504 return;
19506 // specialization
19507 if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0)
19509 // search other specialization for same prof
19510 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19512 if(itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19513 continue;
19515 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19516 if(!itrInfo)
19517 return;
19519 // compare only specializations
19520 if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0)
19521 continue;
19523 // compare same chain spells
19524 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19525 continue;
19527 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19528 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19529 return;
19534 CastSpell( this, spell_id, true);
19537 void Player::learnQuestRewardedSpells()
19539 // learn spells received from quest completing
19540 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19542 // skip no rewarded quests
19543 if(!itr->second.m_rewarded)
19544 continue;
19546 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19547 if( !quest )
19548 continue;
19550 learnQuestRewardedSpells(quest);
19554 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19556 uint32 raceMask = getRaceMask();
19557 uint32 classMask = getClassMask();
19558 for (uint32 j = 0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19560 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19561 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19562 continue;
19563 // Check race if set
19564 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19565 continue;
19566 // Check class if set
19567 if (pAbility->classmask && !(pAbility->classmask & classMask))
19568 continue;
19570 if (sSpellStore.LookupEntry(pAbility->spellId))
19572 // need unlearn spell
19573 if (skill_value < pAbility->req_skill_value)
19574 removeSpell(pAbility->spellId);
19575 // need learn
19576 else if (!IsInWorld())
19577 addSpell(pAbility->spellId, true, true, true, false);
19578 else
19579 learnSpell(pAbility->spellId, true);
19584 void Player::SendAurasForTarget(Unit *target)
19586 if(target->GetVisibleAuras()->empty()) // speedup things
19587 return;
19589 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19590 data << target->GetPackGUID();
19592 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19593 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19595 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
19597 if(Aura *aura = target->GetAura(itr->second, SpellEffectIndex(j)))
19599 data << uint8(aura->GetAuraSlot());
19600 data << uint32(aura->GetId());
19602 if(aura->GetId())
19604 uint8 auraFlags = aura->GetAuraFlags();
19605 // flags
19606 data << uint8(auraFlags);
19607 // level
19608 data << uint8(aura->GetAuraLevel());
19609 // charges
19610 if (aura->GetAuraCharges())
19611 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19612 else
19613 data << uint8(aura->GetStackAmount());
19615 if(!(auraFlags & AFLAG_NOT_CASTER)) // packed GUID of caster
19617 data.appendPackGUID(aura->GetCasterGUID());
19620 if(auraFlags & AFLAG_DURATION) // include aura duration
19622 data << uint32(aura->GetAuraMaxDuration());
19623 data << uint32(aura->GetAuraDuration());
19626 break;
19631 GetSession()->SendPacket(&data);
19634 void Player::SetDailyQuestStatus( uint32 quest_id )
19636 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19638 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19640 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19641 m_DailyQuestChanged = true;
19642 break;
19647 void Player::SetWeeklyQuestStatus( uint32 quest_id )
19649 m_weeklyquests.insert(quest_id);
19650 m_WeeklyQuestChanged = true;
19653 void Player::ResetDailyQuestStatus()
19655 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19656 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19658 // DB data deleted in caller
19659 m_DailyQuestChanged = false;
19662 void Player::ResetWeeklyQuestStatus()
19664 if (m_weeklyquests.empty())
19665 return;
19667 m_weeklyquests.clear();
19668 // DB data deleted in caller
19669 m_WeeklyQuestChanged = false;
19672 BattleGround* Player::GetBattleGround() const
19674 if(GetBattleGroundId()==0)
19675 return NULL;
19677 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19680 bool Player::InArena() const
19682 BattleGround *bg = GetBattleGround();
19683 if(!bg || !bg->isArena())
19684 return false;
19686 return true;
19689 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19691 // get a template bg instead of running one
19692 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19693 if(!bg)
19694 return false;
19696 // limit check leel to dbc compatible level range
19697 uint32 level = getLevel();
19698 if (level > DEFAULT_MAX_LEVEL)
19699 level = DEFAULT_MAX_LEVEL;
19701 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19702 return false;
19704 return true;
19707 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19709 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19710 if(!vendor_faction || !vendor_faction->faction)
19711 return 1.0f;
19713 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19714 if(rank <= REP_NEUTRAL)
19715 return 1.0f;
19717 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19720 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19722 uint32 racemask = getRaceMask();
19723 uint32 classmask = getClassMask();
19725 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19726 if (bounds.first==bounds.second)
19727 return true;
19729 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19731 // skip wrong race skills
19732 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19733 continue;
19735 // skip wrong class skills
19736 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19737 continue;
19739 return true;
19742 return false;
19745 bool Player::HasQuestForGO(int32 GOId) const
19747 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19749 uint32 questid = GetQuestSlotQuestId(i);
19750 if ( questid == 0 )
19751 continue;
19753 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19754 if(qs_itr == mQuestStatus.end())
19755 continue;
19757 QuestStatusData const& qs = qs_itr->second;
19759 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19761 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19762 if(!qinfo)
19763 continue;
19765 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19766 continue;
19768 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19770 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19771 continue;
19773 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19774 return true;
19778 return false;
19781 void Player::UpdateForQuestWorldObjects()
19783 if(m_clientGUIDs.empty())
19784 return;
19786 UpdateData udata;
19787 WorldPacket packet;
19788 for(ObjectGuidSet::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19790 if (itr->IsGameobject())
19792 if (GameObject *obj = GetMap()->GetGameObject(*itr))
19793 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19795 else if (itr->IsCreatureOrVehicle())
19797 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19798 if(!obj)
19799 continue;
19801 // check if this unit requires quest specific flags
19802 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19803 continue;
19805 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19806 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19808 if(_itr->second.questStart || _itr->second.questEnd)
19810 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19811 break;
19816 udata.BuildPacket(&packet);
19817 GetSession()->SendPacket(&packet);
19820 void Player::SummonIfPossible(bool agree)
19822 if(!agree)
19824 m_summon_expire = 0;
19825 return;
19828 // expire and auto declined
19829 if(m_summon_expire < time(NULL))
19830 return;
19832 // stop taxi flight at summon
19833 if(isInFlight())
19835 GetMotionMaster()->MovementExpired();
19836 m_taxi.ClearTaxiDestinations();
19839 // drop flag at summon
19840 // 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
19841 if(BattleGround *bg = GetBattleGround())
19842 bg->EventPlayerDroppedFlag(this);
19844 m_summon_expire = 0;
19846 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19848 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19851 void Player::RemoveItemDurations( Item *item )
19853 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19855 if(*itr==item)
19857 m_itemDuration.erase(itr);
19858 break;
19863 void Player::AddItemDurations( Item *item )
19865 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19867 m_itemDuration.push_back(item);
19868 item->SendTimeUpdate(this);
19872 void Player::AutoUnequipOffhandIfNeed()
19874 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19875 if(!offItem)
19876 return;
19878 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19879 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19880 return;
19882 ItemPosCountVec off_dest;
19883 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19884 if( off_msg == EQUIP_ERR_OK )
19886 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19887 StoreItem( off_dest, offItem, true );
19889 else
19891 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19892 CharacterDatabase.BeginTransaction();
19893 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19894 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19895 CharacterDatabase.CommitTransaction();
19897 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19898 MailDraft(subject, "There's were problems with equipping this item.").AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19902 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19904 if(spellInfo->EquippedItemClass < 0)
19905 return true;
19907 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19908 // for optimize check 2 used cases only
19909 switch(spellInfo->EquippedItemClass)
19911 case ITEM_CLASS_WEAPON:
19913 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19914 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19915 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19916 return true;
19917 break;
19919 case ITEM_CLASS_ARMOR:
19921 // tabard not have dependent spells
19922 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19923 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19924 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19925 return true;
19927 // shields can be equipped to offhand slot
19928 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19929 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19930 return true;
19932 // ranged slot can have some armor subclasses
19933 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19934 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19935 return true;
19937 break;
19939 default:
19940 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19941 break;
19944 return false;
19947 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19949 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19950 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19951 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19952 return true;
19954 // Check no reagent use mask
19955 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19956 uint32 noReagentMask_2 = GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2);
19957 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19958 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19959 return true;
19961 return false;
19964 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19966 AuraMap& auras = GetAuras();
19967 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19969 Aura* aura = itr->second;
19971 // skip passive (passive item dependent spells work in another way) and not self applied auras
19972 SpellEntry const* spellInfo = aura->GetSpellProto();
19973 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19975 ++itr;
19976 continue;
19979 // skip if not item dependent or have alternative item
19980 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19982 ++itr;
19983 continue;
19986 // no alt item, remove aura, restart check
19987 RemoveAurasDueToSpell(aura->GetId());
19988 itr = auras.begin();
19991 // currently casted spells can be dependent from item
19992 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19993 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19994 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19995 InterruptSpell(CurrentSpellTypes(i));
19998 uint32 Player::GetResurrectionSpellId()
20000 // search priceless resurrection possibilities
20001 uint32 prio = 0;
20002 uint32 spell_id = 0;
20003 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
20004 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
20006 // Soulstone Resurrection // prio: 3 (max, non death persistent)
20007 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
20009 switch((*itr)->GetId())
20011 case 20707: spell_id = 3026; break; // rank 1
20012 case 20762: spell_id = 20758; break; // rank 2
20013 case 20763: spell_id = 20759; break; // rank 3
20014 case 20764: spell_id = 20760; break; // rank 4
20015 case 20765: spell_id = 20761; break; // rank 5
20016 case 27239: spell_id = 27240; break; // rank 6
20017 case 47883: spell_id = 47882; break; // rank 7
20018 default:
20019 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
20020 continue;
20023 prio = 3;
20025 // Twisting Nether // prio: 2 (max)
20026 else if((*itr)->GetId()==23701 && roll_chance_i(10))
20028 prio = 2;
20029 spell_id = 23700;
20033 // Reincarnation (passive spell) // prio: 1
20034 // Glyph of Renewed Life remove reagent requiremnnt
20035 if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0)))
20036 spell_id = 21169;
20038 return spell_id;
20041 // Used in triggers for check "Only to targets that grant experience or honor" req
20042 bool Player::isHonorOrXPTarget(Unit* pVictim) const
20044 uint32 v_level = pVictim->getLevel();
20045 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
20047 // Victim level less gray level
20048 if(v_level<=k_grey)
20049 return false;
20051 if(pVictim->GetTypeId() == TYPEID_UNIT)
20053 if (((Creature*)pVictim)->isTotem() ||
20054 ((Creature*)pVictim)->isPet() ||
20055 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
20056 return false;
20058 return true;
20061 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
20063 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
20065 // prepare data for near group iteration (PvP and !PvP cases)
20066 uint32 xp = 0;
20067 bool honored_kill = false;
20069 if(Group *pGroup = GetGroup())
20071 uint32 count = 0;
20072 uint32 sum_level = 0;
20073 Player* member_with_max_level = NULL;
20074 Player* not_gray_member_with_max_level = NULL;
20076 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
20078 if(member_with_max_level)
20080 /// not get Xp in PvP or no not gray players in group
20081 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
20083 /// skip in check PvP case (for speed, not used)
20084 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
20085 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
20086 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
20088 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
20090 Player* pGroupGuy = itr->getSource();
20091 if(!pGroupGuy)
20092 continue;
20094 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
20095 continue; // member (alive or dead) or his corpse at req. distance
20097 // honor can be in PvP and !PvP (racial leader) cases (for alive)
20098 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
20099 honored_kill = true;
20101 // xp and reputation only in !PvP case
20102 if(!PvP)
20104 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
20106 // if is in dungeon then all receive full reputation at kill
20107 // rewarded any alive/dead/near_corpse group member
20108 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
20110 // XP updated only for alive group member
20111 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
20112 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
20114 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
20116 pGroupGuy->GiveXP(itr_xp, pVictim);
20117 if(Pet* pet = pGroupGuy->GetPet())
20118 pet->GivePetXP(itr_xp/2);
20121 // quest objectives updated only for alive group member or dead but with not released body
20122 if(pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
20124 // normal creature (not pet/etc) can be only in !PvP case
20125 if(pVictim->GetTypeId()==TYPEID_UNIT)
20126 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetObjectGuid());
20132 else // if (!pGroup)
20134 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
20136 // honor can be in PvP and !PvP (racial leader) cases
20137 if(RewardHonor(pVictim,1))
20138 honored_kill = true;
20140 // xp and reputation only in !PvP case
20141 if(!PvP)
20143 RewardReputation(pVictim,1);
20144 GiveXP(xp, pVictim);
20146 if(Pet* pet = GetPet())
20147 pet->GivePetXP(xp);
20149 // normal creature (not pet/etc) can be only in !PvP case
20150 if(pVictim->GetTypeId()==TYPEID_UNIT)
20151 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetObjectGuid());
20154 return xp || honored_kill;
20157 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
20159 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
20161 // prepare data for near group iteration
20162 if(Group *pGroup = GetGroup())
20164 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
20166 Player* pGroupGuy = itr->getSource();
20167 if(!pGroupGuy)
20168 continue;
20170 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
20171 continue; // member (alive or dead) or his corpse at req. distance
20173 // quest objectives updated only for alive group member or dead but with not released body
20174 if(pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
20175 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
20178 else // if (!pGroup)
20179 KilledMonsterCredit(creature_id, creature_guid);
20182 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
20184 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)))
20185 return true;
20187 if (isAlive())
20188 return false;
20190 Corpse* corpse = GetCorpse();
20191 if (!corpse)
20192 return false;
20194 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE));
20197 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
20199 Item* item = GetWeaponForAttack(attType,true,true);
20201 // unarmed only with base attack
20202 if(attType != BASE_ATTACK && !item)
20203 return 0;
20205 // weapon skill or (unarmed for base attack)
20206 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
20207 return GetBaseSkillValue(skill);
20210 void Player::ResurectUsingRequestData()
20212 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
20213 if(IS_PLAYER_GUID(m_resurrectGUID))
20214 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
20216 //we cannot resurrect player when we triggered far teleport
20217 //player will be resurrected upon teleportation
20218 if(IsBeingTeleportedFar())
20220 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
20221 return;
20224 ResurrectPlayer(0.0f,false);
20226 if(GetMaxHealth() > m_resurrectHealth)
20227 SetHealth( m_resurrectHealth );
20228 else
20229 SetHealth( GetMaxHealth() );
20231 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
20232 SetPower(POWER_MANA, m_resurrectMana );
20233 else
20234 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
20236 SetPower(POWER_RAGE, 0 );
20238 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
20240 SpawnCorpseBones();
20243 void Player::SetClientControl(Unit* target, uint8 allowMove)
20245 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
20246 data << target->GetPackGUID();
20247 data << uint8(allowMove);
20248 GetSession()->SendPacket(&data);
20251 void Player::UpdateZoneDependentAuras( uint32 newZone )
20253 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
20254 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
20255 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
20256 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
20257 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
20258 CastSpell(this,itr->second->spellId,true);
20261 void Player::UpdateAreaDependentAuras( uint32 newArea )
20263 // remove auras from spells with area limitations
20264 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
20266 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
20267 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
20268 RemoveAura(iter);
20269 else
20270 ++iter;
20273 // some auras applied at subzone enter
20274 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
20275 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
20276 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
20277 if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
20278 CastSpell(this,itr->second->spellId,true);
20281 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
20283 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20284 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20286 return copseReclaimDelay[0];
20289 time_t now = time(NULL);
20290 // 0..2 full period
20291 uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0;
20292 return copseReclaimDelay[count];
20295 void Player::UpdateCorpseReclaimDelay()
20297 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
20299 if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
20300 (!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
20301 return;
20303 time_t now = time(NULL);
20304 if(now < m_deathExpireTime)
20306 // full and partly periods 1..3
20307 uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1);
20308 if(count < MAX_DEATH_COUNT)
20309 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
20310 else
20311 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
20313 else
20314 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
20317 void Player::SendCorpseReclaimDelay(bool load)
20319 Corpse* corpse = GetCorpse();
20320 if(!corpse)
20321 return;
20323 uint32 delay;
20324 if(load)
20326 if(corpse->GetGhostTime() > m_deathExpireTime)
20327 return;
20329 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
20331 uint32 count;
20332 if( pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
20333 !pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
20335 count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
20336 if(count>=MAX_DEATH_COUNT)
20337 count = MAX_DEATH_COUNT-1;
20339 else
20340 count=0;
20342 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
20344 time_t now = time(NULL);
20345 if(now >= expected_time)
20346 return;
20348 delay = uint32(expected_time-now);
20350 else
20351 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
20353 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20354 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
20355 data << uint32(delay*IN_MILLISECONDS);
20356 GetSession()->SendPacket( &data );
20359 Player* Player::GetNextRandomRaidMember(float radius)
20361 Group *pGroup = GetGroup();
20362 if(!pGroup)
20363 return NULL;
20365 std::vector<Player*> nearMembers;
20366 nearMembers.reserve(pGroup->GetMembersCount());
20368 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
20370 Player* Target = itr->getSource();
20372 // IsHostileTo check duel and controlled by enemy
20373 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
20374 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
20375 nearMembers.push_back(Target);
20378 if (nearMembers.empty())
20379 return NULL;
20381 uint32 randTarget = urand(0,nearMembers.size()-1);
20382 return nearMembers[randTarget];
20385 PartyResult Player::CanUninviteFromGroup() const
20387 const Group* grp = GetGroup();
20388 if(!grp)
20389 return ERR_NOT_IN_GROUP;
20391 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
20392 return ERR_NOT_LEADER;
20394 if(InBattleGround())
20395 return ERR_INVITE_RESTRICTED;
20397 return ERR_PARTY_RESULT_OK;
20400 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
20402 //we must move references from m_group to m_originalGroup
20403 SetOriginalGroup(GetGroup(), GetSubGroup());
20405 m_group.unlink();
20406 m_group.link(group, this);
20407 m_group.setSubGroup((uint8)subgroup);
20410 void Player::RemoveFromBattleGroundRaid()
20412 //remove existing reference
20413 m_group.unlink();
20414 if( Group* group = GetOriginalGroup() )
20416 m_group.link(group, this);
20417 m_group.setSubGroup(GetOriginalSubGroup());
20419 SetOriginalGroup(NULL);
20422 void Player::SetOriginalGroup(Group *group, int8 subgroup)
20424 if( group == NULL )
20425 m_originalGroup.unlink();
20426 else
20428 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20429 ASSERT(subgroup >= 0);
20430 m_originalGroup.link(group, this);
20431 m_originalGroup.setSubGroup((uint8)subgroup);
20435 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
20437 LiquidData liquid_status;
20438 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
20439 if (!res)
20441 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWATER_INDARKWATER);
20442 // Small hack for enable breath in WMO
20443 if (IsInWater())
20444 m_MirrorTimerFlags|=UNDERWATER_INWATER;
20445 return;
20448 // All liquids type - check under water position
20449 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
20451 if ( res & LIQUID_MAP_UNDER_WATER)
20452 m_MirrorTimerFlags |= UNDERWATER_INWATER;
20453 else
20454 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
20457 // Allow travel in dark water on taxi or transport
20458 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
20459 m_MirrorTimerFlags |= UNDERWATER_INDARKWATER;
20460 else
20461 m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER;
20463 // in lava check, anywhere in lava level
20464 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
20466 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20467 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
20468 else
20469 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
20471 // in slime check, anywhere in slime level
20472 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
20474 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20475 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
20476 else
20477 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
20481 void Player::SetCanParry( bool value )
20483 if(m_canParry==value)
20484 return;
20486 m_canParry = value;
20487 UpdateParryPercentage();
20490 void Player::SetCanBlock( bool value )
20492 if(m_canBlock==value)
20493 return;
20495 m_canBlock = value;
20496 UpdateBlockPercentage();
20499 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
20501 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
20502 if(itr->pos == pos)
20503 return true;
20505 return false;
20508 bool Player::CanUseBattleGroundObject()
20510 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20511 // maybe gameobject code should handle that ForceReaction usage
20512 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20513 return ( //InBattleGround() && // in battleground - not need, check in other cases
20514 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20515 //player cannot use object when he is invulnerable (immune)
20516 !isTotalImmune() && // not totally immune
20517 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20518 !HasStealthAura() && // not stealthed
20519 !HasInvisibilityAura() && // not invisible
20520 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup
20521 isAlive() // live player
20525 bool Player::CanCaptureTowerPoint()
20527 return ( !HasStealthAura() && // not stealthed
20528 !HasInvisibilityAura() && // not invisible
20529 isAlive() // live player
20533 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20535 uint32 level = getLevel();
20537 if(level > GT_MAX_LEVEL)
20538 level = GT_MAX_LEVEL; // max level in this dbc
20540 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20541 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20542 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20544 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20545 return 0;
20547 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20549 if(!bsc) // shouldn't happen
20550 return 0xFFFFFFFF;
20552 float cost = 0;
20554 if(hairstyle != newhairstyle)
20555 cost += bsc->cost; // full price
20557 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20558 cost += bsc->cost * 0.5f; // +1/2 of price
20560 if(facialhair != newfacialhair)
20561 cost += bsc->cost * 0.75f; // +3/4 of price
20563 return uint32(cost);
20566 void Player::InitGlyphsForLevel()
20568 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20569 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20570 if(gs->Order)
20571 SetGlyphSlot(gs->Order - 1, gs->Id);
20573 uint32 level = getLevel();
20574 uint32 value = 0;
20576 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20577 if(level >= 15)
20578 value |= (0x01 | 0x02);
20579 if(level >= 30)
20580 value |= 0x08;
20581 if(level >= 50)
20582 value |= 0x04;
20583 if(level >= 70)
20584 value |= 0x10;
20585 if(level >= 80)
20586 value |= 0x20;
20588 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20591 void Player::ApplyGlyph(uint8 slot, bool apply)
20593 if (uint32 glyph = GetGlyph(slot))
20595 if(GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
20597 if(apply)
20599 CastSpell(this, gp->SpellId, true);
20600 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
20602 else
20604 RemoveAurasDueToSpell(gp->SpellId);
20605 SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0);
20611 void Player::ApplyGlyphs(bool apply)
20613 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20614 ApplyGlyph(i,apply);
20617 void Player::EnterVehicle(Vehicle *vehicle)
20619 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20620 if(!ve)
20621 return;
20623 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20624 if(!veSeat)
20625 return;
20627 vehicle->SetCharmerGUID(GetGUID());
20628 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20629 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20630 vehicle->setFaction(getFaction());
20632 SetCharm(vehicle); // charm
20633 SetFarSightGUID(vehicle->GetGUID()); // set view
20635 SetClientControl(vehicle, 1); // redirect controls to vehicle
20636 SetMover(vehicle);
20638 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20639 GetSession()->SendPacket(&data);
20641 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20642 data << GetPackGUID();
20643 data << uint32(0); // counter?
20644 data << uint32(MOVEFLAG_ONTRANSPORT); // transport
20645 data << uint16(0); // special flags
20646 data << uint32(getMSTime()); // time
20647 data << vehicle->GetPositionX(); // x
20648 data << vehicle->GetPositionY(); // y
20649 data << vehicle->GetPositionZ(); // z
20650 data << vehicle->GetOrientation(); // o
20651 // transport part, TODO: load/calculate seat offsets
20652 data << uint64(vehicle->GetGUID()); // transport guid
20653 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20654 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20655 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20656 data << float(0); // transport orientation
20657 data << uint32(getMSTime()); // transport time
20658 data << uint8(0); // seat
20659 // end of transport part
20660 data << uint32(0); // fall time
20661 GetSession()->SendPacket(&data);
20663 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20664 data << uint64(vehicle->GetGUID());
20665 data << uint16(0);
20666 data << uint32(0);
20667 data << uint32(0x00000101);
20669 for(uint32 i = 0; i < 10; ++i)
20670 data << uint16(0) << uint8(0) << uint8(i+8);
20672 data << uint8(0);
20673 data << uint8(0);
20674 GetSession()->SendPacket(&data);
20677 void Player::ExitVehicle(Vehicle *vehicle)
20679 vehicle->SetCharmerGUID(0);
20680 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20681 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20682 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20684 SetCharm(NULL);
20685 SetFarSightGUID(0);
20687 SetClientControl(vehicle, 0);
20688 SetMover(NULL);
20690 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20691 data << GetPackGUID();
20692 data << uint32(0); // counter?
20693 data << uint32(MOVEFLAG_ROOT); // fly unk
20694 data << uint16(MOVEFLAG2_UNK4); // special flags
20695 data << uint32(getMSTime()); // time
20696 data << vehicle->GetPositionX(); // x
20697 data << vehicle->GetPositionY(); // y
20698 data << vehicle->GetPositionZ(); // z
20699 data << vehicle->GetOrientation(); // o
20700 data << uint32(0); // fall time
20701 GetSession()->SendPacket(&data);
20703 RemovePetActionBar();
20705 // maybe called at dummy aura remove?
20706 // CastSpell(this, 45472, true); // Parachute
20709 bool Player::isTotalImmune()
20711 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20713 uint32 immuneMask = 0;
20714 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20716 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20717 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20718 return true;
20720 return false;
20723 bool Player::HasTitle(uint32 bitIndex)
20725 if (bitIndex > MAX_TITLE_INDEX)
20726 return false;
20728 uint32 fieldIndexOffset = bitIndex / 32;
20729 uint32 flag = 1 << (bitIndex % 32);
20730 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20733 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20735 uint32 fieldIndexOffset = title->bit_index / 32;
20736 uint32 flag = 1 << (title->bit_index % 32);
20738 if(lost)
20740 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20741 return;
20743 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20745 else
20747 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20748 return;
20750 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20753 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20754 data << uint32(title->bit_index);
20755 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20756 GetSession()->SendPacket(&data);
20759 void Player::ConvertRune(uint8 index, RuneType newType)
20761 SetCurrentRune(index, newType);
20763 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20764 data << uint8(index);
20765 data << uint8(newType);
20766 GetSession()->SendPacket(&data);
20769 void Player::ResyncRunes(uint8 count)
20771 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20772 for(uint32 i = 0; i < count; ++i)
20774 data << uint8(GetCurrentRune(i)); // rune type
20775 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20777 GetSession()->SendPacket(&data);
20780 void Player::AddRunePower(uint8 index)
20782 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20783 data << uint32(1 << index); // mask (0x00-0x3F probably)
20784 GetSession()->SendPacket(&data);
20787 static RuneType runeSlotTypes[MAX_RUNES] = {
20788 /*0*/ RUNE_BLOOD,
20789 /*1*/ RUNE_BLOOD,
20790 /*2*/ RUNE_UNHOLY,
20791 /*3*/ RUNE_UNHOLY,
20792 /*4*/ RUNE_FROST,
20793 /*5*/ RUNE_FROST
20796 void Player::InitRunes()
20798 if(getClass() != CLASS_DEATH_KNIGHT)
20799 return;
20801 m_runes = new Runes;
20803 m_runes->runeState = 0;
20805 for(uint32 i = 0; i < MAX_RUNES; ++i)
20807 SetBaseRune(i, runeSlotTypes[i]); // init base types
20808 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20809 SetRuneCooldown(i, 0); // reset cooldowns
20810 m_runes->SetRuneState(i);
20813 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20814 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20818 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20820 for(uint32 i = 0; i < MAX_RUNES; ++i)
20821 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20822 return false;
20824 return true;
20827 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20829 Loot loot;
20830 loot.FillLoot (loot_id,store,this,true);
20832 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20833 for(uint32 i = 0; i < max_slot; ++i)
20835 LootItem* lootItem = loot.LootItemInSlot(i,this);
20837 ItemPosCountVec dest;
20838 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20839 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20840 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20841 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20842 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20843 if(msg != EQUIP_ERR_OK)
20845 SendEquipError( msg, NULL, NULL, lootItem->itemid );
20846 continue;
20849 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20850 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20854 uint32 Player::CalculateTalentsPoints() const
20856 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20858 if(getClass() != CLASS_DEATH_KNIGHT)
20859 return uint32(base_talent * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20861 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20862 talentPointsForLevel += m_questRewardTalentCount;
20864 if(talentPointsForLevel > base_talent)
20865 talentPointsForLevel = base_talent;
20867 return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
20870 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20872 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20873 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20874 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20877 struct DoPlayerLearnSpell
20879 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20880 void operator() (uint32 spell_id) { player.learnSpell(spell_id, false); }
20881 Player& player;
20884 void Player::learnSpellHighRank(uint32 spellid)
20886 learnSpell(spellid, false);
20888 DoPlayerLearnSpell worker(*this);
20889 sSpellMgr.doForHighRanks(spellid, worker);
20892 void Player::_LoadSkills(QueryResult *result)
20894 // 0 1 2
20895 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20897 uint32 count = 0;
20898 if (result)
20902 Field *fields = result->Fetch();
20904 uint16 skill = fields[0].GetUInt16();
20905 uint16 value = fields[1].GetUInt16();
20906 uint16 max = fields[2].GetUInt16();
20908 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20909 if(!pSkill)
20911 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20912 continue;
20915 // set fixed skill ranges
20916 switch(GetSkillRangeType(pSkill,false))
20918 case SKILL_RANGE_LANGUAGE: // 300..300
20919 value = max = 300;
20920 break;
20921 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20922 value = max = 1;
20923 break;
20924 default:
20925 break;
20928 if(value == 0)
20930 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20931 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20932 continue;
20935 // enable unlearn button for primary professions only
20936 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20937 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20938 else
20939 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20941 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20942 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20944 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20946 learnSkillRewardedSpells(skill, value);
20948 ++count;
20950 if(count >= PLAYER_MAX_SKILLS) // client limit
20952 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20953 break;
20955 } while (result->NextRow());
20956 delete result;
20959 for (; count < PLAYER_MAX_SKILLS; ++count)
20961 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20962 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20963 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20966 // special settings
20967 if(getClass()==CLASS_DEATH_KNIGHT)
20969 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL));
20970 if(base_level < 1)
20971 base_level = 1;
20972 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20973 if(base_skill < 1)
20974 base_skill = 1; // skill mast be known and then > 0 in any case
20976 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20977 SetSkill(SKILL_FIRST_AID, 0, base_skill, base_skill);
20978 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20979 SetSkill(SKILL_AXES, 0, base_skill, base_skill);
20980 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20981 SetSkill(SKILL_DEFENSE, 0, base_skill, base_skill);
20982 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20983 SetSkill(SKILL_POLEARMS, 0, base_skill, base_skill);
20984 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20985 SetSkill(SKILL_SWORDS, 0, base_skill, base_skill);
20986 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20987 SetSkill(SKILL_2H_AXES, 0, base_skill, base_skill);
20988 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20989 SetSkill(SKILL_2H_SWORDS, 0, base_skill, base_skill);
20990 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20991 SetSkill(SKILL_UNARMED, 0, base_skill, base_skill);
20995 uint32 Player::GetPhaseMaskForSpawn() const
20997 uint32 phase = PHASEMASK_NORMAL;
20998 if(!isGameMaster())
20999 phase = GetPhaseMask();
21000 else
21002 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
21003 if(!phases.empty())
21004 phase = phases.front()->GetMiscValue();
21007 // some aura phases include 1 normal map in addition to phase itself
21008 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
21009 return n_phase;
21011 return PHASEMASK_NORMAL;
21014 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
21016 ItemPrototype const* pProto = pItem->GetProto();
21018 // proto based limitations
21019 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
21020 return res;
21022 // check unique-equipped on gems
21023 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
21025 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
21026 if(!enchant_id)
21027 continue;
21028 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
21029 if(!enchantEntry)
21030 continue;
21032 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
21033 if(!pGem)
21034 continue;
21036 // include for check equip another gems with same limit category for not equipped item (and then not counted)
21037 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
21038 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
21040 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
21041 return res;
21044 return EQUIP_ERR_OK;
21047 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
21049 // check unique-equipped on item
21050 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
21052 // there is an equip limit on this item
21053 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
21054 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
21057 // check unique-equipped limit
21058 if (itemProto->ItemLimitCategory)
21060 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
21061 if(!limitEntry)
21062 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
21064 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
21066 if(limit_count > limitEntry->maxCount)
21067 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
21069 // there is an equip limit on this item
21070 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
21071 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
21074 return EQUIP_ERR_OK;
21077 void Player::HandleFall(MovementInfo const& movementInfo)
21079 // calculate total z distance of the fall
21080 float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
21081 sLog.outDebug("zDiff = %f", z_diff);
21083 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
21084 // 14.57 can be calculated by resolving damageperc formula below to 0
21085 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
21086 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
21087 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
21089 //Safe fall, fall height reduction
21090 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
21092 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
21094 if(damageperc >0 )
21096 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL));
21098 float height = movementInfo.GetPos()->z;
21099 UpdateGroundPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
21101 if (damage > 0)
21103 //Prevent fall damage from being more than the player maximum health
21104 if (damage > GetMaxHealth())
21105 damage = GetMaxHealth();
21107 // Gust of Wind
21108 if (GetDummyAura(43621))
21109 damage = GetMaxHealth()/2;
21111 uint32 original_health = GetHealth();
21112 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
21114 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
21115 if (isAlive() && final_damage < original_health)
21116 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
21119 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
21120 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
21125 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
21127 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
21130 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
21132 uint32 CurTalentPoints = GetFreeTalentPoints();
21134 if(CurTalentPoints == 0)
21135 return;
21137 if (talentRank >= MAX_TALENT_RANK)
21138 return;
21140 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
21142 if(!talentInfo)
21143 return;
21145 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
21147 if(!talentTabInfo)
21148 return;
21150 // prevent learn talent for different class (cheating)
21151 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
21152 return;
21154 // find current max talent rank
21155 uint32 curtalent_maxrank = 0;
21156 PlayerTalentMap::iterator itr = m_talents[m_activeSpec].find(talentId);
21157 if (itr != m_talents[m_activeSpec].end() && itr->second.state != PLAYERSPELL_REMOVED)
21158 curtalent_maxrank = itr->second.currentRank + 1;
21160 // we already have same or higher talent rank learned
21161 if(curtalent_maxrank >= (talentRank + 1))
21162 return;
21164 // check if we have enough talent points
21165 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
21166 return;
21168 // Check if it requires another talent
21169 if (talentInfo->DependsOn > 0)
21171 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
21173 bool hasEnoughRank = false;
21174 PlayerTalentMap::iterator dependsOnTalent = m_talents[m_activeSpec].find(depTalentInfo->TalentID);
21175 if (dependsOnTalent != m_talents[m_activeSpec].end() && dependsOnTalent->second.state != PLAYERSPELL_REMOVED)
21177 PlayerTalent depTalent = (*dependsOnTalent).second;
21178 if (depTalent.currentRank >= talentInfo->DependsOnRank)
21179 hasEnoughRank = true;
21182 if (!hasEnoughRank)
21183 return;
21187 // Find out how many points we have in this field
21188 uint32 spentPoints = 0;
21190 uint32 tTab = talentInfo->TalentTab;
21191 if (talentInfo->Row > 0)
21193 for (PlayerTalentMap::const_iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter)
21194 if (iter->second.state != PLAYERSPELL_REMOVED && iter->second.m_talentEntry->TalentTab == tTab)
21195 spentPoints += iter->second.currentRank + 1;
21198 // not have required min points spent in talent tree
21199 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
21200 return;
21202 // spell not set in talent.dbc
21203 uint32 spellid = talentInfo->RankID[talentRank];
21204 if( spellid == 0 )
21206 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
21207 return;
21210 // already known
21211 if(HasSpell(spellid))
21212 return;
21214 // learn! (other talent ranks will unlearned at learning)
21215 learnSpell(spellid, false);
21216 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
21219 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
21221 Pet *pet = GetPet();
21223 if(!pet)
21224 return;
21226 if(petGuid != pet->GetGUID())
21227 return;
21229 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
21231 if(CurTalentPoints == 0)
21232 return;
21234 if (talentRank >= MAX_PET_TALENT_RANK)
21235 return;
21237 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
21239 if(!talentInfo)
21240 return;
21242 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
21244 if(!talentTabInfo)
21245 return;
21247 CreatureInfo const *ci = pet->GetCreatureInfo();
21249 if(!ci)
21250 return;
21252 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21254 if(!pet_family)
21255 return;
21257 if(pet_family->petTalentType < 0) // not hunter pet
21258 return;
21260 // prevent learn talent for different family (cheating)
21261 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21262 return;
21264 // find current max talent rank
21265 int32 curtalent_maxrank = 0;
21266 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21268 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21270 curtalent_maxrank = k + 1;
21271 break;
21275 // we already have same or higher talent rank learned
21276 if(curtalent_maxrank >= int32(talentRank + 1))
21277 return;
21279 // check if we have enough talent points
21280 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
21281 return;
21283 // Check if it requires another talent
21284 if (talentInfo->DependsOn > 0)
21286 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
21288 bool hasEnoughRank = false;
21289 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
21291 if (depTalentInfo->RankID[i] != 0)
21292 if (pet->HasSpell(depTalentInfo->RankID[i]))
21293 hasEnoughRank = true;
21295 if (!hasEnoughRank)
21296 return;
21300 // Find out how many points we have in this field
21301 uint32 spentPoints = 0;
21303 uint32 tTab = talentInfo->TalentTab;
21304 if (talentInfo->Row > 0)
21306 unsigned int numRows = sTalentStore.GetNumRows();
21307 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
21309 // Someday, someone needs to revamp
21310 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
21311 if (tmpTalent) // the way talents are tracked
21313 if (tmpTalent->TalentTab == tTab)
21315 for (int j = 0; j < MAX_TALENT_RANK; ++j)
21317 if (tmpTalent->RankID[j] != 0)
21319 if (pet->HasSpell(tmpTalent->RankID[j]))
21321 spentPoints += j + 1;
21330 // not have required min points spent in talent tree
21331 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
21332 return;
21334 // spell not set in talent.dbc
21335 uint32 spellid = talentInfo->RankID[talentRank];
21336 if( spellid == 0 )
21338 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
21339 return;
21342 // already known
21343 if(pet->HasSpell(spellid))
21344 return;
21346 // learn! (other talent ranks will unlearned at learning)
21347 pet->learnSpell(spellid);
21348 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
21351 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
21353 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
21355 if(apply)
21356 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21357 else
21358 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
21362 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
21364 if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
21365 SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
21368 void Player::UnsummonPetTemporaryIfAny()
21370 Pet* pet = GetPet();
21371 if(!pet)
21372 return;
21374 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
21376 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
21377 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
21380 RemovePet(pet, PET_SAVE_AS_CURRENT);
21383 void Player::ResummonPetTemporaryUnSummonedIfAny()
21385 if(!m_temporaryUnsummonedPetNumber)
21386 return;
21388 // not resummon in not appropriate state
21389 if(IsPetNeedBeTemporaryUnsummoned())
21390 return;
21392 if(GetPetGUID())
21393 return;
21395 Pet* NewPet = new Pet;
21396 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
21397 delete NewPet;
21399 m_temporaryUnsummonedPetNumber = 0;
21402 bool Player::canSeeSpellClickOn(Creature const *c) const
21404 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
21405 return false;
21407 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
21408 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
21409 if(itr->second.IsFitToRequirements(this))
21410 return true;
21412 return false;
21415 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
21417 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
21418 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
21419 *data << uint8(m_activeSpec); // talent group index (0 or 1)
21421 if(m_specsCount)
21423 // loop through all specs (only 1 for now)
21424 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
21426 uint8 talentIdCount = 0;
21427 size_t pos = data->wpos();
21428 *data << uint8(talentIdCount); // [PH], talentIdCount
21430 // find class talent tabs (all players have 3 talent tabs)
21431 uint32 const* talentTabIds = GetTalentTabPages(getClass());
21433 for(uint32 i = 0; i < 3; ++i)
21435 uint32 talentTabId = talentTabIds[i];
21436 for(PlayerTalentMap::iterator iter = m_talents[specIdx].begin(); iter != m_talents[specIdx].end(); ++iter)
21438 PlayerTalent talent = (*iter).second;
21440 if (talent.state == PLAYERSPELL_REMOVED)
21441 continue;
21443 // skip another tab talents
21444 if(talent.m_talentEntry->TalentTab != talentTabId)
21445 continue;
21447 *data << uint32(talent.m_talentEntry->TalentID); // Talent.dbc
21448 *data << uint8(talent.currentRank); // talentMaxRank (0-4)
21450 ++talentIdCount;
21454 data->put<uint8>(pos, talentIdCount); // put real count
21456 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
21458 // GlyphProperties.dbc
21459 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
21460 *data << uint16(m_glyphs[specIdx][i].GetId());
21465 void Player::BuildPetTalentsInfoData(WorldPacket *data)
21467 uint32 unspentTalentPoints = 0;
21468 size_t pointsPos = data->wpos();
21469 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
21471 uint8 talentIdCount = 0;
21472 size_t countPos = data->wpos();
21473 *data << uint8(talentIdCount); // [PH], talentIdCount
21475 Pet *pet = GetPet();
21476 if(!pet)
21477 return;
21479 unspentTalentPoints = pet->GetFreeTalentPoints();
21481 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
21483 CreatureInfo const *ci = pet->GetCreatureInfo();
21484 if(!ci)
21485 return;
21487 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21488 if(!pet_family || pet_family->petTalentType < 0)
21489 return;
21491 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
21493 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
21494 if(!talentTabInfo)
21495 continue;
21497 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21498 continue;
21500 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21502 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21503 if(!talentInfo)
21504 continue;
21506 // skip another tab talents
21507 if(talentInfo->TalentTab != talentTabId)
21508 continue;
21510 // find max talent rank
21511 int32 curtalent_maxrank = -1;
21512 for(int32 k = 4; k > -1; --k)
21514 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21516 curtalent_maxrank = k;
21517 break;
21521 // not learned talent
21522 if(curtalent_maxrank < 0)
21523 continue;
21525 *data << uint32(talentInfo->TalentID); // Talent.dbc
21526 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21528 ++talentIdCount;
21531 data->put<uint8>(countPos, talentIdCount); // put real count
21533 break;
21537 void Player::SendTalentsInfoData(bool pet)
21539 WorldPacket data(SMSG_TALENTS_INFO, 50);
21540 data << uint8(pet ? 1 : 0);
21541 if(pet)
21542 BuildPetTalentsInfoData(&data);
21543 else
21544 BuildPlayerTalentsInfoData(&data);
21545 GetSession()->SendPacket(&data);
21548 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21550 uint32 slotUsedMask = 0;
21551 size_t slotUsedMaskPos = data->wpos();
21552 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21554 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21556 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21558 if(!item)
21559 continue;
21561 slotUsedMask |= (1 << i);
21563 *data << uint32(item->GetEntry()); // item entry
21565 uint16 enchantmentMask = 0;
21566 size_t enchantmentMaskPos = data->wpos();
21567 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21569 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21571 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21573 if(!enchId)
21574 continue;
21576 enchantmentMask |= (1 << j);
21578 *data << uint16(enchId); // enchantmentId?
21581 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21583 *data << uint16(0); // ?
21584 *data << uint8(0); // PGUID!
21585 *data << uint32(0); // seed?
21588 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21591 void Player::SendEquipmentSetList()
21593 uint32 count = 0;
21594 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21595 size_t count_pos = data.wpos();
21596 data << uint32(count); // count placeholder
21597 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21599 if(itr->second.state==EQUIPMENT_SET_DELETED)
21600 continue;
21601 data.appendPackGUID(itr->second.Guid);
21602 data << uint32(itr->first);
21603 data << itr->second.Name;
21604 data << itr->second.IconName;
21605 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21606 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21608 ++count; // client have limit but it checked at loading and set
21610 data.put<uint32>(count_pos, count);
21611 GetSession()->SendPacket(&data);
21614 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21616 if(eqset.Guid != 0)
21618 bool found = false;
21620 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21622 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21624 found = true;
21625 break;
21629 if(!found) // something wrong...
21631 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21632 return;
21636 EquipmentSet& eqslot = m_EquipmentSets[index];
21638 EquipmentSetUpdateState old_state = eqslot.state;
21640 eqslot = eqset;
21642 if(eqset.Guid == 0)
21644 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21646 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21647 data << uint32(index);
21648 data.appendPackGUID(eqslot.Guid);
21649 GetSession()->SendPacket(&data);
21652 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21655 void Player::_SaveEquipmentSets()
21657 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21659 uint32 index = itr->first;
21660 EquipmentSet& eqset = itr->second;
21661 switch(eqset.state)
21663 case EQUIPMENT_SET_UNCHANGED:
21664 ++itr;
21665 break; // nothing do
21666 case EQUIPMENT_SET_CHANGED:
21667 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
21668 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21669 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
21670 eqset.state = EQUIPMENT_SET_UNCHANGED;
21671 ++itr;
21672 break;
21673 case EQUIPMENT_SET_NEW:
21674 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
21675 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21676 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
21677 eqset.state = EQUIPMENT_SET_UNCHANGED;
21678 ++itr;
21679 break;
21680 case EQUIPMENT_SET_DELETED:
21681 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21682 m_EquipmentSets.erase(itr++);
21683 break;
21688 void Player::_SaveBGData()
21690 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21691 if (m_bgData.bgInstanceID)
21693 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21694 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21695 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21696 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21700 void Player::DeleteEquipmentSet(uint64 setGuid)
21702 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21704 if(itr->second.Guid == setGuid)
21706 if(itr->second.state == EQUIPMENT_SET_NEW)
21707 m_EquipmentSets.erase(itr);
21708 else
21709 itr->second.state = EQUIPMENT_SET_DELETED;
21710 break;
21715 void Player::ActivateSpec(uint8 specNum)
21717 if(GetActiveSpec() == specNum)
21718 return;
21720 if(specNum >= GetSpecsCount())
21721 return;
21723 UnsummonPetTemporaryIfAny();
21725 ApplyGlyphs(false);
21727 // copy of new talent spec (we will use it as model for converting current tlanet state to new)
21728 PlayerTalentMap tempSpec = m_talents[specNum];
21730 // copy old spec talents to new one, must be before spec switch to have previous spec num(as m_activeSpec)
21731 m_talents[specNum] = m_talents[m_activeSpec];
21733 SetActiveSpec(specNum);
21735 // remove all talent spells that don't exist in next spec but exist in old
21736 for (PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].begin(); specIter != m_talents[m_activeSpec].end();)
21738 PlayerTalent& talent = (*specIter).second;
21740 if (talent.state == PLAYERSPELL_REMOVED)
21742 ++specIter;
21743 continue;
21746 PlayerTalentMap::iterator iterTempSpec = tempSpec.find(specIter->first);
21748 // remove any talent rank if talent not listed in temp spec
21749 if (iterTempSpec == tempSpec.end() || iterTempSpec->second.state == PLAYERSPELL_REMOVED)
21751 TalentEntry const *talentInfo = talent.m_talentEntry;
21753 for(int r = 0; r < MAX_TALENT_RANK; ++r)
21754 if (talentInfo->RankID[r])
21755 removeSpell(talentInfo->RankID[r],!IsPassiveSpell(talentInfo->RankID[r]),false);
21757 specIter = m_talents[m_activeSpec].begin();
21759 else
21760 ++specIter;
21763 // now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then.
21764 for (PlayerTalentMap::const_iterator tempIter = tempSpec.begin(); tempIter != tempSpec.end(); ++tempIter)
21766 PlayerTalent const& talent = (*tempIter).second;
21768 // removed state talent already unlearned in prev. loop
21769 // but we need restore it if it deleted for finish removed-marked data in DB
21770 if (talent.state == PLAYERSPELL_REMOVED)
21772 m_talents[m_activeSpec][tempIter->first] = talent;
21773 continue;
21776 uint32 talentSpellId = talent.m_talentEntry->RankID[talent.currentRank];
21778 // learn talent spells if they not in new spec (old spec copy)
21779 // and if they have different rank
21780 PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].find(tempIter->first);
21781 if (specIter != m_talents[m_activeSpec].end() && specIter->second.state != PLAYERSPELL_REMOVED)
21783 if ((*specIter).second.currentRank != talent.currentRank)
21784 learnSpell(talentSpellId, false);
21786 else
21787 learnSpell(talentSpellId, false);
21789 // sync states - original state is changed in addSpell that learnSpell calls
21790 specIter = m_talents[m_activeSpec].find(tempIter->first);
21791 if (specIter != m_talents[m_activeSpec].end())
21792 (*specIter).second.state = talent.state;
21793 else
21795 sLog.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId);
21797 // attempt resync DB state (deleted lost spell from DB)
21798 if (talent.state != PLAYERSPELL_NEW)
21800 PlayerTalent& talentNew = m_talents[m_activeSpec][tempIter->first];
21801 talentNew = talent;
21802 talentNew.state = PLAYERSPELL_REMOVED;
21807 InitTalentForLevel();
21809 // recheck action buttons (not checked at loading/spec copy)
21810 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21811 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21812 if (itr->second.uState != ACTIONBUTTON_DELETED)
21813 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21814 if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false))
21815 removeActionButton(m_activeSpec,itr->first);
21817 ResummonPetTemporaryUnSummonedIfAny();
21819 ApplyGlyphs(true);
21821 SendInitialActionButtons();
21823 Powers pw = getPowerType();
21824 if(pw != POWER_MANA)
21825 SetPower(POWER_MANA, 0);
21827 SetPower(pw, 0);
21830 void Player::UpdateSpecCount(uint8 count)
21832 uint8 curCount = GetSpecsCount();
21833 if (curCount == count)
21834 return;
21836 // maybe current spec data must be copied to 0 spec?
21837 if (m_activeSpec >= count)
21838 ActivateSpec(0);
21840 // copy spec data from new specs
21841 if (count > curCount)
21843 // copy action buttons from active spec (more easy in this case iterate first by button)
21844 ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
21846 for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
21848 if (itr->second.uState != ACTIONBUTTON_DELETED)
21850 for(uint8 spec = curCount; spec < count; ++spec)
21851 addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
21855 // delete spec data for removed specs
21856 else if (count < curCount)
21858 // delete action buttons for removed spec
21859 for(uint8 spec = count; spec < curCount; ++spec)
21861 // delete action buttons for removed spec
21862 for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
21863 removeActionButton(spec,button);
21867 SetSpecsCount(count);
21869 SendTalentsInfoData(false);
21872 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21874 m_atLoginFlags &= ~f;
21876 if(in_db_also)
21877 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21880 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21882 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21883 data << uint32(spell_id);
21884 data << uint64(target->GetGUID());
21885 SendDirectMessage(&data);
21888 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21890 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21891 *data << GetPackGUID();
21892 *data << uint32(0); // this value increments every time
21893 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21894 *data << uint16(0); // 2.3.0
21895 *data << uint32(getMSTime()); // time
21896 *data << x;
21897 *data << y;
21898 *data << z;
21899 *data << ang;
21900 *data << uint32(0);
21903 bool Player::HasMovementFlag( MovementFlags f ) const
21905 return m_movementInfo.HasMovementFlag(f);
21908 void Player::SetFarSightGUID( uint64 guid )
21910 if(GetFarSight() == guid)
21911 return;
21913 SetUInt64Value(PLAYER_FARSIGHT, guid);
21915 // need triggering load grids around new view point
21916 UpdateVisibilityForPlayer();
21919 void Player::UpdateVisibilityForPlayer()
21921 WorldObject const* viewPoint = GetViewPoint();
21922 Map* m = GetMap();
21924 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21925 Cell cell(p);
21927 m->UpdatePlayerVisibility(this, cell, p);
21929 if (this != viewPoint)
21931 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21932 Cell cellView(pView);
21934 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21936 else
21937 m->UpdateObjectsVisibilityFor(this, cell, p);
21940 void Player::ResetTimeSync()
21942 m_timeSyncCounter = 0;
21943 m_timeSyncTimer = 0;
21944 m_timeSyncClient = 0;
21945 m_timeSyncServer = getMSTime();
21948 void Player::SendTimeSync()
21950 WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
21951 data << uint32(m_timeSyncCounter++);
21952 GetSession()->SendPacket(&data);
21954 // Schedule next sync in 10 sec
21955 m_timeSyncTimer = 10000;
21956 m_timeSyncServer = getMSTime();
21959 void Player::SendDuelCountdown(uint32 counter)
21961 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21962 data << uint32(counter); // seconds
21963 GetSession()->SendPacket(&data);
21966 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
21968 switch(spellInfo->Effect[index])
21970 case SPELL_EFFECT_ATTACK_ME:
21971 return true;
21972 default:
21973 break;
21975 switch(spellInfo->EffectApplyAuraName[index])
21977 case SPELL_AURA_MOD_TAUNT:
21978 return true;
21979 default:
21980 break;
21982 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21985 void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id)
21987 m_homebindMapId = loc.mapid;
21988 m_homebindAreaId = area_id;
21989 m_homebindX = loc.coord_x;
21990 m_homebindY = loc.coord_y;
21991 m_homebindZ = loc.coord_z;
21993 // update sql homebind
21994 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21995 m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());
21998 Object* Player::GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask)
22000 switch(guid.GetHigh())
22002 case HIGHGUID_ITEM:
22003 if (typemask & TYPEMASK_ITEM)
22004 return GetItemByGuid(guid);
22005 break;
22006 case HIGHGUID_PLAYER:
22007 if (GetObjectGuid()==guid)
22008 return this;
22009 if ((typemask & TYPEMASK_PLAYER) && IsInWorld())
22010 return ObjectAccessor::FindPlayer(guid);
22011 break;
22012 case HIGHGUID_GAMEOBJECT:
22013 if ((typemask & TYPEMASK_GAMEOBJECT) && IsInWorld())
22014 return GetMap()->GetGameObject(guid);
22015 break;
22016 case HIGHGUID_UNIT:
22017 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
22018 return GetMap()->GetCreature(guid);
22019 break;
22020 case HIGHGUID_PET:
22021 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
22022 return GetMap()->GetPet(guid);
22023 break;
22024 case HIGHGUID_VEHICLE:
22025 if ((typemask & TYPEMASK_UNIT) && IsInWorld())
22026 return GetMap()->GetVehicle(guid);
22027 break;
22028 case HIGHGUID_DYNAMICOBJECT:
22029 if ((typemask & TYPEMASK_DYNAMICOBJECT) && IsInWorld())
22030 return GetMap()->GetDynamicObject(guid);
22031 break;
22032 case HIGHGUID_TRANSPORT:
22033 case HIGHGUID_CORPSE:
22034 case HIGHGUID_MO_TRANSPORT:
22035 break;
22038 return NULL;
22041 void Player::SetRestType( RestType n_r_type, uint32 areaTriggerId /*= 0*/)
22043 rest_type = n_r_type;
22045 if (rest_type == REST_TYPE_NO)
22047 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
22049 // Set player to FFA PVP when not in rested environment.
22050 if(sWorld.IsFFAPvPRealm())
22051 SetFFAPvP(true);
22053 else
22055 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
22057 inn_trigger_id = areaTriggerId;
22058 time_inn_enter = time(NULL);
22060 if(sWorld.IsFFAPvPRealm())
22061 SetFFAPvP(false);