[7297] Fixed profession spells sorting in trainer spell list at client.
[getmangos.git] / src / game / Player.cpp
blob4da09e2375b85b8d4aa583f6979cfba74bfa35f4
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.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 "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
223 return false;
225 return true;
228 std::string PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations.empty())
231 return "";
233 std::ostringstream ss;
235 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
236 ss << m_TaxiDestinations[i] << " ";
238 return ss.str();
241 uint32 PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations.size() < 2)
244 return 0;
246 uint32 path;
247 uint32 cost;
249 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
251 return path;
254 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
256 ss << "'";
257 for(int i = 0; i < TaxiMaskSize; ++i)
258 ss << taxi.m_taximask[i] << " ";
259 ss << "'";
260 return ss;
263 //== Player ====================================================
265 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask Player::updateVisualBits;
269 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
271 m_transport = 0;
273 m_speakTime = 0;
274 m_speakCount = 0;
276 m_objectType |= TYPEMASK_PLAYER;
277 m_objectTypeId = TYPEID_PLAYER;
279 m_valuesCount = PLAYER_END;
281 m_session = session;
283 m_divider = 0;
285 m_ExtraFlags = 0;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER)
291 SetAcceptWhispers(true);
293 m_curSelection = 0;
294 m_lootGuid = 0;
296 m_comboTarget = 0;
297 m_comboPoints = 0;
299 m_usedTalentCount = 0;
300 m_questRewardTalentCount = 0;
302 m_regenTimer = 0;
303 m_weaponChangeTimer = 0;
305 m_zoneUpdateId = 0;
306 m_zoneUpdateTimer = 0;
308 m_areaUpdateId = 0;
310 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount = 0;
320 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
322 m_social = NULL;
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL);
326 m_groupUpdateMask = 0;
327 m_auraUpdateMask = 0;
329 duel = NULL;
331 m_GuildIdInvited = 0;
332 m_ArenaTeamIdInvited = 0;
334 m_atLoginFlags = AT_LOGIN_NONE;
336 m_dontMove = false;
338 pTrader = 0;
339 ClearTrade();
341 m_cinematic = 0;
343 PlayerTalkClass = new PlayerMenu( GetSession() );
344 m_currentBuybackSlot = BUYBACK_SLOT_START;
346 for ( int aX = 0 ; aX < 8 ; aX++ )
347 m_Tutorials[ aX ] = 0x00;
348 m_TutorialsChanged = false;
350 m_DailyQuestChanged = false;
351 m_lastDailyQuestTime = 0;
353 m_regenTimer = 0;
354 m_weaponChangeTimer = 0;
355 m_breathTimer = 0;
356 m_isunderwater = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1000;
368 m_bgBattleGroundID = 0;
369 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
371 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
372 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
374 m_bgTeam = 0;
376 m_logintime = time(NULL);
377 m_Last_tick = m_logintime;
378 m_WeaponProficiency = 0;
379 m_ArmorProficiency = 0;
380 m_canParry = false;
381 m_canBlock = false;
382 m_canDualWield = false;
383 m_canTitanGrip = false;
384 m_ammoDPS = 0.0f;
386 m_temporaryUnsummonedPetNumber = 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
390 m_oldpetspell = 0;
392 ////////////////////Rest System/////////////////////
393 time_inn_enter=0;
394 inn_pos_mapid=0;
395 inn_pos_x=0;
396 inn_pos_y=0;
397 inn_pos_z=0;
398 m_rest_bonus=0;
399 rest_type=REST_TYPE_NO;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded = false;
403 m_mailsUpdated = false;
404 unReadMails = 0;
405 m_nextMailDelivereTime = 0;
407 m_resetTalentsCost = 0;
408 m_resetTalentsTime = 0;
409 m_itemUpdateQueueBlocked = false;
411 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
412 m_forced_speed_changes[i] = 0;
414 m_stableSlots = 0;
416 /////////////////// Instance System /////////////////////
418 m_HomebindTimer = 0;
419 m_InstanceValid = true;
420 m_dungeonDifficulty = DIFFICULTY_NORMAL;
422 for (int i = 0; i < BASEMOD_END; i++)
424 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
425 m_auraBaseMod[i][PCT_MOD] = 1.0f;
428 for (int i = 0; i < MAX_COMBAT_RATING; i++)
429 m_baseRatingValue[i] = 0;
431 m_baseSpellDamage = 0;
432 m_baseSpellHealing = 0;
433 m_baseFeralAP = 0;
434 m_baseManaRegen = 0;
436 // Honor System
437 m_lastHonorUpdateTime = time(NULL);
439 // Player summoning
440 m_summon_expire = 0;
441 m_summon_mapid = 0;
442 m_summon_x = 0.0f;
443 m_summon_y = 0.0f;
444 m_summon_z = 0.0f;
446 //Default movement to run mode
447 m_unit_movement_flags = 0;
449 m_mover = NULL;
451 m_miniPet = 0;
452 m_bgAfkReportedTimer = 0;
453 m_contestedPvPTimer = 0;
455 m_declinedname = NULL;
456 m_runes = NULL;
459 Player::~Player ()
461 CleanupsBeforeDelete();
463 // it must be unloaded already in PlayerLogout and accessed only for loggined player
464 //m_social = NULL;
466 // Note: buy back item already deleted from DB when player was saved
467 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
469 if(m_items[i])
470 delete m_items[i];
472 CleanupChannels();
474 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
475 delete itr->second;
477 //all mailed items should be deleted, also all mail should be deallocated
478 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
479 delete *itr;
481 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
482 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
484 delete PlayerTalkClass;
486 if (m_transport)
488 m_transport->RemovePassenger(this);
491 for(size_t x = 0; x < ItemSetEff.size(); x++)
492 if(ItemSetEff[x])
493 delete ItemSetEff[x];
495 // clean up player-instance binds, may unload some instance saves
496 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
497 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
498 itr->second.save->RemovePlayer(this);
500 delete m_declinedname;
501 delete m_runes;
504 void Player::CleanupsBeforeDelete()
506 if(m_uint32Values) // only for fully created Object
508 TradeCancel(false);
509 DuelComplete(DUEL_INTERUPTED);
511 Unit::CleanupsBeforeDelete();
514 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 )
516 //FIXME: outfitId not used in player creating
518 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
520 m_name = name;
522 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
523 if(!info)
525 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
526 return false;
529 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
530 m_items[i] = NULL;
532 m_race = race;
533 m_class = class_;
535 SetMapId(info->mapId);
536 Relocate(info->positionX,info->positionY,info->positionZ);
538 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
539 if(!cEntry)
541 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
542 return false;
545 uint8 powertype = cEntry->powerType;
547 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
548 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
550 switch(gender)
552 case GENDER_FEMALE:
553 SetDisplayId(info->displayId_f );
554 SetNativeDisplayId(info->displayId_f );
555 break;
556 case GENDER_MALE:
557 SetDisplayId(info->displayId_m );
558 SetNativeDisplayId(info->displayId_m );
559 break;
560 default:
561 sLog.outError("Invalid gender %u for player",gender);
562 return false;
563 break;
566 setFactionForRace(m_race);
568 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
570 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
571 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
572 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
573 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
574 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
575 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
577 // -1 is default value
578 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
580 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
581 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
582 SetByteValue(PLAYER_BYTES_3, 0, gender);
584 SetUInt32Value( PLAYER_GUILDID, 0 );
585 SetUInt32Value( PLAYER_GUILDRANK, 0 );
586 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
588 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
590 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
591 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
592 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
593 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
594 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
596 // set starting level
597 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
598 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
599 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
601 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
603 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
604 if(gm_level > start_level)
605 start_level = gm_level;
608 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
610 InitRunes();
612 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
613 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
614 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
616 // Played time
617 m_Last_tick = time(NULL);
618 m_Played_time[0] = 0;
619 m_Played_time[1] = 0;
621 // base stats and related field values
622 InitStatsForLevel();
623 InitTaxiNodesForLevel();
624 InitGlyphsForLevel();
625 InitTalentForLevel();
626 InitPrimaryProffesions(); // to max set before any spell added
628 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
629 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
630 SetHealth(GetMaxHealth());
631 if (getPowerType()==POWER_MANA)
633 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
634 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
637 if(getPowerType() == POWER_RUNIC_POWER)
639 SetPower(POWER_RUNE, 8);
640 SetMaxPower(POWER_RUNE, 8);
641 SetPower(POWER_RUNIC_POWER, 0);
642 SetMaxPower(POWER_RUNIC_POWER, 1000);
645 // original spells
646 learnDefaultSpells();
648 // original action bar
649 std::list<uint16>::const_iterator action_itr[4];
650 for(int i=0; i<4; i++)
651 action_itr[i] = info->action[i].begin();
653 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
655 uint16 taction[4];
656 for(int i=0; i<4 ;i++)
657 taction[i] = (*action_itr[i]);
659 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
661 for(int i=0; i<4 ;i++)
662 ++action_itr[i];
665 // original items
666 CharStartOutfitEntry const* oEntry = NULL;
667 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
669 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
671 if(entry->RaceClassGender == RaceClassGender)
673 oEntry = entry;
674 break;
679 if(oEntry)
681 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
683 if(oEntry->ItemId[j] <= 0)
684 continue;
686 uint32 item_id = oEntry->ItemId[j];
689 // Hack for not existed item id in dbc 3.0.3
690 if(item_id==40582)
691 continue;
693 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
694 if(!iProto)
696 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
697 continue;
700 // max stack by default (mostly 1), 1 for infinity stackable
701 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
703 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
705 switch(iProto->Spells[0].SpellCategory)
707 case 11: // food
708 if(iProto->Stackable > 4)
709 count = 4;
710 break;
711 case 59: // drink
712 if(iProto->Stackable > 2)
713 count = 2;
714 break;
718 StoreNewItemInBestSlots(item_id, count);
722 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
723 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
725 // bags and main-hand weapon must equipped at this moment
726 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
727 // or ammo not equipped in special bag
728 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
730 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
732 uint16 eDest;
733 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
734 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
735 if( msg == EQUIP_ERR_OK )
737 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
738 EquipItem( eDest, pItem, true);
740 // move other items to more appropriate slots (ammo not equipped in special bag)
741 else
743 ItemPosCountVec sDest;
744 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 pItem = StoreItem( sDest, pItem, true);
751 // if this is ammo then use it
752 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
753 if( msg == EQUIP_ERR_OK )
754 SetAmmo( pItem->GetProto()->ItemId );
758 // all item positions resolved
760 return true;
763 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
765 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
767 // attempt equip by one
768 while(titem_amount > 0)
770 uint16 eDest;
771 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
772 if( msg != EQUIP_ERR_OK )
773 break;
775 EquipNewItem( eDest, titem_id, true);
776 AutoUnequipOffhandIfNeed();
777 --titem_amount;
780 if(titem_amount == 0)
781 return true; // equipped
783 // attempt store
784 ItemPosCountVec sDest;
785 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
786 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
787 if( msg == EQUIP_ERR_OK )
789 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
790 return true; // stored
793 // item can't be added
794 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
795 return false;
798 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
800 uint32 BreathRegen = (uint32)-1;
802 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
803 data << (uint32)Type;
804 data << MaxValue;
805 data << MaxValue;
806 data << BreathRegen;
807 data << (uint8)0;
808 data << (uint32)0; // spell id
809 GetSession()->SendPacket(&data);
812 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
814 if(Type==BREATH_TIMER)
815 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
817 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
818 data << (uint32)Type;
819 data << CurrentValue;
820 data << MaxValue;
821 data << Regen;
822 data << (uint8)0;
823 data << (uint32)0; // spell id
824 GetSession()->SendPacket( &data );
827 void Player::StopMirrorTimer(MirrorTimerType Type)
829 if(Type==BREATH_TIMER)
830 m_breathTimer = 0;
832 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
833 data << (uint32)Type;
834 GetSession()->SendPacket( &data );
837 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
839 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
840 data << (uint64)guid;
841 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
842 data << (uint32)damage;
843 data << (uint32)0;
844 data << (uint32)0;
845 SendMessageToSet(&data, true);
847 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
849 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
851 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
852 DurabilityLossAll(0.10f,false);
853 // durability lost message
854 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
855 GetSession()->SendPacket(&data);
859 void Player::HandleDrowning()
861 if(!(m_isunderwater&~UNDERWATER_INLAVA))
862 return;
864 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
865 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
867 StopMirrorTimer(BREATH_TIMER);
868 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
869 m_isunderwater &= UNDERWATER_INLAVA;
870 return;
873 uint32 UnderWaterTime = 3*MINUTE*1000; // default duration
875 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
876 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
877 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
879 if ((m_isunderwater & UNDERWATER_INWATER) && !(m_isunderwater & UNDERWATER_INLAVA) && isAlive())
881 //single trigger timer
882 if (!(m_isunderwater & UNDERWATER_WATER_TRIGGER))
884 m_isunderwater|= UNDERWATER_WATER_TRIGGER;
885 m_breathTimer = UnderWaterTime + 1000;
887 //single trigger "show Breathbar"
888 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & UNDERWATER_WATER_BREATHB))
890 m_isunderwater|= UNDERWATER_WATER_BREATHB;
891 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
893 //continuous trigger drowning "Damage"
894 if ((m_breathTimer == 0) && (m_isunderwater & UNDERWATER_INWATER))
896 //TODO: Check this formula
897 uint64 guid = GetGUID();
898 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
900 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
901 m_breathTimer = 2000;
904 //single trigger retract bar
905 else if (!(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater & UNDERWATER_WATER_TRIGGER) && (m_breathTimer > 0) && isAlive())
907 uint32 BreathRegen = 10;
908 // m_breathTimer will be reduced in ModifyMirrorTimer
909 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
910 m_isunderwater = UNDERWATER_WATER_BREATHB_RETRACTING;
912 //remove bar
913 else if ((m_breathTimer < 50) && !(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater == UNDERWATER_WATER_BREATHB_RETRACTING))
915 StopMirrorTimer(BREATH_TIMER);
916 m_isunderwater = UNDERWATER_NONE;
920 void Player::HandleLava()
922 if ((m_isunderwater & UNDERWATER_INLAVA) && isAlive())
925 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
926 // Single trigger Set BreathTimer
927 if (!(m_isunderwater & UNDERWATER_INLAVA))
929 m_isunderwater|= UNDERWATER_WATER_BREATHB;
930 m_breathTimer = 1000;
933 // Reset BreathTimer and still in the lava
934 if (!m_breathTimer)
936 uint64 guid = GetGUID();
937 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
939 // if not gamemaster then deal damage
940 if ( !isGameMaster() )
941 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
943 m_breathTimer = 1000;
946 else if (!isAlive()) // Disable breath timer and reset underwater flags
948 m_breathTimer = 0;
949 m_isunderwater = UNDERWATER_NONE;
953 ///The player sobers by 256 every 10 seconds
954 void Player::HandleSobering()
956 m_drunkTimer = 0;
958 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
959 SetDrunkValue(drunk);
962 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
964 if(value >= 23000)
965 return DRUNKEN_SMASHED;
966 if(value >= 12800)
967 return DRUNKEN_DRUNK;
968 if(value & 0xFFFE)
969 return DRUNKEN_TIPSY;
970 return DRUNKEN_SOBER;
973 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
975 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
977 m_drunk = newDrunkenValue;
978 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
980 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
982 // special drunk invisibility detection
983 if(newDrunkenState >= DRUNKEN_DRUNK)
984 m_detectInvisibilityMask |= (1<<6);
985 else
986 m_detectInvisibilityMask &= ~(1<<6);
988 if(newDrunkenState == oldDrunkenState)
989 return;
991 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
992 data << uint64(GetGUID());
993 data << uint32(newDrunkenState);
994 data << uint32(itemId);
996 SendMessageToSet(&data, true);
999 void Player::Update( uint32 p_time )
1001 if(!IsInWorld())
1002 return;
1004 // undelivered mail
1005 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1007 SendNewMail();
1008 ++unReadMails;
1010 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1011 m_nextMailDelivereTime = 0;
1014 Unit::Update( p_time );
1016 // update player only attacks
1017 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1019 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1022 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1024 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1027 time_t now = time (NULL);
1029 UpdatePvPFlag(now);
1031 UpdateContestedPvP(p_time);
1033 UpdateDuelFlag(now);
1035 CheckDuelDistance(now);
1037 UpdateAfkReport(now);
1039 CheckExploreSystem();
1041 // Update items that have just a limited lifetime
1042 if (now>m_Last_tick)
1043 UpdateItemDuration(uint32(now- m_Last_tick));
1045 if (!m_timedquests.empty())
1047 std::set<uint32>::iterator iter = m_timedquests.begin();
1048 while (iter != m_timedquests.end())
1050 QuestStatusData& q_status = mQuestStatus[*iter];
1051 if( q_status.m_timer <= p_time )
1053 uint32 quest_id = *iter;
1054 ++iter; // current iter will be removed in FailTimedQuest
1055 FailTimedQuest( quest_id );
1057 else
1059 q_status.m_timer -= p_time;
1060 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1061 ++iter;
1066 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1068 Unit *pVictim = getVictim();
1069 if( !IsNonMeleeSpellCasted(false) && pVictim)
1071 // default combat reach 10
1072 // TODO add weapon,skill check
1074 float pldistance = ATTACK_DISTANCE;
1076 if (isAttackReady(BASE_ATTACK))
1078 if(!IsWithinDistInMap(pVictim, pldistance))
1080 setAttackTimer(BASE_ATTACK,100);
1081 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1083 SendAttackSwingNotInRange();
1084 m_swingErrorMsg = 1;
1087 //120 degrees of radiant range
1088 else if( !HasInArc( 2*M_PI/3, pVictim ))
1090 setAttackTimer(BASE_ATTACK,100);
1091 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1093 SendAttackSwingBadFacingAttack();
1094 m_swingErrorMsg = 2;
1097 else
1099 m_swingErrorMsg = 0; // reset swing error state
1101 // prevent base and off attack in same time, delay attack at 0.2 sec
1102 if(haveOffhandWeapon())
1104 uint32 off_att = getAttackTimer(OFF_ATTACK);
1105 if(off_att < ATTACK_DISPLAY_DELAY)
1106 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1108 AttackerStateUpdate(pVictim, BASE_ATTACK);
1109 resetAttackTimer(BASE_ATTACK);
1113 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1115 if(!IsWithinDistInMap(pVictim, pldistance))
1117 setAttackTimer(OFF_ATTACK,100);
1119 else if( !HasInArc( 2*M_PI/3, pVictim ))
1121 setAttackTimer(OFF_ATTACK,100);
1123 else
1125 // prevent base and off attack in same time, delay attack at 0.2 sec
1126 uint32 base_att = getAttackTimer(BASE_ATTACK);
1127 if(base_att < ATTACK_DISPLAY_DELAY)
1128 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1129 // do attack
1130 AttackerStateUpdate(pVictim, OFF_ATTACK);
1131 resetAttackTimer(OFF_ATTACK);
1135 Unit *owner = pVictim->GetOwner();
1136 Unit *u = owner ? owner : pVictim;
1137 if(u->IsPvP() && (!duel || duel->opponent != u))
1139 UpdatePvP(true);
1140 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1145 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1147 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1149 int time_inn = time(NULL)-GetTimeInnEnter();
1150 if (time_inn >= 10) //freeze update
1152 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1153 //speed collect rest bonus (section/in hour)
1154 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1155 UpdateInnerTime(time(NULL));
1160 if(m_regenTimer > 0)
1162 if(p_time >= m_regenTimer)
1163 m_regenTimer = 0;
1164 else
1165 m_regenTimer -= p_time;
1168 if (m_weaponChangeTimer > 0)
1170 if(p_time >= m_weaponChangeTimer)
1171 m_weaponChangeTimer = 0;
1172 else
1173 m_weaponChangeTimer -= p_time;
1176 if (m_zoneUpdateTimer > 0)
1178 if(p_time >= m_zoneUpdateTimer)
1180 uint32 newzone = GetZoneId();
1181 if( m_zoneUpdateId != newzone )
1182 UpdateZone(newzone); // also update area
1183 else
1185 // use area updates as well
1186 // needed for free far all arenas for example
1187 uint32 newarea = GetAreaId();
1188 if( m_areaUpdateId != newarea )
1189 UpdateArea(newarea);
1191 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1194 else
1195 m_zoneUpdateTimer -= p_time;
1198 if (isAlive())
1200 RegenerateAll();
1203 if (m_deathState == JUST_DIED)
1205 KillPlayer();
1208 if(m_nextSave > 0)
1210 if(p_time >= m_nextSave)
1212 // m_nextSave reseted in SaveToDB call
1213 SaveToDB();
1214 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1216 else
1218 m_nextSave -= p_time;
1222 //Breathtimer
1223 if(m_breathTimer > 0)
1225 if(p_time >= m_breathTimer)
1226 m_breathTimer = 0;
1227 else
1228 m_breathTimer -= p_time;
1232 //Handle Water/drowning
1233 HandleDrowning();
1235 //Handle lava
1236 HandleLava();
1238 //Handle detect stealth players
1239 if (m_DetectInvTimer > 0)
1241 if (p_time >= m_DetectInvTimer)
1243 m_DetectInvTimer = 3000;
1244 HandleStealthedUnitsDetection();
1246 else
1247 m_DetectInvTimer -= p_time;
1250 // Played time
1251 if (now > m_Last_tick)
1253 uint32 elapsed = uint32(now - m_Last_tick);
1254 m_Played_time[0] += elapsed; // Total played time
1255 m_Played_time[1] += elapsed; // Level played time
1256 m_Last_tick = now;
1259 if (m_drunk)
1261 m_drunkTimer += p_time;
1263 if (m_drunkTimer > 10000)
1264 HandleSobering();
1267 // not auto-free ghost from body in instances
1268 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1270 if(p_time >= m_deathTimer)
1272 m_deathTimer = 0;
1273 BuildPlayerRepop();
1274 RepopAtGraveyard();
1276 else
1277 m_deathTimer -= p_time;
1280 UpdateEnchantTime(p_time);
1281 UpdateHomebindTime(p_time);
1283 // group update
1284 SendUpdateToOutOfRangeGroupMembers();
1286 Pet* pet = GetPet();
1287 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1289 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1290 return;
1294 void Player::setDeathState(DeathState s)
1296 uint32 ressSpellId = 0;
1298 bool cur = isAlive();
1300 if(s == JUST_DIED && cur)
1302 // drunken state is cleared on death
1303 SetDrunkValue(0);
1304 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1305 ClearComboPoints();
1307 clearResurrectRequestData();
1309 // remove form before other mods to prevent incorrect stats calculation
1310 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1312 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1313 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1315 // remove uncontrolled pets
1316 RemoveMiniPet();
1317 RemoveGuardians();
1319 // save value before aura remove in Unit::setDeathState
1320 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1322 // passive spell
1323 if(!ressSpellId)
1324 ressSpellId = GetResurrectionSpellId();
1325 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1327 Unit::setDeathState(s);
1329 // restore resurrection spell id for player after aura remove
1330 if(s == JUST_DIED && cur && ressSpellId)
1331 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1333 if(isAlive() && !cur)
1335 //clear aura case after resurrection by another way (spells will be applied before next death)
1336 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1338 // restore default warrior stance
1339 if(getClass()== CLASS_WARRIOR)
1340 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1344 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1346 Field *fields = result->Fetch();
1348 *p_data << uint64(GetGUID());
1349 *p_data << m_name;
1351 *p_data << uint8(getRace());
1352 uint8 pClass = getClass();
1353 *p_data << uint8(pClass);
1354 *p_data << uint8(getGender());
1356 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1357 *p_data << uint8(bytes);
1358 *p_data << uint8(bytes >> 8);
1359 *p_data << uint8(bytes >> 16);
1360 *p_data << uint8(bytes >> 24);
1362 bytes = GetUInt32Value(PLAYER_BYTES_2);
1363 *p_data << uint8(bytes);
1365 *p_data << uint8(getLevel()); // player level
1366 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1367 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1368 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1369 *p_data << uint32(zoneId);
1370 *p_data << uint32(GetMapId());
1372 *p_data << GetPositionX();
1373 *p_data << GetPositionY();
1374 *p_data << GetPositionZ();
1376 // guild id
1377 *p_data << (result ? fields[13].GetUInt32() : 0);
1379 uint32 char_flags = 0;
1380 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1381 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1382 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1383 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1384 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1385 char_flags |= CHARACTER_FLAG_GHOST;
1386 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1387 char_flags |= CHARACTER_FLAG_RENAME;
1388 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1389 char_flags |= CHARACTER_FLAG_DECLINED;
1391 *p_data << uint32(char_flags); // character flags
1392 // character customize (flags?)
1393 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1394 *p_data << uint8(1); // unknown
1396 // Pets info
1398 uint32 petDisplayId = 0;
1399 uint32 petLevel = 0;
1400 uint32 petFamily = 0;
1402 // show pet at selection character in character list only for non-ghost character
1403 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1405 uint32 entry = fields[10].GetUInt32();
1406 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1407 if(cInfo)
1409 petDisplayId = fields[11].GetUInt32();
1410 petLevel = fields[12].GetUInt32();
1411 petFamily = cInfo->family;
1415 *p_data << uint32(petDisplayId);
1416 *p_data << uint32(petLevel);
1417 *p_data << uint32(petFamily);
1420 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1422 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1423 uint32 item_id = GetUInt32Value(visualbase);
1424 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1425 SpellItemEnchantmentEntry const *enchant = NULL;
1427 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1429 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1430 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1431 break;
1434 if (proto != NULL)
1436 *p_data << uint32(proto->DisplayInfoID);
1437 *p_data << uint8(proto->InventoryType);
1438 *p_data << uint32(enchant ? enchant->aura_id : 0);
1440 else
1442 *p_data << uint32(0);
1443 *p_data << uint8(0);
1444 *p_data << uint32(0); // enchant?
1447 *p_data << uint32(0); // first bag display id
1448 *p_data << uint8(0); // first bag inventory type
1449 *p_data << uint32(0); // enchant?
1452 bool Player::ToggleAFK()
1454 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1456 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1458 // afk player not allowed in battleground
1459 if(state && InBattleGround())
1460 LeaveBattleground();
1462 return state;
1465 bool Player::ToggleDND()
1467 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1469 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1472 uint8 Player::chatTag() const
1474 // it's bitmask
1475 // 0x8 - ??
1476 // 0x4 - gm
1477 // 0x2 - dnd
1478 // 0x1 - afk
1479 if(isGMChat())
1480 return 4;
1481 else if(isDND())
1482 return 3;
1483 if(isAFK())
1484 return 1;
1485 else
1486 return 0;
1489 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1491 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1493 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1494 return false;
1497 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1498 Pet* pet = GetPet();
1500 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1502 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1503 // don't let gm level > 1 either
1504 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1505 return false;
1507 // client without expansion support
1508 if(GetSession()->Expansion() < mEntry->Expansion())
1510 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1512 if(GetTransport())
1513 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1515 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1517 return false; // normal client can't teleport to this map...
1519 else
1521 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1524 // if we were on a transport, leave
1525 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1527 m_transport->RemovePassenger(this);
1528 m_transport = NULL;
1529 m_movementInfo.t_x = 0.0f;
1530 m_movementInfo.t_y = 0.0f;
1531 m_movementInfo.t_z = 0.0f;
1532 m_movementInfo.t_o = 0.0f;
1533 m_movementInfo.t_time = 0;
1536 SetSemaphoreTeleport(true);
1538 // The player was ported to another map and looses the duel immediately.
1539 // We have to perform this check before the teleport, otherwise the
1540 // ObjectAccessor won't find the flag.
1541 if (duel && GetMapId()!=mapid)
1543 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1544 if (obj)
1545 DuelComplete(DUEL_FLED);
1548 // reset movement flags at teleport, because player will continue move with these flags after teleport
1549 SetUnitMovementFlags(0);
1551 if ((GetMapId() == mapid) && (!m_transport))
1553 // prepare zone change detect
1554 uint32 old_zone = GetZoneId();
1556 // near teleport
1557 if(!GetSession()->PlayerLogout())
1559 WorldPacket data;
1560 BuildTeleportAckMsg(&data, x, y, z, orientation);
1561 GetSession()->SendPacket(&data);
1562 SetPosition( x, y, z, orientation, true);
1564 else
1565 // this will be used instead of the current location in SaveToDB
1566 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1567 SetFallInformation(0, z);
1569 //BuildHeartBeatMsg(&data);
1570 //SendMessageToSet(&data, true);
1571 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1573 //same map, only remove pet if out of range
1574 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1576 if(pet->isControlled() && !pet->isTemporarySummoned() )
1577 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1578 else
1579 m_temporaryUnsummonedPetNumber = 0;
1581 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1585 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1586 CombatStop();
1588 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1590 // resummon pet
1591 if(pet && m_temporaryUnsummonedPetNumber)
1593 Pet* NewPet = new Pet;
1594 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1595 delete NewPet;
1597 m_temporaryUnsummonedPetNumber = 0;
1601 if(!GetSession()->PlayerLogout())
1603 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1604 SetSemaphoreTeleport(false);
1606 UpdateZone(GetZoneId());
1609 // new zone
1610 if(old_zone != GetZoneId())
1612 // honorless target
1613 if(pvpInfo.inHostileArea)
1614 CastSpell(this, 2479, true);
1617 else
1619 // far teleport to another map
1620 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1621 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1623 // Check enter rights before map getting to avoid creating instance copy for player
1624 // this check not dependent from map instance copy and same for all instance copies of selected map
1625 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1627 SetSemaphoreTeleport(false);
1628 return false;
1631 // If the map is not created, assume it is possible to enter it.
1632 // It will be created in the WorldPortAck.
1633 Map *map = MapManager::Instance().FindMap(mapid);
1634 if (!map || map->CanEnter(this))
1636 SetSelection(0);
1638 CombatStop();
1640 ResetContestedPvP();
1642 // remove player from battleground on far teleport (when changing maps)
1643 if(BattleGround const* bg = GetBattleGround())
1645 // Note: at battleground join battleground id set before teleport
1646 // and we already will found "current" battleground
1647 // just need check that this is targeted map or leave
1648 if(bg->GetMapId() != mapid)
1649 LeaveBattleground(false); // don't teleport to entry point
1652 // remove pet on map change
1653 if (pet)
1655 //leaving map -> delete pet right away (doing this later will cause problems)
1656 if(pet->isControlled() && !pet->isTemporarySummoned())
1657 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1658 else
1659 m_temporaryUnsummonedPetNumber = 0;
1661 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1664 // remove all dyn objects
1665 RemoveAllDynObjects();
1667 // stop spellcasting
1668 // not attempt interrupt teleportation spell at caster teleport
1669 if(!(options & TELE_TO_SPELL))
1670 if(IsNonMeleeSpellCasted(true))
1671 InterruptNonMeleeSpells(true);
1673 if(!GetSession()->PlayerLogout())
1675 // send transfer packets
1676 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1677 data << uint32(mapid);
1678 if (m_transport)
1680 data << m_transport->GetEntry() << GetMapId();
1682 GetSession()->SendPacket(&data);
1684 data.Initialize(SMSG_NEW_WORLD, (20));
1685 if (m_transport)
1687 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1689 else
1691 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1693 GetSession()->SendPacket( &data );
1694 SendSavedInstances();
1696 // remove from old map now
1697 if(oldmap) oldmap->Remove(this, false);
1700 // new final coordinates
1701 float final_x = x;
1702 float final_y = y;
1703 float final_z = z;
1704 float final_o = orientation;
1706 if(m_transport)
1708 final_x += m_movementInfo.t_x;
1709 final_y += m_movementInfo.t_y;
1710 final_z += m_movementInfo.t_z;
1711 final_o += m_movementInfo.t_o;
1714 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1715 SetFallInformation(0, final_z);
1716 // if the player is saved before worldportack (at logout for example)
1717 // this will be used instead of the current location in SaveToDB
1719 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1721 // move packet sent by client always after far teleport
1722 // SetPosition(final_x, final_y, final_z, final_o, true);
1723 SetDontMove(true);
1725 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1727 else
1728 return false;
1730 return true;
1733 void Player::AddToWorld()
1735 ///- Do not add/remove the player from the object storage
1736 ///- It will crash when updating the ObjectAccessor
1737 ///- The player should only be added when logging in
1738 Unit::AddToWorld();
1740 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1742 if(m_items[i])
1743 m_items[i]->AddToWorld();
1747 void Player::RemoveFromWorld()
1749 // cleanup
1750 if(IsInWorld())
1752 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1753 Uncharm();
1754 UnsummonAllTotems();
1755 RemoveMiniPet();
1756 RemoveGuardians();
1759 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1761 if(m_items[i])
1762 m_items[i]->RemoveFromWorld();
1765 ///- Do not add/remove the player from the object storage
1766 ///- It will crash when updating the ObjectAccessor
1767 ///- The player should only be removed when logging out
1768 Unit::RemoveFromWorld();
1771 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1773 float addRage;
1775 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1777 if(attacker)
1779 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1781 // talent who gave more rage on attack
1782 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1784 else
1786 addRage = damage/rageconversion*2.5;
1788 // Berserker Rage effect
1789 if(HasAura(18499,0))
1790 addRage *= 1.3;
1793 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1795 ModifyPower(POWER_RAGE, uint32(addRage*10));
1798 void Player::RegenerateAll()
1800 if (m_regenTimer != 0)
1801 return;
1802 uint32 regenDelay = 2000;
1804 // Not in combat or they have regeneration
1805 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1806 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1808 RegenerateHealth();
1809 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1811 Regenerate(POWER_RAGE);
1812 if(getClass() == CLASS_DEATH_KNIGHT)
1813 Regenerate(POWER_RUNIC_POWER);
1817 Regenerate( POWER_ENERGY );
1819 Regenerate( POWER_MANA );
1821 if(getClass() == CLASS_DEATH_KNIGHT)
1822 Regenerate( POWER_RUNE );
1824 m_regenTimer = regenDelay;
1827 void Player::Regenerate(Powers power)
1829 uint32 curValue = GetPower(power);
1830 uint32 maxValue = GetMaxPower(power);
1832 float addvalue = 0.0f;
1834 switch (power)
1836 case POWER_MANA:
1838 bool recentCast = IsUnderLastManaUseEffect();
1839 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1840 if (recentCast)
1842 // Mangos Updates Mana in intervals of 2s, which is correct
1843 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1845 else
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 } break;
1850 case POWER_RAGE: // Regenerate rage
1852 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1853 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1854 } break;
1855 case POWER_ENERGY: // Regenerate energy (rogue)
1856 addvalue = 20;
1857 break;
1858 case POWER_RUNIC_POWER:
1860 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1861 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1862 } break;
1863 case POWER_RUNE:
1865 for(uint32 i = 0; i < MAX_RUNES; ++i)
1866 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1867 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1868 } break;
1869 case POWER_FOCUS:
1870 case POWER_HAPPINESS:
1871 break;
1874 // Mana regen calculated in Player::UpdateManaRegen()
1875 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1876 if(power != POWER_MANA)
1878 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1879 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1880 if ((*i)->GetModifier()->m_miscvalue == power)
1881 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1884 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1886 curValue += uint32(addvalue);
1887 if (curValue > maxValue)
1888 curValue = maxValue;
1890 else
1892 if(curValue <= uint32(addvalue))
1893 curValue = 0;
1894 else
1895 curValue -= uint32(addvalue);
1897 SetPower(power, curValue);
1900 void Player::RegenerateHealth()
1902 uint32 curValue = GetHealth();
1903 uint32 maxValue = GetMaxHealth();
1905 if (curValue >= maxValue) return;
1907 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1909 float addvalue = 0.0f;
1911 // polymorphed case
1912 if ( IsPolymorphed() )
1913 addvalue = GetMaxHealth()/3;
1914 // normal regen case (maybe partly in combat case)
1915 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1917 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1918 if (!isInCombat())
1920 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1921 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1922 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1924 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1925 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1927 if(!IsStandState())
1928 addvalue *= 1.5;
1931 // always regeneration bonus (including combat)
1932 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1934 if(addvalue < 0)
1935 addvalue = 0;
1937 ModifyHealth(int32(addvalue));
1940 bool Player::CanInteractWithNPCs(bool alive) const
1942 if(alive && !isAlive())
1943 return false;
1944 if(isInFlight())
1945 return false;
1947 return true;
1950 bool Player::IsUnderWater() const
1952 return IsInWater() &&
1953 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1956 void Player::SetInWater(bool apply)
1958 if(m_isInWater==apply)
1959 return;
1961 //define player in water by opcodes
1962 //move player's guid into HateOfflineList of those mobs
1963 //which can't swim and move guid back into ThreatList when
1964 //on surface.
1965 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1966 m_isInWater = apply;
1968 // remove auras that need water/land
1969 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1971 getHostilRefManager().updateThreatTables();
1974 void Player::SetGameMaster(bool on)
1976 if(on)
1978 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1979 setFaction(35);
1980 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1982 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1983 ResetContestedPvP();
1985 getHostilRefManager().setOnlineOfflineState(false);
1986 CombatStop();
1988 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
1990 else
1992 // restore phase
1993 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
1994 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
1996 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1997 setFactionForRace(getRace());
1998 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2000 // restore FFA PvP Server state
2001 if(sWorld.IsFFAPvPRealm())
2002 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2004 // restore FFA PvP area state, remove not allowed for GM mounts
2005 UpdateArea(m_areaUpdateId);
2007 getHostilRefManager().setOnlineOfflineState(true);
2010 ObjectAccessor::UpdateVisibilityForPlayer(this);
2013 void Player::SetGMVisible(bool on)
2015 if(on)
2017 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2019 // Reapply stealth/invisibility if active or show if not any
2020 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2021 SetVisibility(VISIBILITY_GROUP_STEALTH);
2022 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2023 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2024 else
2025 SetVisibility(VISIBILITY_ON);
2027 else
2029 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2031 SetAcceptWhispers(false);
2032 SetGameMaster(true);
2034 SetVisibility(VISIBILITY_OFF);
2038 bool Player::IsGroupVisibleFor(Player* p) const
2040 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2042 default: return IsInSameGroupWith(p);
2043 case 1: return IsInSameRaidWith(p);
2044 case 2: return GetTeam()==p->GetTeam();
2048 bool Player::IsInSameGroupWith(Player const* p) const
2050 return p==this || GetGroup() != NULL &&
2051 GetGroup() == p->GetGroup() &&
2052 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2055 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2056 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2057 void Player::UninviteFromGroup()
2059 Group* group = GetGroupInvite();
2060 if(!group)
2061 return;
2063 group->RemoveInvite(this);
2065 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2067 if(group->IsCreated())
2069 group->Disband(true);
2070 objmgr.RemoveGroup(group);
2072 else
2073 group->RemoveAllInvites();
2075 delete group;
2079 void Player::RemoveFromGroup(Group* group, uint64 guid)
2081 if(group)
2083 if (group->RemoveMember(guid, 0) <= 1)
2085 // group->Disband(); already disbanded in RemoveMember
2086 objmgr.RemoveGroup(group);
2087 delete group;
2088 // removemember sets the player's group pointer to NULL
2093 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2095 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2096 data << uint64(victim ? victim->GetGUID() : 0); // guid
2097 data << uint32(GivenXP+RestXP); // given experience
2098 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2099 if(victim)
2101 data << uint32(GivenXP); // experience without rested bonus
2102 data << float(1); // 1 - none 0 - 100% group bonus output
2104 data << uint8(0); // new 2.4.0
2105 GetSession()->SendPacket(&data);
2108 void Player::GiveXP(uint32 xp, Unit* victim)
2110 if ( xp < 1 )
2111 return;
2113 if(!isAlive())
2114 return;
2116 uint32 level = getLevel();
2118 // XP to money conversion processed in Player::RewardQuest
2119 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2120 return;
2122 // handle SPELL_AURA_MOD_XP_PCT auras
2123 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2124 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2125 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2127 // XP resting bonus for kill
2128 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2130 SendLogXPGain(xp,victim,rested_bonus_xp);
2132 uint32 curXP = GetUInt32Value(PLAYER_XP);
2133 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2134 uint32 newXP = curXP + xp + rested_bonus_xp;
2136 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2138 newXP -= nextLvlXP;
2140 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2141 GiveLevel(level + 1);
2143 level = getLevel();
2144 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2147 SetUInt32Value(PLAYER_XP, newXP);
2150 // Update player to next level
2151 // Current player experience not update (must be update by caller)
2152 void Player::GiveLevel(uint32 level)
2154 if ( level == getLevel() )
2155 return;
2157 PlayerLevelInfo info;
2158 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2160 PlayerClassLevelInfo classInfo;
2161 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2163 // send levelup info to client
2164 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2165 data << uint32(level);
2166 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2167 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2168 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2169 data << uint32(0);
2170 data << uint32(0);
2171 data << uint32(0);
2172 data << uint32(0);
2173 data << uint32(0);
2174 data << uint32(0);
2175 // end for
2176 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2177 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2179 GetSession()->SendPacket(&data);
2181 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2183 //update level, max level of skills
2184 if(getLevel()!= level)
2185 m_Played_time[1] = 0; // Level Played Time reset
2186 SetLevel(level);
2187 UpdateSkillsForLevel ();
2189 // save base values (bonuses already included in stored stats
2190 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2191 SetCreateStat(Stats(i), info.stats[i]);
2193 SetCreateHealth(classInfo.basehealth);
2194 SetCreateMana(classInfo.basemana);
2196 InitTalentForLevel();
2197 InitTaxiNodesForLevel();
2198 InitGlyphsForLevel();
2200 UpdateAllStats();
2202 // set current level health and mana/energy to maximum after applying all mods.
2203 SetHealth(GetMaxHealth());
2204 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2205 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2206 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2207 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2208 SetPower(POWER_FOCUS, 0);
2209 SetPower(POWER_HAPPINESS, 0);
2211 // give level to summoned pet
2212 Pet* pet = GetPet();
2213 if(pet && pet->getPetType()==SUMMON_PET)
2214 pet->GivePetLevel(level);
2215 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2218 void Player::InitTalentForLevel()
2220 uint32 level = getLevel();
2221 // talents base at level diff ( talents = level - 9 but some can be used already)
2222 if(level < 10)
2224 // Remove all talent points
2225 if(m_usedTalentCount > 0) // Free any used talents
2227 resetTalents(true);
2228 SetFreeTalentPoints(0);
2231 else
2233 uint32 talentPointsForLevel = CalculateTalentsPoints();
2235 // if used more that have then reset
2236 if(m_usedTalentCount > talentPointsForLevel)
2238 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2239 resetTalents(true);
2240 else
2241 SetFreeTalentPoints(0);
2243 // else update amount of free points
2244 else
2245 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2249 void Player::InitStatsForLevel(bool reapplyMods)
2251 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2252 _RemoveAllStatBonuses();
2254 PlayerClassLevelInfo classInfo;
2255 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2257 PlayerLevelInfo info;
2258 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2260 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2261 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2263 UpdateSkillsForLevel ();
2265 // set default cast time multiplier
2266 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2268 // reset size before reapply auras
2269 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2271 // save base values (bonuses already included in stored stats
2272 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2273 SetCreateStat(Stats(i), info.stats[i]);
2275 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2276 SetStat(Stats(i), info.stats[i]);
2278 SetCreateHealth(classInfo.basehealth);
2280 //set create powers
2281 SetCreateMana(classInfo.basemana);
2283 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2285 InitStatBuffMods();
2287 //reset rating fields values
2288 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2289 SetUInt32Value(index, 0);
2291 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2292 for (int i = 0; i < 7; i++)
2294 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2295 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2296 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2299 //reset attack power, damage and attack speed fields
2300 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2301 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2302 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2304 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2305 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2306 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2307 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2308 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2309 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2311 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2312 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2313 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2314 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2315 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2316 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2318 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2319 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2320 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2321 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2323 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2324 for (uint8 i = 0; i < 7; ++i)
2325 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2327 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2328 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2329 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2331 // Dodge percentage
2332 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2334 // set armor (resistance 0) to original value (create_agility*2)
2335 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2336 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2337 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2338 // set other resistance to original value (0)
2339 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2341 SetResistance(SpellSchools(i), 0);
2342 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2343 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2346 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2347 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2348 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2350 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2351 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2353 // Reset no reagent cost field
2354 for(int i = 0; i < 3; i++)
2355 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2356 // Init data for form but skip reapply item mods for form
2357 InitDataForForm(reapplyMods);
2359 // save new stats
2360 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2361 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2363 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2365 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2366 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2368 // cleanup unit flags (will be re-applied if need at aura load).
2369 RemoveFlag( UNIT_FIELD_FLAGS,
2370 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2371 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2372 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2373 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2374 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2375 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2377 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2378 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2380 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2381 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2383 // restore if need some important flags
2384 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2386 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2387 _ApplyAllStatBonuses();
2389 // set current level health and mana/energy to maximum after applying all mods.
2390 SetHealth(GetMaxHealth());
2391 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2392 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2393 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2394 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2395 SetPower(POWER_FOCUS, 0);
2396 SetPower(POWER_HAPPINESS, 0);
2397 SetPower(POWER_RUNIC_POWER, 0);
2400 void Player::SendInitialSpells()
2402 uint16 spellCount = 0;
2404 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2405 data << uint8(0);
2407 size_t countPos = data.wpos();
2408 data << uint16(spellCount); // spell count placeholder
2410 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2412 if(itr->second->state == PLAYERSPELL_REMOVED)
2413 continue;
2415 if(!itr->second->active || itr->second->disabled)
2416 continue;
2418 data << uint16(itr->first);
2419 data << uint16(0); // it's not slot id
2421 spellCount +=1;
2424 data.put<uint16>(countPos,spellCount); // write real count value
2426 uint16 spellCooldowns = m_spellCooldowns.size();
2427 data << uint16(spellCooldowns);
2428 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2430 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2431 if(!sEntry)
2432 continue;
2434 data << uint16(itr->first);
2436 time_t cooldown = 0;
2437 time_t curTime = time(NULL);
2438 if(itr->second.end > curTime)
2439 cooldown = (itr->second.end-curTime)*1000;
2441 data << uint16(itr->second.itemid); // cast item id
2442 data << uint16(sEntry->Category); // spell category
2443 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2445 data << uint32(0); // cooldown
2446 data << uint32(cooldown); // category cooldown
2448 else
2450 data << uint32(cooldown); // cooldown
2451 data << uint32(0); // category cooldown
2455 GetSession()->SendPacket(&data);
2457 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2460 void Player::RemoveMail(uint32 id)
2462 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2464 if ((*itr)->messageID == id)
2466 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2467 m_mail.erase(itr);
2468 return;
2473 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2475 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2476 data << (uint32) mailId;
2477 data << (uint32) mailAction;
2478 data << (uint32) mailError;
2479 if ( mailError == MAIL_ERR_BAG_FULL )
2480 data << (uint32) equipError;
2481 else if( mailAction == MAIL_ITEM_TAKEN )
2483 data << (uint32) item_guid; // item guid low?
2484 data << (uint32) item_count; // item count?
2486 GetSession()->SendPacket(&data);
2489 void Player::SendNewMail()
2491 // deliver undelivered mail
2492 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2493 data << (uint32) 0;
2494 GetSession()->SendPacket(&data);
2497 void Player::UpdateNextMailTimeAndUnreads()
2499 // calculate next delivery time (min. from non-delivered mails
2500 // and recalculate unReadMail
2501 time_t cTime = time(NULL);
2502 m_nextMailDelivereTime = 0;
2503 unReadMails = 0;
2504 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2506 if((*itr)->deliver_time > cTime)
2508 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2509 m_nextMailDelivereTime = (*itr)->deliver_time;
2511 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2512 ++unReadMails;
2516 void Player::AddNewMailDeliverTime(time_t deliver_time)
2518 if(deliver_time <= time(NULL)) // ready now
2520 ++unReadMails;
2521 SendNewMail();
2523 else // not ready and no have ready mails
2525 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2526 m_nextMailDelivereTime = deliver_time;
2530 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2532 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2533 if (!spellInfo)
2535 // do character spell book cleanup (all characters)
2536 if(!IsInWorld() && !learning) // spell load case
2538 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2539 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2541 else
2542 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2544 return false;
2547 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2549 // do character spell book cleanup (all characters)
2550 if(!IsInWorld() && !learning) // spell load case
2552 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2553 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2555 else
2556 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2558 return false;
2561 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2563 bool dependent_set = false;
2564 bool disabled_case = false;
2565 bool superceded_old = false;
2567 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2568 if (itr != m_spells.end())
2570 uint32 next_active_spell_id = 0;
2571 // fix activate state for non-stackable low rank (and find next spell for !active case)
2572 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2574 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2575 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2577 if(HasSpell(next_itr->second))
2579 // high rank already known so this must !active
2580 active = false;
2581 next_active_spell_id = next_itr->second;
2582 break;
2587 // not do anything if already known in expected state
2588 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2589 itr->second->dependent == dependent && itr->second->disabled == disabled)
2591 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2592 itr->second->state = PLAYERSPELL_UNCHANGED;
2594 return false;
2597 // dependent spell known as not dependent, overwrite state
2598 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2600 itr->second->dependent = dependent;
2601 if (itr->second->state != PLAYERSPELL_NEW)
2602 itr->second->state = PLAYERSPELL_CHANGED;
2603 dependent_set = true;
2606 // update active state for known spell
2607 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2609 itr->second->active = active;
2611 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2612 itr->second->state = PLAYERSPELL_UNCHANGED;
2613 else if(itr->second->state != PLAYERSPELL_NEW)
2614 itr->second->state = PLAYERSPELL_CHANGED;
2616 if(active)
2618 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2619 CastSpell (this,spell_id,true);
2621 else if(IsInWorld())
2623 if(next_active_spell_id)
2625 // update spell ranks in spellbook and action bar
2626 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2627 data << uint16(spell_id);
2628 data << uint16(next_active_spell_id);
2629 GetSession()->SendPacket( &data );
2631 else
2633 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2634 data << uint16(spell_id);
2635 GetSession()->SendPacket(&data);
2639 return active; // learn (show in spell book if active now)
2642 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2644 if(itr->second->state != PLAYERSPELL_NEW)
2645 itr->second->state = PLAYERSPELL_CHANGED;
2646 itr->second->disabled = disabled;
2648 if(disabled)
2649 return false;
2651 disabled_case = true;
2653 else switch(itr->second->state)
2655 case PLAYERSPELL_UNCHANGED: // known saved spell
2656 return false;
2657 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2659 delete itr->second;
2660 m_spells.erase(itr);
2661 state = PLAYERSPELL_CHANGED;
2662 break; // need re-add
2664 default: // known not saved yet spell (new or modified)
2666 // can be in case spell loading but learned at some previous spell loading
2667 if(!IsInWorld() && !learning && !dependent_set)
2668 itr->second->state = PLAYERSPELL_UNCHANGED;
2670 return false;
2675 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2677 // talent: unlearn all other talent ranks (high and low)
2678 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2680 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2682 for(int i=0; i <5; ++i)
2684 // skip learning spell and no rank spell case
2685 uint32 rankSpellId = talentInfo->RankID[i];
2686 if(!rankSpellId || rankSpellId==spell_id)
2687 continue;
2689 removeSpell(rankSpellId);
2693 // non talent spell: learn low ranks (recursive call)
2694 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2696 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2697 addSpell(prev_spell,active,true,true,disabled);
2698 else // at normal learning
2699 learnSpell(prev_spell,true);
2702 PlayerSpell *newspell = new PlayerSpell;
2703 newspell->state = state;
2704 newspell->active = active;
2705 newspell->dependent = dependent;
2706 newspell->disabled = disabled;
2708 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2709 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2711 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2713 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2714 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2715 if(!i_spellInfo) continue;
2717 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2719 if(itr->second->active)
2721 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2723 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2725 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2726 data << uint16(itr->first);
2727 data << uint16(spell_id);
2728 GetSession()->SendPacket( &data );
2731 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2732 itr->second->active = false;
2733 if(itr->second->state != PLAYERSPELL_NEW)
2734 itr->second->state = PLAYERSPELL_CHANGED;
2735 superceded_old = true; // new spell replace old in action bars and spell book.
2737 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2739 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2741 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2742 data << uint16(spell_id);
2743 data << uint16(itr->first);
2744 GetSession()->SendPacket( &data );
2747 // mark new spell as disable (not learned yet for client and will not learned)
2748 newspell->active = false;
2749 if(newspell->state != PLAYERSPELL_NEW)
2750 newspell->state = PLAYERSPELL_CHANGED;
2757 m_spells[spell_id] = newspell;
2759 // return false if spell disabled
2760 if (newspell->disabled)
2761 return false;
2764 uint32 talentCost = GetTalentSpellCost(spell_id);
2766 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2767 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2768 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2770 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2771 CastSpell(this, spell_id, true);
2773 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2774 else if (IsPassiveSpell(spell_id))
2776 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2777 CastSpell(this, spell_id, true);
2779 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2781 CastSpell(this, spell_id, true);
2782 return false;
2785 // update used talent points count
2786 m_usedTalentCount += talentCost;
2788 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2789 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2791 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2792 SetFreePrimaryProffesions(freeProfs-1);
2795 // add dependent skills
2796 uint16 maxskill = GetMaxSkillValueForLevel();
2798 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2800 if(spellLearnSkill)
2802 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2803 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2805 if(skill_value < spellLearnSkill->value)
2806 skill_value = spellLearnSkill->value;
2808 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2810 if(skill_max_value < new_skill_max_value)
2811 skill_max_value = new_skill_max_value;
2813 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2815 else
2817 // not ranked skills
2818 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2819 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2821 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2823 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2824 if(!pSkill)
2825 continue;
2827 if(HasSkill(pSkill->id))
2828 continue;
2830 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2831 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2832 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2834 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2836 case SKILL_RANGE_LANGUAGE:
2837 SetSkill(pSkill->id, 300, 300 );
2838 break;
2839 case SKILL_RANGE_LEVEL:
2840 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2841 break;
2842 case SKILL_RANGE_MONO:
2843 SetSkill(pSkill->id, 1, 1 );
2844 break;
2845 default:
2846 break;
2852 // learn dependent spells
2853 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2854 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2856 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2858 if(!itr->second.autoLearned)
2860 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2861 addSpell(itr->second.spell,itr->second.active,true,true,false);
2862 else // at normal learning
2863 learnSpell(itr->second.spell,true);
2867 if(IsInWorld())
2869 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2873 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2874 return active && !disabled && !superceded_old;
2877 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2879 bool need_cast = false;
2881 switch(spellInfo->Id)
2883 // some spells not have stance data expacted cast at form change or present
2884 case 5420: need_cast = (m_form == FORM_TREE); break;
2885 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2886 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2887 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2888 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2889 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2890 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2891 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2892 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2893 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2894 // another spells have proper stance data
2895 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2898 //Check CasterAuraStates
2899 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
2902 void Player::learnSpell(uint32 spell_id, bool dependent)
2904 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2906 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2907 bool active = disabled ? itr->second->active : true;
2909 bool learning = addSpell(spell_id,active,true,dependent,false);
2911 // learn all disabled higher ranks (recursive)
2912 if(disabled)
2914 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2915 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2917 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2918 if (iter != m_spells.end() && iter->second->disabled)
2919 learnSpell(i->second,false);
2923 // prevent duplicated entires in spell book, also not send if not in world (loading)
2924 if(!learning || !IsInWorld ())
2925 return;
2927 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2928 data << uint32(spell_id);
2929 GetSession()->SendPacket(&data);
2932 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
2934 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2935 if (itr == m_spells.end())
2936 return;
2938 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2939 return;
2941 // unlearn non talent higher ranks (recursive)
2942 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2943 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2944 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2945 removeSpell(itr2->second,disabled);
2947 bool cur_active = itr->second->active;
2948 bool cur_dependent = itr->second->dependent;
2950 if (disabled)
2952 itr->second->disabled = disabled;
2953 if(itr->second->state != PLAYERSPELL_NEW)
2954 itr->second->state = PLAYERSPELL_CHANGED;
2956 else
2958 if(itr->second->state == PLAYERSPELL_NEW)
2960 delete itr->second;
2961 m_spells.erase(itr);
2963 else
2964 itr->second->state = PLAYERSPELL_REMOVED;
2967 RemoveAurasDueToSpell(spell_id);
2969 // remove pet auras
2970 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2971 RemovePetAura(petSpell);
2973 // free talent points
2974 uint32 talentCosts = GetTalentSpellCost(spell_id);
2975 if(talentCosts > 0)
2977 if(talentCosts < m_usedTalentCount)
2978 m_usedTalentCount -= talentCosts;
2979 else
2980 m_usedTalentCount = 0;
2983 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2984 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2986 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2987 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2988 SetFreePrimaryProffesions(freeProfs);
2991 // remove dependent skill
2992 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2993 if(spellLearnSkill)
2995 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2996 if(!prev_spell) // first rank, remove skill
2997 SetSkill(spellLearnSkill->skill,0,0);
2998 else
3000 // search prev. skill setting by spell ranks chain
3001 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3002 while(!prevSkill && prev_spell)
3004 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3005 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3008 if(!prevSkill) // not found prev skill setting, remove skill
3009 SetSkill(spellLearnSkill->skill,0,0);
3010 else // set to prev. skill setting values
3012 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3013 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3015 if(skill_value > prevSkill->value)
3016 skill_value = prevSkill->value;
3018 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3020 if(skill_max_value > new_skill_max_value)
3021 skill_max_value = new_skill_max_value;
3023 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3028 else
3030 // not ranked skills
3031 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3032 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3034 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3036 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3037 if(!pSkill)
3038 continue;
3040 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3041 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3042 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
3044 // not reset skills for professions and racial abilities
3045 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3046 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3047 continue;
3049 SetSkill(pSkill->id, 0, 0 );
3054 // remove dependent spells
3055 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3056 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3058 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3059 removeSpell(itr2->second.spell, disabled);
3061 // activate lesser rank in spellbook/action bar, and cast it if need
3062 bool prev_activate = false;
3064 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3066 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3068 // if talent then lesser rank also talent and need learn
3069 if(talentCosts)
3070 learnSpell (prev_id,false);
3071 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3072 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3074 // need manually update dependence state (learn spell ignore like attempts)
3075 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3076 if (prev_itr != m_spells.end())
3078 if(prev_itr->second->dependent != cur_dependent)
3080 prev_itr->second->dependent = cur_dependent;
3081 if(prev_itr->second->state != PLAYERSPELL_NEW)
3082 prev_itr->second->state = PLAYERSPELL_CHANGED;
3085 // now re-learn if need re-activate
3086 if(cur_active && !prev_itr->second->active)
3088 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3090 if(update_action_bar_for_low_rank)
3092 // downgrade spell ranks in spellbook and action bar
3093 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3094 data << uint16(spell_id);
3095 data << uint16(prev_id);
3096 GetSession()->SendPacket( &data );
3097 prev_activate = true;
3105 // remove from spell book if not replaced by lesser rank
3106 if(!prev_activate)
3108 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3109 data << uint16(spell_id);
3110 GetSession()->SendPacket(&data);
3114 void Player::RemoveArenaSpellCooldowns()
3116 // remove cooldowns on spells that has < 15 min CD
3117 SpellCooldowns::iterator itr, next;
3118 // iterate spell cooldowns
3119 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3121 next = itr;
3122 ++next;
3123 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3124 // check if spellentry is present and if the cooldown is less than 15 mins
3125 if( entry &&
3126 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3127 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3129 // notify player
3130 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3131 data << uint32(itr->first);
3132 data << GetGUID();
3133 GetSession()->SendPacket(&data);
3134 // remove cooldown
3135 m_spellCooldowns.erase(itr);
3140 void Player::RemoveAllSpellCooldown()
3142 if(!m_spellCooldowns.empty())
3144 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3146 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3147 data << uint32(itr->first);
3148 data << uint64(GetGUID());
3149 GetSession()->SendPacket(&data);
3151 m_spellCooldowns.clear();
3155 void Player::_LoadSpellCooldowns(QueryResult *result)
3157 m_spellCooldowns.clear();
3159 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3161 if(result)
3163 time_t curTime = time(NULL);
3167 Field *fields = result->Fetch();
3169 uint32 spell_id = fields[0].GetUInt32();
3170 uint32 item_id = fields[1].GetUInt32();
3171 time_t db_time = (time_t)fields[2].GetUInt64();
3173 if(!sSpellStore.LookupEntry(spell_id))
3175 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3176 continue;
3179 // skip outdated cooldown
3180 if(db_time <= curTime)
3181 continue;
3183 AddSpellCooldown(spell_id, item_id, db_time);
3185 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3187 while( result->NextRow() );
3189 delete result;
3193 void Player::_SaveSpellCooldowns()
3195 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3197 time_t curTime = time(NULL);
3199 // remove outdated and save active
3200 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3202 if(itr->second.end <= curTime)
3203 m_spellCooldowns.erase(itr++);
3204 else
3206 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3207 ++itr;
3212 uint32 Player::resetTalentsCost() const
3214 // The first time reset costs 1 gold
3215 if(m_resetTalentsCost < 1*GOLD)
3216 return 1*GOLD;
3217 // then 5 gold
3218 else if(m_resetTalentsCost < 5*GOLD)
3219 return 5*GOLD;
3220 // After that it increases in increments of 5 gold
3221 else if(m_resetTalentsCost < 10*GOLD)
3222 return 10*GOLD;
3223 else
3225 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3226 if(months > 0)
3228 // This cost will be reduced by a rate of 5 gold per month
3229 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3230 // to a minimum of 10 gold.
3231 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3233 else
3235 // After that it increases in increments of 5 gold
3236 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3237 // until it hits a cap of 50 gold.
3238 if(new_cost > 50*GOLD)
3239 new_cost = 50*GOLD;
3240 return new_cost;
3245 bool Player::resetTalents(bool no_cost)
3247 // not need after this call
3248 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3250 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3251 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3254 uint32 talentPointsForLevel = CalculateTalentsPoints();
3256 if (m_usedTalentCount == 0)
3258 SetFreeTalentPoints(talentPointsForLevel);
3259 return false;
3262 uint32 cost = 0;
3264 if(!no_cost)
3266 cost = resetTalentsCost();
3268 if (GetMoney() < cost)
3270 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3271 return false;
3275 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3277 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3279 if (!talentInfo) continue;
3281 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3283 if(!talentTabInfo)
3284 continue;
3286 // unlearn only talents for character class
3287 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3288 // to prevent unexpected lost normal learned spell skip another class talents
3289 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3290 continue;
3292 for (int j = 0; j < 5; j++)
3294 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3296 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3298 ++itr;
3299 continue;
3302 // remove learned spells (all ranks)
3303 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3305 // unlearn if first rank is talent or learned by talent
3306 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3308 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3309 itr = GetSpellMap().begin();
3310 continue;
3312 else
3313 ++itr;
3318 SetFreeTalentPoints(talentPointsForLevel);
3320 if(!no_cost)
3322 ModifyMoney(-(int32)cost);
3324 m_resetTalentsCost = cost;
3325 m_resetTalentsTime = time(NULL);
3328 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3329 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3331 return true;
3334 Mail* Player::GetMail(uint32 id)
3336 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3338 if ((*itr)->messageID == id)
3340 return (*itr);
3343 return NULL;
3346 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3348 if(target == this)
3350 Object::_SetCreateBits(updateMask, target);
3352 else
3354 for(uint16 index = 0; index < m_valuesCount; index++)
3356 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3357 updateMask->SetBit(index);
3362 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3364 if(target == this)
3366 Object::_SetUpdateBits(updateMask, target);
3368 else
3370 Object::_SetUpdateBits(updateMask, target);
3371 *updateMask &= updateVisualBits;
3375 void Player::InitVisibleBits()
3377 updateVisualBits.SetCount(PLAYER_END);
3379 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3380 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3381 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3382 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3383 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3384 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3385 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3386 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3387 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3388 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3389 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3390 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3391 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3392 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3393 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3394 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3395 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3396 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3397 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3398 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3399 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3400 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3401 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3402 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3403 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3404 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3405 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3406 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3407 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3408 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3409 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3410 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3411 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3412 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3413 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3414 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3415 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3416 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3417 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3418 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3419 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3420 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3421 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3422 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3423 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3424 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3425 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3426 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3427 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3428 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3429 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3430 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3431 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3432 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3433 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3435 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3436 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3437 updateVisualBits.SetBit(PLAYER_FLAGS);
3438 updateVisualBits.SetBit(PLAYER_GUILDID);
3439 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3440 updateVisualBits.SetBit(PLAYER_BYTES);
3441 updateVisualBits.SetBit(PLAYER_BYTES_2);
3442 updateVisualBits.SetBit(PLAYER_BYTES_3);
3443 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3444 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3446 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3447 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3448 updateVisualBits.SetBit(i);
3450 // Players visible items are not inventory stuff
3451 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3453 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3455 // item creator
3456 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3457 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3459 // item entry
3460 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3462 // item enchantments
3463 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3464 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3466 // random properties
3467 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3468 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3469 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3472 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3475 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3477 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3479 if(m_items[i] == NULL)
3480 continue;
3482 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3485 if(target == this)
3487 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3489 if(m_items[i] == NULL)
3490 continue;
3492 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3494 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3496 if(m_items[i] == NULL)
3497 continue;
3499 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3503 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3506 void Player::DestroyForPlayer( Player *target ) const
3508 Unit::DestroyForPlayer( target );
3510 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3512 if(m_items[i] == NULL)
3513 continue;
3515 m_items[i]->DestroyForPlayer( target );
3518 if(target == this)
3520 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3522 if(m_items[i] == NULL)
3523 continue;
3525 m_items[i]->DestroyForPlayer( target );
3527 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3529 if(m_items[i] == NULL)
3530 continue;
3532 m_items[i]->DestroyForPlayer( target );
3537 bool Player::HasSpell(uint32 spell) const
3539 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3540 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3541 !itr->second->disabled);
3544 bool Player::HasActiveSpell(uint32 spell) const
3546 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3547 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3548 itr->second->active && !itr->second->disabled);
3551 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3553 if (!trainer_spell)
3554 return TRAINER_SPELL_RED;
3556 if (!trainer_spell->learnedSpell)
3557 return TRAINER_SPELL_RED;
3559 // known spell
3560 if(HasSpell(trainer_spell->learnedSpell))
3561 return TRAINER_SPELL_GRAY;
3563 // check race/class requirement
3564 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3565 return TRAINER_SPELL_RED;
3567 // check level requirement
3568 if(getLevel() < trainer_spell->reqLevel)
3569 return TRAINER_SPELL_RED;
3571 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3573 // check prev.rank requirement
3574 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3575 return TRAINER_SPELL_RED;
3577 // check additional spell requirement
3578 if(spell_chain->req && !HasSpell(spell_chain->req))
3579 return TRAINER_SPELL_RED;
3582 // check skill requirement
3583 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3584 return TRAINER_SPELL_RED;
3586 // exist, already checked at loading
3587 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3589 // secondary prof. or not prof. spell
3590 uint32 skill = spell->EffectMiscValue[1];
3592 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3593 return TRAINER_SPELL_GREEN;
3595 // check primary prof. limit
3596 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3597 return TRAINER_SPELL_RED;
3599 return TRAINER_SPELL_GREEN;
3602 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3604 uint32 guid = GUID_LOPART(playerguid);
3606 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3607 // bones will be deleted by corpse/bones deleting thread shortly
3608 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3610 // remove from guild
3611 uint32 guildId = GetGuildIdFromDB(playerguid);
3612 if(guildId != 0)
3614 Guild* guild = objmgr.GetGuildById(guildId);
3615 if(guild)
3616 guild->DelMember(guid);
3619 // remove from arena teams
3620 LeaveAllArenaTeams(playerguid);
3622 // the player was uninvited already on logout so just remove from group
3623 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3624 if(resultGroup)
3626 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3627 delete resultGroup;
3628 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3629 if(group)
3631 RemoveFromGroup(group, playerguid);
3635 // remove signs from petitions (also remove petitions if owner);
3636 RemovePetitionsAndSigns(playerguid, 10);
3638 // return back all mails with COD and Item 0 1 2 3 4 5 6
3639 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3640 if(resultMail)
3644 Field *fields = resultMail->Fetch();
3646 uint32 mail_id = fields[0].GetUInt32();
3647 uint16 mailTemplateId= fields[1].GetUInt16();
3648 uint32 sender = fields[2].GetUInt32();
3649 std::string subject = fields[3].GetCppString();
3650 uint32 itemTextId = fields[4].GetUInt32();
3651 uint32 money = fields[5].GetUInt32();
3652 bool has_items = fields[6].GetBool();
3654 //we can return mail now
3655 //so firstly delete the old one
3656 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3658 MailItemsInfo mi;
3659 if(has_items)
3661 // data needs to be at first place for Item::LoadFromDB
3662 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
3663 if(resultItems)
3667 Field *fields2 = resultItems->Fetch();
3669 uint32 item_guidlow = fields2[1].GetUInt32();
3670 uint32 item_template = fields2[2].GetUInt32();
3672 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3673 if(!itemProto)
3675 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3676 continue;
3679 Item *pItem = NewItemOrBag(itemProto);
3680 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3682 pItem->FSetState(ITEM_REMOVED);
3683 pItem->SaveToDB(); // it also deletes item object !
3684 continue;
3687 mi.AddItem(item_guidlow, item_template, pItem);
3689 while (resultItems->NextRow());
3691 delete resultItems;
3695 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3697 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3699 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3701 while (resultMail->NextRow());
3703 delete resultMail;
3706 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3707 // Get guids of character's pets, will deleted in transaction
3708 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3710 // NOW we can finally clear other DB data related to character
3711 CharacterDatabase.BeginTransaction();
3712 if (resultPets)
3716 Field *fields3 = resultPets->Fetch();
3717 uint32 petguidlow = fields3[0].GetUInt32();
3718 Pet::DeleteFromDB(petguidlow);
3719 } while (resultPets->NextRow());
3720 delete resultPets;
3723 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3724 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3725 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3726 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3727 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3728 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3729 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3730 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3731 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3732 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3733 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3734 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3735 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3736 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3737 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3738 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3739 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3740 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3741 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3742 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3743 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3744 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3745 CharacterDatabase.CommitTransaction();
3747 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3748 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3751 void Player::SetMovement(PlayerMovementType pType)
3753 WorldPacket data;
3754 switch(pType)
3756 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3757 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3758 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3759 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3760 default:
3761 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3762 return;
3764 data.append(GetPackGUID());
3765 data << uint32(0);
3766 GetSession()->SendPacket( &data );
3769 /* Preconditions:
3770 - a resurrectable corpse must not be loaded for the player (only bones)
3771 - the player must be in world
3773 void Player::BuildPlayerRepop()
3775 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3776 data.append(GetPackGUID());
3777 GetSession()->SendPacket(&data);
3779 if(getRace() == RACE_NIGHTELF)
3780 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)
3781 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3783 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3784 // there must be SMSG.STOP_MIRROR_TIMER
3785 // there we must send 888 opcode
3787 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3788 if(GetCorpse())
3790 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3791 assert(false);
3794 // create a corpse and place it at the player's location
3795 CreateCorpse();
3796 Corpse *corpse = GetCorpse();
3797 if(!corpse)
3799 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3800 return;
3802 GetMap()->Add(corpse);
3804 // convert player body to ghost
3805 SetHealth( 1 );
3807 SetMovement(MOVE_WATER_WALK);
3808 if(!GetSession()->isLogingOut())
3809 SetMovement(MOVE_UNROOT);
3811 // BG - remove insignia related
3812 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3814 SendCorpseReclaimDelay();
3816 // to prevent cheating
3817 corpse->ResetGhostTime();
3819 StopMirrorTimers(); //disable timers(bars)
3821 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3823 // set and clear other
3824 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3827 void Player::SendDelayResponse(const uint32 ml_seconds)
3829 //FIXME: is this delay time arg really need? 50msec by default in code
3830 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3831 data << (uint32)time(NULL);
3832 data << (uint32)0;
3833 GetSession()->SendPacket( &data );
3836 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3838 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3839 data << uint32(-1);
3840 data << float(0);
3841 data << float(0);
3842 data << float(0);
3843 GetSession()->SendPacket(&data);
3845 // speed change, land walk
3847 // remove death flag + set aura
3848 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3849 if(getRace() == RACE_NIGHTELF)
3850 RemoveAurasDueToSpell(20584); // speed bonuses
3851 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3853 setDeathState(ALIVE);
3855 SetMovement(MOVE_LAND_WALK);
3856 SetMovement(MOVE_UNROOT);
3858 m_deathTimer = 0;
3860 // set health/powers (0- will be set in caller)
3861 if(restore_percent>0.0f)
3863 SetHealth(uint32(GetMaxHealth()*restore_percent));
3864 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3865 SetPower(POWER_RAGE, 0);
3866 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3869 // update visibility
3870 ObjectAccessor::UpdateVisibilityForPlayer(this);
3872 // some items limited to specific map
3873 DestroyZoneLimitedItem( true, GetZoneId());
3875 if(!applySickness)
3876 return;
3878 //Characters from level 1-10 are not affected by resurrection sickness.
3879 //Characters from level 11-19 will suffer from one minute of sickness
3880 //for each level they are above 10.
3881 //Characters level 20 and up suffer from ten minutes of sickness.
3882 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3884 if(int32(getLevel()) >= startLevel)
3886 // set resurrection sickness
3887 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3889 // not full duration
3890 if(int32(getLevel()) < startLevel+9)
3892 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3894 for(int i =0; i < 3; ++i)
3896 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3898 Aur->SetAuraDuration(delta*1000);
3899 Aur->SendAuraUpdate(false);
3906 void Player::KillPlayer()
3908 SetMovement(MOVE_ROOT);
3910 StopMirrorTimers(); //disable timers(bars)
3912 setDeathState(CORPSE);
3913 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3915 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3916 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3918 // 6 minutes until repop at graveyard
3919 m_deathTimer = 6*MINUTE*1000;
3921 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3923 // don't create corpse at this moment, player might be falling
3925 // update visibility
3926 ObjectAccessor::UpdateObjectVisibility(this);
3929 void Player::CreateCorpse()
3931 // prevent existence 2 corpse for player
3932 SpawnCorpseBones();
3934 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3936 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3937 SetPvPDeath(false);
3939 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
3941 delete corpse;
3942 return;
3945 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3946 _pb = GetUInt32Value(PLAYER_BYTES);
3947 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3949 uint8 race = (uint8)(_uf);
3950 uint8 skin = (uint8)(_pb);
3951 uint8 face = (uint8)(_pb >> 8);
3952 uint8 hairstyle = (uint8)(_pb >> 16);
3953 uint8 haircolor = (uint8)(_pb >> 24);
3954 uint8 facialhair = (uint8)(_pb2);
3956 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3957 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3959 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3960 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3962 uint32 flags = CORPSE_FLAG_UNK2;
3963 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3964 flags |= CORPSE_FLAG_HIDE_HELM;
3965 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3966 flags |= CORPSE_FLAG_HIDE_CLOAK;
3967 if(InBattleGround())
3968 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3969 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3971 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3973 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3975 uint32 iDisplayID;
3976 uint16 iIventoryType;
3977 uint32 _cfi;
3978 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3980 if(m_items[i])
3982 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3983 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3985 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3986 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3990 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3991 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3992 assert(entry);
3993 if(entry->map_type != MAP_BATTLEGROUND)
3994 corpse->SaveToDB();
3996 // register for player, but not show
3997 ObjectAccessor::Instance().AddCorpse(corpse);
4000 void Player::SpawnCorpseBones()
4002 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4003 SaveToDB(); // prevent loading as ghost without corpse
4006 Corpse* Player::GetCorpse() const
4008 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4011 void Player::DurabilityLossAll(double percent, bool inventory)
4013 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4014 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4015 DurabilityLoss(pItem,percent);
4017 if(inventory)
4019 // bags not have durability
4020 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4022 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4023 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4024 DurabilityLoss(pItem,percent);
4026 // keys not have durability
4027 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4029 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4030 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4031 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4032 if(Item* pItem = GetItemByPos( i, j ))
4033 DurabilityLoss(pItem,percent);
4037 void Player::DurabilityLoss(Item* item, double percent)
4039 if(!item )
4040 return;
4042 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4044 if(!pMaxDurability)
4045 return;
4047 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4049 if(pDurabilityLoss < 1 )
4050 pDurabilityLoss = 1;
4052 DurabilityPointsLoss(item,pDurabilityLoss);
4055 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4057 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4058 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4059 DurabilityPointsLoss(pItem,points);
4061 if(inventory)
4063 // bags not have durability
4064 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4066 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4067 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4068 DurabilityPointsLoss(pItem,points);
4070 // keys not have durability
4071 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4073 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4074 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4075 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4076 if(Item* pItem = GetItemByPos( i, j ))
4077 DurabilityPointsLoss(pItem,points);
4081 void Player::DurabilityPointsLoss(Item* item, int32 points)
4083 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4084 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4085 int32 pNewDurability = pOldDurability - points;
4087 if (pNewDurability < 0)
4088 pNewDurability = 0;
4089 else if (pNewDurability > pMaxDurability)
4090 pNewDurability = pMaxDurability;
4092 if (pOldDurability != pNewDurability)
4094 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4095 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4096 _ApplyItemMods(item,item->GetSlot(), false);
4098 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4100 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4101 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4102 _ApplyItemMods(item,item->GetSlot(), true);
4104 item->SetState(ITEM_CHANGED, this);
4108 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4110 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4111 DurabilityPointsLoss(pItem,1);
4114 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4116 uint32 TotalCost = 0;
4117 // equipped, backpack, bags itself
4118 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4119 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4121 // bank, buyback and keys not repaired
4123 // items in inventory bags
4124 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4125 for(int i = 0; i < MAX_BAG_SIZE; i++)
4126 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4127 return TotalCost;
4130 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4132 Item* item = GetItemByPos(pos);
4134 uint32 TotalCost = 0;
4135 if(!item)
4136 return TotalCost;
4138 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4139 if(!maxDurability)
4140 return TotalCost;
4142 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4144 if(cost)
4146 uint32 LostDurability = maxDurability - curDurability;
4147 if(LostDurability>0)
4149 ItemPrototype const *ditemProto = item->GetProto();
4151 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4152 if(!dcost)
4154 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4155 return TotalCost;
4158 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4159 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4160 if(!dQualitymodEntry)
4162 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4163 return TotalCost;
4166 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4167 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4169 costs = uint32(costs * discountMod);
4171 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4172 costs = 1;
4174 if (guildBank)
4176 if (GetGuildId()==0)
4178 DEBUG_LOG("You are not member of a guild");
4179 return TotalCost;
4182 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4183 if (!pGuild)
4184 return TotalCost;
4186 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4188 DEBUG_LOG("You do not have rights to withdraw for repairs");
4189 return TotalCost;
4192 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4194 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4195 return TotalCost;
4198 if (pGuild->GetGuildBankMoney() < costs)
4200 DEBUG_LOG("There is not enough money in bank");
4201 return TotalCost;
4204 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4205 TotalCost = costs;
4207 else if (GetMoney() < costs)
4209 DEBUG_LOG("You do not have enough money");
4210 return TotalCost;
4212 else
4213 ModifyMoney( -int32(costs) );
4217 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4218 item->SetState(ITEM_CHANGED, this);
4220 // reapply mods for total broken and repaired item if equipped
4221 if(IsEquipmentPos(pos) && !curDurability)
4222 _ApplyItemMods(item,pos & 255, true);
4223 return TotalCost;
4226 void Player::RepopAtGraveyard()
4228 // note: this can be called also when the player is alive
4229 // for example from WorldSession::HandleMovementOpcodes
4231 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4233 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4234 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4236 ResurrectPlayer(0.5f);
4237 SpawnCorpseBones();
4240 WorldSafeLocsEntry const *ClosestGrave = NULL;
4242 // Special handle for battleground maps
4243 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4245 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4246 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4247 else
4248 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4250 // stop countdown until repop
4251 m_deathTimer = 0;
4253 // if no grave found, stay at the current location
4254 // and don't show spirit healer location
4255 if(ClosestGrave)
4257 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4258 if(isDead()) // not send if alive, because it used in TeleportTo()
4260 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4261 data << ClosestGrave->map_id;
4262 data << ClosestGrave->x;
4263 data << ClosestGrave->y;
4264 data << ClosestGrave->z;
4265 GetSession()->SendPacket(&data);
4270 void Player::JoinedChannel(Channel *c)
4272 m_channels.push_back(c);
4275 void Player::LeftChannel(Channel *c)
4277 m_channels.remove(c);
4280 void Player::CleanupChannels()
4282 while(!m_channels.empty())
4284 Channel* ch = *m_channels.begin();
4285 m_channels.erase(m_channels.begin()); // remove from player's channel list
4286 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4287 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4288 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4291 sLog.outDebug("Player: channels cleaned up!");
4294 void Player::UpdateLocalChannels(uint32 newZone )
4296 if(m_channels.empty())
4297 return;
4299 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4300 if(!current_zone)
4301 return;
4303 ChannelMgr* cMgr = channelMgr(GetTeam());
4304 if(!cMgr)
4305 return;
4307 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4309 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4311 next = i; ++next;
4313 // skip non built-in channels
4314 if(!(*i)->IsConstant())
4315 continue;
4317 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4318 if(!ch)
4319 continue;
4321 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4322 continue;
4324 // new channel
4325 char new_channel_name_buf[100];
4326 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4327 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4329 if((*i)!=new_channel)
4331 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4333 // leave old channel
4334 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4335 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4336 LeftChannel(*i); // remove from player's channel list
4337 cMgr->LeftChannel(name); // delete if empty
4340 sLog.outDebug("Player: channels cleaned up!");
4343 void Player::LeaveLFGChannel()
4345 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4347 if((*i)->IsLFG())
4349 (*i)->Leave(GetGUID());
4350 break;
4355 void Player::UpdateDefense()
4357 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4359 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4361 // update dependent from defense skill part
4362 UpdateDefenseBonusesMod();
4366 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4368 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4370 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4371 return;
4374 float val = 1.0f;
4376 switch(modType)
4378 case FLAT_MOD:
4379 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4380 break;
4381 case PCT_MOD:
4382 if(amount <= -100.0f)
4383 amount = -200.0f;
4385 val = (100.0f + amount) / 100.0f;
4386 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4387 break;
4390 if(!CanModifyStats())
4391 return;
4393 switch(modGroup)
4395 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4396 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4397 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4398 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4399 default: break;
4403 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4405 if(modGroup >= BASEMOD_END || modType > MOD_END)
4407 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4408 return 0.0f;
4411 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4412 return 0.0f;
4414 return m_auraBaseMod[modGroup][modType];
4417 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4419 if(modGroup >= BASEMOD_END)
4421 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4422 return 0.0f;
4425 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4426 return 0.0f;
4428 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4431 uint32 Player::GetShieldBlockValue() const
4433 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4435 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4437 value = (value < 0) ? 0 : value;
4439 return uint32(value);
4442 float Player::GetMeleeCritFromAgility()
4444 uint32 level = getLevel();
4445 uint32 pclass = getClass();
4447 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4449 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4450 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4451 if (critBase==NULL || critRatio==NULL)
4452 return 0.0f;
4454 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4455 return crit*100.0f;
4458 float Player::GetDodgeFromAgility()
4460 // Table for base dodge values
4461 float dodge_base[MAX_CLASSES] = {
4462 0.0075f, // Warrior
4463 0.00652f, // Paladin
4464 -0.0545f, // Hunter
4465 -0.0059f, // Rogue
4466 0.03183f, // Priest
4467 0.0114f, // DK
4468 0.0167f, // Shaman
4469 0.034575f, // Mage
4470 0.02011f, // Warlock
4471 0.0f, // ??
4472 -0.0187f // Druid
4474 // Crit/agility to dodge/agility coefficient multipliers
4475 float crit_to_dodge[MAX_CLASSES] = {
4476 1.1f, // Warrior
4477 1.0f, // Paladin
4478 1.6f, // Hunter
4479 2.0f, // Rogue
4480 1.0f, // Priest
4481 1.0f, // DK?
4482 1.0f, // Shaman
4483 1.0f, // Mage
4484 1.0f, // Warlock
4485 0.0f, // ??
4486 1.7f // Druid
4489 uint32 level = getLevel();
4490 uint32 pclass = getClass();
4492 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4494 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4495 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4496 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4497 return 0.0f;
4499 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4500 return dodge*100.0f;
4503 float Player::GetSpellCritFromIntellect()
4505 uint32 level = getLevel();
4506 uint32 pclass = getClass();
4508 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4510 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4511 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4512 if (critBase==NULL || critRatio==NULL)
4513 return 0.0f;
4515 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4516 return crit*100.0f;
4519 float Player::GetRatingCoefficient(CombatRating cr) const
4521 uint32 level = getLevel();
4523 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4525 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4526 if (Rating == NULL)
4527 return 1.0f; // By default use minimum coefficient (not must be called)
4529 return Rating->ratio;
4532 float Player::GetRatingBonusValue(CombatRating cr) const
4534 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4537 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4539 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4540 if (melee>25.0f) melee = 25.0f;
4541 return uint32 (melee * damage /100.0f);
4544 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4546 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4547 if (ranged>25.0f) ranged=25.0f;
4548 return uint32 (ranged * damage /100.0f);
4551 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4553 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4554 // In wow script resilience limited to 25%
4555 if (spell>25.0f)
4556 spell = 25.0f;
4557 return uint32 (spell * damage / 100.0f);
4560 uint32 Player::GetDotDamageReduction(uint32 damage) const
4562 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4563 // Dot resilience not limited (limit it by 100%)
4564 if (spellDot > 100.0f)
4565 spellDot = 100.0f;
4566 return uint32 (spellDot * damage / 100.0f);
4569 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4571 switch (attType)
4573 case BASE_ATTACK:
4574 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4575 case OFF_ATTACK:
4576 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4577 default:
4578 break;
4580 return 0.0f;
4583 float Player::OCTRegenHPPerSpirit()
4585 uint32 level = getLevel();
4586 uint32 pclass = getClass();
4588 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4590 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4591 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4592 if (baseRatio==NULL || moreRatio==NULL)
4593 return 0.0f;
4595 // Formula from PaperDollFrame script
4596 float spirit = GetStat(STAT_SPIRIT);
4597 float baseSpirit = spirit;
4598 if (baseSpirit>50) baseSpirit = 50;
4599 float moreSpirit = spirit - baseSpirit;
4600 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4601 return regen;
4604 float Player::OCTRegenMPPerSpirit()
4606 uint32 level = getLevel();
4607 uint32 pclass = getClass();
4609 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4611 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4613 if (moreRatio==NULL)
4614 return 0.0f;
4616 // Formula get from PaperDollFrame script
4617 float spirit = GetStat(STAT_SPIRIT);
4618 float regen = spirit * moreRatio->ratio;
4619 return regen;
4622 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4624 m_baseRatingValue[cr]+=(apply ? value : -value);
4626 int32 amount = uint32(m_baseRatingValue[cr]);
4627 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4628 // stat used stored in miscValueB for this aura
4629 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4630 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4631 if ((*i)->GetMiscValue() & (1<<cr))
4632 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4633 if (amount < 0)
4634 amount = 0;
4635 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4637 float RatingCoeffecient = GetRatingCoefficient(cr);
4638 float RatingChange = 0.0f;
4640 bool affectStats = CanModifyStats();
4642 switch (cr)
4644 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4645 case CR_DEFENSE_SKILL:
4646 UpdateDefenseBonusesMod();
4647 break;
4648 case CR_DODGE:
4649 UpdateDodgePercentage();
4650 break;
4651 case CR_PARRY:
4652 UpdateParryPercentage();
4653 break;
4654 case CR_BLOCK:
4655 UpdateBlockPercentage();
4656 break;
4657 case CR_HIT_MELEE:
4658 UpdateMeleeHitChances();
4659 break;
4660 case CR_HIT_RANGED:
4661 UpdateRangedHitChances();
4662 break;
4663 case CR_HIT_SPELL:
4664 UpdateSpellHitChances();
4665 break;
4666 case CR_CRIT_MELEE:
4667 if(affectStats)
4669 UpdateCritPercentage(BASE_ATTACK);
4670 UpdateCritPercentage(OFF_ATTACK);
4672 break;
4673 case CR_CRIT_RANGED:
4674 if(affectStats)
4675 UpdateCritPercentage(RANGED_ATTACK);
4676 break;
4677 case CR_CRIT_SPELL:
4678 if(affectStats)
4679 UpdateAllSpellCritChances();
4680 break;
4681 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4682 case CR_HIT_TAKEN_RANGED:
4683 break;
4684 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4685 break;
4686 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4687 case CR_CRIT_TAKEN_RANGED:
4688 break;
4689 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4690 break;
4691 case CR_HASTE_MELEE:
4692 RatingChange = value / RatingCoeffecient;
4693 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4694 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4695 break;
4696 case CR_HASTE_RANGED:
4697 RatingChange = value / RatingCoeffecient;
4698 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4699 break;
4700 case CR_HASTE_SPELL:
4701 RatingChange = value / RatingCoeffecient;
4702 ApplyCastTimePercentMod(RatingChange,apply);
4703 break;
4704 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4705 case CR_WEAPON_SKILL_OFFHAND:
4706 case CR_WEAPON_SKILL_RANGED:
4707 break;
4708 case CR_EXPERTISE:
4709 if(affectStats)
4711 UpdateExpertise(BASE_ATTACK);
4712 UpdateExpertise(OFF_ATTACK);
4714 break;
4718 void Player::SetRegularAttackTime()
4720 for(int i = 0; i < MAX_ATTACK; ++i)
4722 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4723 if(tmpitem && !tmpitem->IsBroken())
4725 ItemPrototype const *proto = tmpitem->GetProto();
4726 if(proto->Delay)
4727 SetAttackTime(WeaponAttackType(i), proto->Delay);
4728 else
4729 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4734 //skill+step, checking for max value
4735 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4737 if(!skill_id)
4738 return false;
4740 uint16 i=0;
4741 for (; i < PLAYER_MAX_SKILLS; i++)
4742 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4743 break;
4745 if(i>=PLAYER_MAX_SKILLS)
4746 return false;
4748 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4749 uint32 value = SKILL_VALUE(data);
4750 uint32 max = SKILL_MAX(data);
4752 if ((!max) || (!value) || (value >= max))
4753 return false;
4755 if (value*512 < max*urand(0,512))
4757 uint32 new_value = value+step;
4758 if(new_value > max)
4759 new_value = max;
4761 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4762 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4763 return true;
4766 return false;
4769 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4771 if ( SkillValue >= GrayLevel )
4772 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4773 if ( SkillValue >= GreenLevel )
4774 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4775 if ( SkillValue >= YellowLevel )
4776 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4777 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4780 bool Player::UpdateCraftSkill(uint32 spellid)
4782 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4784 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4785 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4787 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4789 if(_spell_idx->second->skillId)
4791 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4793 // Alchemy Discoveries here
4794 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4795 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4797 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4798 learnSpell(discoveredSpell,false);
4801 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4803 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4804 _spell_idx->second->max_value,
4805 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4806 _spell_idx->second->min_value),
4807 craft_skill_gain);
4810 return false;
4813 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4815 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4817 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4819 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4820 switch (SkillId)
4822 case SKILL_HERBALISM:
4823 case SKILL_LOCKPICKING:
4824 case SKILL_JEWELCRAFTING:
4825 case SKILL_INSCRIPTION:
4826 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4827 case SKILL_SKINNING:
4828 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4829 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4830 else
4831 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4832 case SKILL_MINING:
4833 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4834 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4835 else
4836 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4838 return false;
4841 bool Player::UpdateFishingSkill()
4843 sLog.outDebug("UpdateFishingSkill");
4845 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4847 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4849 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4851 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4854 // levels sync. with spell requirement for skill levels to learn
4855 // bonus abilities in sSkillLineAbilityStore
4856 // Used only to avoid scan DBC at each skill grow
4857 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4859 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4861 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4862 if ( !SkillId )
4863 return false;
4865 if(Chance <= 0) // speedup in 0 chance case
4867 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4868 return false;
4871 uint16 i=0;
4872 for (; i < PLAYER_MAX_SKILLS; i++)
4873 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4874 if ( i >= PLAYER_MAX_SKILLS )
4875 return false;
4877 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4878 uint16 SkillValue = SKILL_VALUE(data);
4879 uint16 MaxValue = SKILL_MAX(data);
4881 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4882 return false;
4884 int32 Roll = irand(1,1000);
4886 if ( Roll <= Chance )
4888 uint32 new_value = SkillValue+step;
4889 if(new_value > MaxValue)
4890 new_value = MaxValue;
4892 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4893 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4895 if((SkillValue < *bsl && new_value >= *bsl))
4897 learnSkillRewardedSpells( SkillId, new_value);
4898 break;
4901 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4902 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4903 return true;
4906 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4907 return false;
4910 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4912 // no skill gain in pvp
4913 Unit *pVictim = getVictim();
4914 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4915 return;
4917 if(IsInFeralForm())
4918 return; // always maximized SKILL_FERAL_COMBAT in fact
4920 if(m_form == FORM_TREE)
4921 return; // use weapon but not skill up
4923 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4925 switch(attType)
4927 case BASE_ATTACK:
4929 Item *tmpitem = GetWeaponForAttack(attType,true);
4931 if (!tmpitem)
4932 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4933 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4934 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4935 break;
4937 case OFF_ATTACK:
4938 case RANGED_ATTACK:
4940 Item *tmpitem = GetWeaponForAttack(attType,true);
4941 if (tmpitem)
4942 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4943 break;
4946 UpdateAllCritPercentages();
4949 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
4951 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4952 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4953 uint32 moblevel = pVictim->getLevelForTarget(this);
4954 if(moblevel < greylevel)
4955 return;
4957 if (moblevel > plevel + 5)
4958 moblevel = plevel + 5;
4960 uint32 lvldif = moblevel - greylevel;
4961 if(lvldif < 3)
4962 lvldif = 3;
4964 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4965 if(skilldif <= 0)
4966 return;
4968 float chance = float(3 * lvldif * skilldif) / plevel;
4969 if(!defence)
4971 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4972 chance *= 0.1f * GetStat(STAT_INTELLECT);
4975 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4977 if(roll_chance_f(chance))
4979 if(defence)
4980 UpdateDefense();
4981 else
4982 UpdateWeaponSkill(attType);
4984 else
4985 return;
4988 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4990 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4991 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4993 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4994 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4995 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4997 if(talent) // permanent bonus stored in high part
4998 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4999 else // temporary/item bonus stored in low part
5000 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5001 return;
5005 void Player::UpdateSkillsForLevel()
5007 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5008 uint32 maxSkill = GetMaxSkillValueForLevel();
5010 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5012 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5013 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5015 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5017 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5018 if(!pSkill)
5019 continue;
5021 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5022 continue;
5024 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5025 uint32 max = SKILL_MAX(data);
5026 uint32 val = SKILL_VALUE(data);
5028 /// update only level dependent max skill values
5029 if(max!=1)
5031 /// miximize skill always
5032 if(alwaysMaxSkill)
5033 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5034 /// update max skill value if current max skill not maximized
5035 else if(max != maxconfskill)
5036 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5041 void Player::UpdateSkillsToMaxSkillsForLevel()
5043 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5044 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5046 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5047 if( IsProfessionOrRidingSkill(pskill))
5048 continue;
5049 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5051 uint32 max = SKILL_MAX(data);
5053 if(max > 1)
5054 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5056 if(pskill == SKILL_DEFENSE)
5057 UpdateDefenseBonusesMod();
5061 // This functions sets a skill line value (and adds if doesn't exist yet)
5062 // To "remove" a skill line, set it's values to zero
5063 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5065 if(!id)
5066 return;
5068 uint16 i=0;
5069 for (; i < PLAYER_MAX_SKILLS; i++)
5070 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5072 if(i<PLAYER_MAX_SKILLS) //has skill
5074 if(currVal)
5076 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5077 learnSkillRewardedSpells(id, currVal);
5078 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5080 else //remove
5082 // clear skill fields
5083 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5084 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5085 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5087 // remove all spells that related to this skill
5088 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5089 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5090 if (pAbility->skillId==id)
5091 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5094 else if(currVal) //add
5096 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5097 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5099 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5100 if(!pSkill)
5102 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5103 return;
5105 // enable unlearn button for primary professions only
5106 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5107 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5108 else
5109 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5110 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5111 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5113 // apply skill bonuses
5114 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5116 // temporary bonuses
5117 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5118 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5119 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5120 (*i)->ApplyModifier(true);
5122 // permanent bonuses
5123 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5124 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5125 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5126 (*i)->ApplyModifier(true);
5128 // Learn all spells for skill
5129 learnSkillRewardedSpells(id, currVal);
5130 return;
5135 bool Player::HasSkill(uint32 skill) const
5137 if(!skill)return false;
5138 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5140 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5142 return true;
5145 return false;
5148 uint16 Player::GetSkillValue(uint32 skill) const
5150 if(!skill)
5151 return 0;
5153 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5155 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5157 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5159 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5160 result += SKILL_TEMP_BONUS(bonus);
5161 result += SKILL_PERM_BONUS(bonus);
5162 return result < 0 ? 0 : result;
5165 return 0;
5168 uint16 Player::GetMaxSkillValue(uint32 skill) const
5170 if(!skill)return 0;
5171 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5173 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5175 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5177 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5178 result += SKILL_TEMP_BONUS(bonus);
5179 result += SKILL_PERM_BONUS(bonus);
5180 return result < 0 ? 0 : result;
5183 return 0;
5186 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5188 if(!skill)return 0;
5189 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5191 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5193 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5196 return 0;
5199 uint16 Player::GetBaseSkillValue(uint32 skill) const
5201 if(!skill)return 0;
5202 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5204 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5206 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5207 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5208 return result < 0 ? 0 : result;
5211 return 0;
5214 uint16 Player::GetPureSkillValue(uint32 skill) const
5216 if(!skill)return 0;
5217 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5219 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5221 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5224 return 0;
5227 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5229 if(!skill)
5230 return 0;
5232 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5234 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5236 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5240 return 0;
5243 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5245 if(!skill)
5246 return 0;
5248 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5250 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5252 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5256 return 0;
5259 void Player::SendInitialActionButtons()
5261 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5263 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5264 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5266 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5267 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5269 data << uint16(itr->second.action);
5270 data << uint8(itr->second.misc);
5271 data << uint8(itr->second.type);
5273 else
5275 data << uint32(0);
5279 GetSession()->SendPacket( &data );
5280 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5283 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5285 if(button >= MAX_ACTION_BUTTONS)
5287 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5288 return;
5291 // check cheating with adding non-known spells to action bar
5292 if(type==ACTION_BUTTON_SPELL)
5294 if(!sSpellStore.LookupEntry(action))
5296 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5297 return;
5300 if(!HasSpell(action))
5302 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5303 return;
5307 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5309 if (buttonItr==m_actionButtons.end())
5310 { // just add new button
5311 m_actionButtons[button] = ActionButton(action,type,misc);
5313 else
5314 { // change state of current button
5315 ActionButtonUpdateState uState = buttonItr->second.uState;
5316 buttonItr->second = ActionButton(action,type,misc);
5317 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5320 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5323 void Player::removeActionButton(uint8 button)
5325 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5326 if (buttonItr==m_actionButtons.end())
5327 return;
5329 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5330 m_actionButtons.erase(buttonItr); // new and not saved
5331 else
5332 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5334 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5337 void Player::SetDontMove(bool dontMove)
5339 m_dontMove = dontMove;
5342 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5344 // prevent crash when a bad coord is sent by the client
5345 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5347 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5348 return false;
5351 Map *m = GetMap();
5353 const float old_x = GetPositionX();
5354 const float old_y = GetPositionY();
5355 const float old_z = GetPositionZ();
5356 const float old_r = GetOrientation();
5358 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5360 if (teleport || old_x != x || old_y != y || old_z != z)
5361 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5362 else
5363 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5365 // move and update visible state if need
5366 m->PlayerRelocation(this, x, y, z, orientation);
5368 // reread after Map::Relocation
5369 m = GetMap();
5370 x = GetPositionX();
5371 y = GetPositionY();
5372 z = GetPositionZ();
5374 // group update
5375 if(GetGroup() && (old_x != x || old_y != y))
5376 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5379 // code block for underwater state update
5380 UpdateUnderwaterState(m, x, y, z);
5382 CheckExploreSystem();
5384 return true;
5387 void Player::SaveRecallPosition()
5389 m_recallMap = GetMapId();
5390 m_recallX = GetPositionX();
5391 m_recallY = GetPositionY();
5392 m_recallZ = GetPositionZ();
5393 m_recallO = GetOrientation();
5396 void Player::SendMessageToSet(WorldPacket *data, bool self)
5398 GetMap()->MessageBroadcast(this, data, self);
5401 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5403 GetMap()->MessageDistBroadcast(this, data, dist, self);
5406 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5408 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5411 void Player::SendDirectMessage(WorldPacket *data)
5413 GetSession()->SendPacket(data);
5416 void Player::CheckExploreSystem()
5418 if (!isAlive())
5419 return;
5421 if (isInFlight())
5422 return;
5424 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5425 if(areaFlag==0xffff)
5426 return;
5427 int offset = areaFlag / 32;
5429 if(offset >= 128)
5431 sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5432 return;
5435 uint32 val = (uint32)(1 << (areaFlag % 32));
5436 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5438 if( !(currFields & val) )
5440 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5442 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5444 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5445 if(!p)
5447 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5449 else if(p->area_level > 0)
5451 uint32 area = p->ID;
5452 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5454 SendExplorationExperience(area,0);
5456 else
5458 int32 diff = int32(getLevel()) - p->area_level;
5459 uint32 XP = 0;
5460 if (diff < -5)
5462 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5464 else if (diff > 5)
5466 int32 exploration_percent = (100-((diff-5)*5));
5467 if (exploration_percent > 100)
5468 exploration_percent = 100;
5469 else if (exploration_percent < 0)
5470 exploration_percent = 0;
5472 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5474 else
5476 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5479 GiveXP( XP, NULL );
5480 SendExplorationExperience(area,XP);
5482 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5487 uint32 Player::TeamForRace(uint8 race)
5489 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5490 if(!rEntry)
5492 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5493 return ALLIANCE;
5496 switch(rEntry->TeamID)
5498 case 7: return ALLIANCE;
5499 case 1: return HORDE;
5502 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5503 return ALLIANCE;
5506 uint32 Player::getFactionForRace(uint8 race)
5508 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5509 if(!rEntry)
5511 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5512 return 0;
5515 return rEntry->FactionID;
5518 void Player::setFactionForRace(uint8 race)
5520 m_team = TeamForRace(race);
5521 setFaction( getFactionForRace(race) );
5524 void Player::UpdateReputation() const
5526 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5528 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5530 SendFactionState(&(itr->second));
5534 void Player::SendFactionState(FactionState const* faction) const
5536 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5538 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5539 data << (float) 0; // unk 2.4.0
5540 data << (uint8) 0; // wotlk 8634
5541 data << (uint32) 1; // count
5542 // for
5543 data << (uint32) faction->ReputationListID;
5544 data << (uint32) faction->Standing;
5545 // end for
5546 GetSession()->SendPacket(&data);
5550 void Player::SendInitialReputations()
5552 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5553 data << uint32 (0x00000080);
5555 RepListID a = 0;
5557 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5559 // fill in absent fields
5560 for (; a != itr->first; a++)
5562 data << uint8 (0x00);
5563 data << uint32 (0x00000000);
5566 // fill in encountered data
5567 data << uint8 (itr->second.Flags);
5568 data << uint32 (itr->second.Standing);
5570 ++a;
5573 // fill in absent fields
5574 for (; a != 128; a++)
5576 data << uint8 (0x00);
5577 data << uint32 (0x00000000);
5580 GetSession()->SendPacket(&data);
5583 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5585 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5586 if (itr != m_factions.end())
5587 return &itr->second;
5589 return NULL;
5592 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5594 // not allow declare war to own faction
5595 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5596 return;
5598 // already set
5599 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5600 return;
5602 if( atWar )
5603 faction->Flags |= FACTION_FLAG_AT_WAR;
5604 else
5605 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5607 faction->Changed = true;
5610 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5612 // always invisible or hidden faction can't be inactive
5613 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5614 return;
5616 // already set
5617 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5618 return;
5620 if(inactive)
5621 faction->Flags |= FACTION_FLAG_INACTIVE;
5622 else
5623 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5625 faction->Changed = true;
5628 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5630 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5632 if(!factionTemplateEntry)
5633 return;
5635 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5638 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5640 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5641 if(!factionEntry)
5642 return;
5644 if(factionEntry->reputationListID < 0)
5645 return;
5647 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5648 if (itr == m_factions.end())
5649 return;
5651 SetFactionVisible(&itr->second);
5654 void Player::SetFactionVisible(FactionState* faction)
5656 // always invisible or hidden faction can't be make visible
5657 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5658 return;
5660 // already set
5661 if(faction->Flags & FACTION_FLAG_VISIBLE)
5662 return;
5664 faction->Flags |= FACTION_FLAG_VISIBLE;
5665 faction->Changed = true;
5667 if(!m_session->PlayerLoading())
5669 // make faction visible in reputation list at client
5670 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5671 data << faction->ReputationListID;
5672 GetSession()->SendPacket(&data);
5676 void Player::SetInitialFactions()
5678 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5680 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5682 if( factionEntry && (factionEntry->reputationListID >= 0))
5684 FactionState newFaction;
5685 newFaction.ID = factionEntry->ID;
5686 newFaction.ReputationListID = factionEntry->reputationListID;
5687 newFaction.Standing = 0;
5688 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5689 newFaction.Changed = true;
5691 m_factions[newFaction.ReputationListID] = newFaction;
5696 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5698 if (!factionEntry)
5699 return 0;
5701 uint32 raceMask = getRaceMask();
5702 uint32 classMask = getClassMask();
5703 for (int i=0; i < 4; i++)
5705 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5706 (factionEntry->BaseRepClassMask[i]==0 ||
5707 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5708 return factionEntry->ReputationFlags[i];
5710 return 0;
5713 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5715 if (!factionEntry)
5716 return 0;
5718 uint32 raceMask = getRaceMask();
5719 uint32 classMask = getClassMask();
5720 for (int i=0; i < 4; i++)
5722 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5723 (factionEntry->BaseRepClassMask[i]==0 ||
5724 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5725 return factionEntry->BaseRepValue[i];
5728 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5729 return 0;
5732 int32 Player::GetReputation(uint32 faction_id) const
5734 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5736 if (!factionEntry)
5738 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5739 return 0;
5742 return GetReputation(factionEntry);
5745 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5747 // Faction without recorded reputation. Just ignore.
5748 if(!factionEntry)
5749 return 0;
5751 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5752 if (itr != m_factions.end())
5753 return GetBaseReputation(factionEntry) + itr->second.Standing;
5755 return 0;
5758 ReputationRank Player::GetReputationRank(uint32 faction) const
5760 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5761 if(!factionEntry)
5762 return MIN_REPUTATION_RANK;
5764 return GetReputationRank(factionEntry);
5767 ReputationRank Player::ReputationToRank(int32 standing) const
5769 int32 Limit = Reputation_Cap + 1;
5770 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5772 Limit -= ReputationRank_Length[i];
5773 if (standing >= Limit )
5774 return ReputationRank(i);
5776 return MIN_REPUTATION_RANK;
5779 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5781 int32 Reputation = GetReputation(factionEntry);
5782 return ReputationToRank(Reputation);
5785 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5787 int32 Reputation = GetBaseReputation(factionEntry);
5788 return ReputationToRank(Reputation);
5791 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5793 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5795 if(!factionTemplateEntry)
5797 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5798 return false;
5801 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5803 // Faction without recorded reputation. Just ignore.
5804 if(!factionEntry)
5805 return false;
5807 return ModifyFactionReputation(factionEntry, DeltaReputation);
5810 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5812 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5813 if (flist)
5815 bool res = false;
5816 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5818 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5819 if(factionEntryCalc)
5820 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5822 return res;
5824 else
5825 return ModifyOneFactionReputation(factionEntry, standing);
5828 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5830 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5831 if (itr != m_factions.end())
5833 int32 BaseRep = GetBaseReputation(factionEntry);
5834 int32 new_rep = BaseRep + itr->second.Standing + standing;
5836 if (new_rep > Reputation_Cap)
5837 new_rep = Reputation_Cap;
5838 else
5839 if (new_rep < Reputation_Bottom)
5840 new_rep = Reputation_Bottom;
5842 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5843 SetFactionAtWar(&itr->second,true);
5845 itr->second.Standing = new_rep - BaseRep;
5846 itr->second.Changed = true;
5848 SetFactionVisible(&itr->second);
5850 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
5852 if(uint32 questid = GetQuestSlotQuestId(i))
5854 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5855 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5857 QuestStatusData& q_status = mQuestStatus[questid];
5858 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5860 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5861 if ( CanCompleteQuest( questid ) )
5862 CompleteQuest( questid );
5864 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5866 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5867 IncompleteQuest( questid );
5872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5873 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5874 SendFactionState(&(itr->second));
5876 return true;
5878 return false;
5881 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5883 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5885 if(!factionTemplateEntry)
5887 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5888 return false;
5891 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5893 // Faction without recorded reputation. Just ignore.
5894 if(!factionEntry)
5895 return false;
5897 return SetFactionReputation(factionEntry, standing);
5900 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5902 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5903 if (flist)
5905 bool res = false;
5906 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5908 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5909 if(factionEntryCalc)
5910 res = SetOneFactionReputation(factionEntryCalc, standing);
5912 return res;
5914 else
5915 return SetOneFactionReputation(factionEntry, standing);
5918 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5920 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5921 if (itr != m_factions.end())
5923 if (standing > Reputation_Cap)
5924 standing = Reputation_Cap;
5925 else
5926 if (standing < Reputation_Bottom)
5927 standing = Reputation_Bottom;
5929 int32 BaseRep = GetBaseReputation(factionEntry);
5930 itr->second.Standing = standing - BaseRep;
5931 itr->second.Changed = true;
5933 SetFactionVisible(&itr->second);
5935 if(ReputationToRank(standing) <= REP_HOSTILE)
5936 SetFactionAtWar(&itr->second,true);
5938 SendFactionState(&(itr->second));
5939 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5940 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5941 return true;
5943 return false;
5946 //Calculate total reputation percent player gain with quest/creature level
5947 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5949 // for grey creature kill received 20%, in other case 100.
5950 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5952 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5954 percent += rep > 0 ? repMod : -repMod;
5956 if(percent <=0)
5957 return 0;
5959 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5962 //Calculates how many reputation points player gains in victim's enemy factions
5963 void Player::RewardReputation(Unit *pVictim, float rate)
5965 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5966 return;
5968 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5970 if(!Rep)
5971 return;
5973 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5975 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5976 donerep1 = int32(donerep1*rate);
5977 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5978 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5979 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5980 ModifyFactionReputation(factionEntry1, donerep1);
5982 // Wiki: Team factions value divided by 2
5983 if(Rep->is_teamaward1)
5985 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5986 if(team1_factionEntry)
5987 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5991 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5993 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5994 donerep2 = int32(donerep2*rate);
5995 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5996 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5997 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5998 ModifyFactionReputation(factionEntry2, donerep2);
6000 // Wiki: Team factions value divided by 2
6001 if(Rep->is_teamaward2)
6003 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6004 if(team2_factionEntry)
6005 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
6010 //Calculate how many reputation points player gain with the quest
6011 void Player::RewardReputation(Quest const *pQuest)
6013 // quest reputation reward/loss
6014 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6016 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
6018 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
6019 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6020 if(factionEntry)
6021 ModifyFactionReputation(factionEntry, rep);
6025 // TODO: implement reputation spillover
6028 void Player::UpdateArenaFields(void)
6030 /* arena calcs go here */
6033 void Player::UpdateHonorFields()
6035 /// called when rewarding honor and at each save
6036 uint64 now = time(NULL);
6037 uint64 today = uint64(time(NULL) / DAY) * DAY;
6039 if(m_lastHonorUpdateTime < today)
6041 uint64 yesterday = today - DAY;
6043 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6045 // update yesterday's contribution
6046 if(m_lastHonorUpdateTime >= yesterday )
6048 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6050 // this is the first update today, reset today's contribution
6051 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6052 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6054 else
6056 // no honor/kills yesterday or today, reset
6057 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6058 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6062 m_lastHonorUpdateTime = now;
6065 ///Calculate the amount of honor gained based on the victim
6066 ///and the size of the group for which the honor is divided
6067 ///An exact honor value can also be given (overriding the calcs)
6068 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6070 // do not reward honor in arenas, but enable onkill spellproc
6071 if(InArena())
6073 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6074 return false;
6076 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6077 return false;
6079 return true;
6082 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6083 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6084 return false;
6086 uint64 victim_guid = 0;
6087 uint32 victim_rank = 0;
6089 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6090 UpdateHonorFields();
6092 if(honor <= 0)
6094 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6095 return false;
6097 victim_guid = uVictim->GetGUID();
6099 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6101 Player *pVictim = (Player *)uVictim;
6103 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6104 return false;
6106 float f = 1; //need for total kills (?? need more info)
6107 uint32 k_grey = 0;
6108 uint32 k_level = getLevel();
6109 uint32 v_level = pVictim->getLevel();
6112 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6113 // [0] Just name
6114 // [1..14] Alliance honor titles and player name
6115 // [15..28] Horde honor titles and player name
6116 // [29..38] Other title and player name
6117 // [39+] Nothing
6118 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6119 // Get Killer titles, CharTitlesEntry::bit_index
6120 // Ranks:
6121 // title[1..14] -> rank[5..18]
6122 // title[15..28] -> rank[5..18]
6123 // title[other] -> 0
6124 if (victim_title == 0)
6125 victim_guid = 0; // Don't show HK: <rank> message, only log.
6126 else if (victim_title < 15)
6127 victim_rank = victim_title + 4;
6128 else if (victim_title < 29)
6129 victim_rank = victim_title - 14 + 4;
6130 else
6131 victim_guid = 0; // Don't show HK: <rank> message, only log.
6134 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6136 if(v_level<=k_grey)
6137 return false;
6139 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6141 int32 v_rank =1; //need more info
6143 honor = ((f * diff_level * (190 + v_rank*10))/6);
6144 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6146 // count the number of playerkills in one day
6147 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6148 // and those in a lifetime
6149 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6151 else
6153 Creature *cVictim = (Creature *)uVictim;
6155 if (!cVictim->isRacialLeader())
6156 return false;
6158 honor = 100; // ??? need more info
6159 victim_rank = 19; // HK: Leader
6163 if (uVictim != NULL)
6165 honor *= sWorld.getRate(RATE_HONOR);
6167 if(groupsize > 1)
6168 honor /= groupsize;
6170 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6173 // honor - for show honor points in log
6174 // victim_guid - for show victim name in log
6175 // victim_rank [1..4] HK: <dishonored rank>
6176 // victim_rank [5..19] HK: <alliance\horde rank>
6177 // victim_rank [0,20+] HK: <>
6178 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6179 data << (uint32) honor;
6180 data << (uint64) victim_guid;
6181 data << (uint32) victim_rank;
6183 GetSession()->SendPacket(&data);
6185 // add honor points
6186 ModifyHonorPoints(int32(honor));
6188 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6189 return true;
6192 void Player::ModifyHonorPoints( int32 value )
6194 if(value < 0)
6196 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6197 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6198 else
6199 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6201 else
6202 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6205 void Player::ModifyArenaPoints( int32 value )
6207 if(value < 0)
6209 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6210 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6211 else
6212 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6214 else
6215 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6218 uint32 Player::GetGuildIdFromDB(uint64 guid)
6220 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6221 if(!result)
6222 return 0;
6224 uint32 id = result->Fetch()[0].GetUInt32();
6225 delete result;
6226 return id;
6229 uint32 Player::GetRankFromDB(uint64 guid)
6231 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6232 if( result )
6234 uint32 v = result->Fetch()[0].GetUInt32();
6235 delete result;
6236 return v;
6238 else
6239 return 0;
6242 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6244 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);
6245 if(!result)
6246 return 0;
6248 uint32 id = (*result)[0].GetUInt32();
6249 delete result;
6250 return id;
6253 uint32 Player::GetZoneIdFromDB(uint64 guid)
6255 uint32 guidLow = GUID_LOPART(guid);
6256 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6257 if (!result)
6258 return 0;
6259 Field* fields = result->Fetch();
6260 uint32 zone = fields[0].GetUInt32();
6261 delete result;
6263 if (!zone)
6265 // stored zone is zero, use generic and slow zone detection
6266 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6267 if( !result )
6268 return 0;
6269 fields = result->Fetch();
6270 uint32 map = fields[0].GetUInt32();
6271 float posx = fields[1].GetFloat();
6272 float posy = fields[2].GetFloat();
6273 float posz = fields[3].GetFloat();
6274 delete result;
6276 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6278 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6281 return zone;
6284 void Player::UpdateArea(uint32 newArea)
6286 // FFA_PVP flags are area and not zone id dependent
6287 // so apply them accordingly
6288 m_areaUpdateId = newArea;
6290 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6292 if(area && (area->flags & AREA_FLAG_ARENA))
6294 if(!isGameMaster())
6295 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6297 else
6299 // remove ffa flag only if not ffapvp realm
6300 // removal in sanctuaries and capitals is handled in zone update
6301 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6302 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6305 UpdateAreaDependentAuras(newArea);
6308 void Player::UpdateZone(uint32 newZone)
6310 m_zoneUpdateId = newZone;
6311 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6313 // zone changed, so area changed as well, update it
6314 UpdateArea(GetAreaId());
6316 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6317 if(!zone)
6318 return;
6320 if (sWorld.getConfig(CONFIG_WEATHER))
6322 Weather *wth = sWorld.FindWeather(zone->ID);
6323 if(wth)
6325 wth->SendWeatherUpdateToPlayer(this);
6327 else
6329 if(!sWorld.AddWeather(zone->ID))
6331 // send fine weather packet to remove old zone's weather
6332 Weather::SendFineWeatherUpdateToPlayer(this);
6337 pvpInfo.inHostileArea =
6338 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6339 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6340 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6341 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6343 if(pvpInfo.inHostileArea) // in hostile area
6345 if(!IsPvP() || pvpInfo.endTimer != 0)
6346 UpdatePvP(true, true);
6348 else // in friendly area
6350 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6351 pvpInfo.endTimer = time(0); // start toggle-off
6354 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6356 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6357 if(sWorld.IsFFAPvPRealm())
6358 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6360 else
6362 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6365 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6367 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6368 SetRestType(REST_TYPE_IN_CITY);
6369 InnEnter(time(0),GetMapId(),0,0,0);
6371 if(sWorld.IsFFAPvPRealm())
6372 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6374 else // anywhere else
6376 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6378 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6380 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6382 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6383 SetRestType(REST_TYPE_NO);
6385 if(sWorld.IsFFAPvPRealm())
6386 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6389 else // not in tavern (leave city then)
6391 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6392 SetRestType(REST_TYPE_NO);
6394 // Set player to FFA PVP when not in rested environment.
6395 if(sWorld.IsFFAPvPRealm())
6396 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6401 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6402 // if player resurrected at teleport this will be applied in resurrect code
6403 if(isAlive())
6404 DestroyZoneLimitedItem( true, newZone );
6406 // recent client version not send leave/join channel packets for built-in local channels
6407 UpdateLocalChannels( newZone );
6409 // group update
6410 if(GetGroup())
6411 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6413 UpdateZoneDependentAuras(newZone);
6416 //If players are too far way of duel flag... then player loose the duel
6417 void Player::CheckDuelDistance(time_t currTime)
6419 if(!duel)
6420 return;
6422 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6423 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6424 if(!obj)
6425 return;
6427 if(duel->outOfBound == 0)
6429 if(!IsWithinDistInMap(obj, 50))
6431 duel->outOfBound = currTime;
6433 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6434 GetSession()->SendPacket(&data);
6437 else
6439 if(IsWithinDistInMap(obj, 40))
6441 duel->outOfBound = 0;
6443 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6444 GetSession()->SendPacket(&data);
6446 else if(currTime >= (duel->outOfBound+10))
6448 DuelComplete(DUEL_FLED);
6453 void Player::DuelComplete(DuelCompleteType type)
6455 // duel not requested
6456 if(!duel)
6457 return;
6459 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6460 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6461 GetSession()->SendPacket(&data);
6462 duel->opponent->GetSession()->SendPacket(&data);
6464 if(type != DUEL_INTERUPTED)
6466 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6467 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6468 data << duel->opponent->GetName();
6469 data << GetName();
6470 SendMessageToSet(&data,true);
6473 // cool-down duel spell
6474 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6476 data<<GetGUID();
6477 data<<uint8(0x0);
6479 data<<(uint32)7266;
6480 data<<uint32(0x0);
6481 GetSession()->SendPacket(&data);
6482 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6483 data<<duel->opponent->GetGUID();
6484 data<<uint8(0x0);
6485 data<<(uint32)7266;
6486 data<<uint32(0x0);
6487 duel->opponent->GetSession()->SendPacket(&data);*/
6489 //Remove Duel Flag object
6490 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6491 if(obj)
6492 duel->initiator->RemoveGameObject(obj,true);
6494 /* remove auras */
6495 std::vector<uint32> auras2remove;
6496 AuraMap const& vAuras = duel->opponent->GetAuras();
6497 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6499 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6500 auras2remove.push_back(i->second->GetId());
6503 for(size_t i=0; i<auras2remove.size(); i++)
6504 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6506 auras2remove.clear();
6507 AuraMap const& auras = GetAuras();
6508 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6510 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6511 auras2remove.push_back(i->second->GetId());
6513 for(size_t i=0; i<auras2remove.size(); i++)
6514 RemoveAurasDueToSpell(auras2remove[i]);
6516 // cleanup combo points
6517 if(GetComboTarget()==duel->opponent->GetGUID())
6518 ClearComboPoints();
6519 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6520 ClearComboPoints();
6522 if(duel->opponent->GetComboTarget()==GetGUID())
6523 duel->opponent->ClearComboPoints();
6524 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6525 duel->opponent->ClearComboPoints();
6527 //cleanups
6528 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6529 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6530 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6531 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6533 delete duel->opponent->duel;
6534 duel->opponent->duel = NULL;
6535 delete duel;
6536 duel = NULL;
6539 //---------------------------------------------------------//
6541 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6543 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6544 return;
6546 // not apply/remove mods for broken item
6547 if(item->IsBroken())
6548 return;
6550 ItemPrototype const *proto = item->GetProto();
6552 if(!proto)
6553 return;
6555 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6557 uint32 attacktype = Player::GetAttackBySlot(slot);
6558 if(attacktype < MAX_ATTACK)
6559 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6561 _ApplyItemBonuses(proto,slot,apply);
6563 if( slot==EQUIPMENT_SLOT_RANGED )
6564 _ApplyAmmoBonuses();
6566 ApplyItemEquipSpell(item,apply);
6567 ApplyEnchantment(item, apply);
6569 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6570 CorrectMetaGemEnchants(slot, apply);
6572 sLog.outDebug("_ApplyItemMods complete.");
6575 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6577 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6578 return;
6580 for (int i = 0; i < 10; i++)
6582 uint32 statType = 0;
6583 int32 val = 0;
6585 if(proto->ScalingStatDistribution)
6587 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6589 statType = ssd->StatMod[i];
6591 if(uint32 modifier = ssd->Modifier[i])
6593 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6594 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6596 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6597 val = (multiplier * modifier) / 10000;
6602 else
6604 statType = proto->ItemStat[i].ItemStatType;
6605 val = proto->ItemStat[i].ItemStatValue;
6608 if(val == 0)
6609 continue;
6611 switch (statType)
6613 case ITEM_MOD_MANA:
6614 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6615 break;
6616 case ITEM_MOD_HEALTH: // modify HP
6617 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6618 break;
6619 case ITEM_MOD_AGILITY: // modify agility
6620 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6621 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6622 break;
6623 case ITEM_MOD_STRENGTH: //modify strength
6624 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6625 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6626 break;
6627 case ITEM_MOD_INTELLECT: //modify intellect
6628 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6629 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6630 break;
6631 case ITEM_MOD_SPIRIT: //modify spirit
6632 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6633 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6634 break;
6635 case ITEM_MOD_STAMINA: //modify stamina
6636 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6637 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6638 break;
6639 case ITEM_MOD_DEFENSE_SKILL_RATING:
6640 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6641 break;
6642 case ITEM_MOD_DODGE_RATING:
6643 ApplyRatingMod(CR_DODGE, int32(val), apply);
6644 break;
6645 case ITEM_MOD_PARRY_RATING:
6646 ApplyRatingMod(CR_PARRY, int32(val), apply);
6647 break;
6648 case ITEM_MOD_BLOCK_RATING:
6649 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6650 break;
6651 case ITEM_MOD_HIT_MELEE_RATING:
6652 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6653 break;
6654 case ITEM_MOD_HIT_RANGED_RATING:
6655 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6656 break;
6657 case ITEM_MOD_HIT_SPELL_RATING:
6658 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6659 break;
6660 case ITEM_MOD_CRIT_MELEE_RATING:
6661 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6662 break;
6663 case ITEM_MOD_CRIT_RANGED_RATING:
6664 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6665 break;
6666 case ITEM_MOD_CRIT_SPELL_RATING:
6667 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6668 break;
6669 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6670 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6671 break;
6672 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6673 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6674 break;
6675 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6676 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6677 break;
6678 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6679 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6680 break;
6681 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6682 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6683 break;
6684 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6685 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6686 break;
6687 case ITEM_MOD_HASTE_MELEE_RATING:
6688 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6689 break;
6690 case ITEM_MOD_HASTE_RANGED_RATING:
6691 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6692 break;
6693 case ITEM_MOD_HASTE_SPELL_RATING:
6694 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6695 break;
6696 case ITEM_MOD_HIT_RATING:
6697 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6698 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6699 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6700 break;
6701 case ITEM_MOD_CRIT_RATING:
6702 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6703 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6704 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6705 break;
6706 case ITEM_MOD_HIT_TAKEN_RATING:
6707 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6708 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6709 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6710 break;
6711 case ITEM_MOD_CRIT_TAKEN_RATING:
6712 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6713 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6714 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6715 break;
6716 case ITEM_MOD_RESILIENCE_RATING:
6717 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6718 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6719 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6720 break;
6721 case ITEM_MOD_HASTE_RATING:
6722 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6723 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6724 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6725 break;
6726 case ITEM_MOD_EXPERTISE_RATING:
6727 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6728 break;
6729 case ITEM_MOD_ATTACK_POWER:
6730 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6731 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6732 break;
6733 case ITEM_MOD_RANGED_ATTACK_POWER:
6734 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6735 break;
6736 case ITEM_MOD_FERAL_ATTACK_POWER:
6737 ApplyFeralAPBonus(int32(val), apply);
6738 break;
6739 case ITEM_MOD_SPELL_HEALING_DONE:
6740 ApplySpellHealingBonus(int32(val), apply);
6741 break;
6742 case ITEM_MOD_SPELL_DAMAGE_DONE:
6743 ApplySpellDamageBonus(int32(val), apply);
6744 break;
6745 case ITEM_MOD_MANA_REGENERATION:
6746 ApplyManaRegenBonus(int32(val), apply);
6747 break;
6748 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6749 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6750 break;
6751 case ITEM_MOD_SPELL_POWER:
6752 ApplySpellHealingBonus(int32(val), apply);
6753 ApplySpellDamageBonus(int32(val), apply);
6754 break;
6758 if (proto->Armor)
6759 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6761 if (proto->Block)
6762 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6764 if (proto->HolyRes)
6765 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6767 if (proto->FireRes)
6768 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6770 if (proto->NatureRes)
6771 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6773 if (proto->FrostRes)
6774 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6776 if (proto->ShadowRes)
6777 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6779 if (proto->ArcaneRes)
6780 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6782 WeaponAttackType attType = BASE_ATTACK;
6783 float damage = 0.0f;
6785 if( slot == EQUIPMENT_SLOT_RANGED && (
6786 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6787 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6789 attType = RANGED_ATTACK;
6791 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6793 attType = OFF_ATTACK;
6796 if (proto->Damage[0].DamageMin > 0 )
6798 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6799 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6800 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6803 if (proto->Damage[0].DamageMax > 0 )
6805 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6806 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6809 // Druids get feral AP bonus from weapon dps
6810 if(getClass() == CLASS_DRUID)
6812 int32 feral_bonus = proto->getFeralBonus();
6813 if (feral_bonus > 0)
6814 ApplyFeralAPBonus(feral_bonus, apply);
6817 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6818 return;
6820 if (proto->Delay)
6822 if(slot == EQUIPMENT_SLOT_RANGED)
6823 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6824 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6825 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6826 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6827 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6830 if(CanModifyStats() && (damage || proto->Delay))
6831 UpdateDamagePhysical(attType);
6834 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6836 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6837 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6838 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6840 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6841 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6842 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6844 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6845 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6846 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6849 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6851 // generic not weapon specific case processes in aura code
6852 if(aura->GetSpellProto()->EquippedItemClass == -1)
6853 return;
6855 BaseModGroup mod = BASEMOD_END;
6856 switch(attackType)
6858 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6859 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6860 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6861 default: return;
6864 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6866 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6870 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6872 // ignore spell mods for not wands
6873 Modifier const* modifier = aura->GetModifier();
6874 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6875 return;
6877 // generic not weapon specific case processes in aura code
6878 if(aura->GetSpellProto()->EquippedItemClass == -1)
6879 return;
6881 UnitMods unitMod = UNIT_MOD_END;
6882 switch(attackType)
6884 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6885 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6886 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6887 default: return;
6890 UnitModifierType unitModType = TOTAL_VALUE;
6891 switch(modifier->m_auraname)
6893 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6894 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6895 default: return;
6898 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6900 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6904 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6906 if(!item)
6907 return;
6909 ItemPrototype const *proto = item->GetProto();
6910 if(!proto)
6911 return;
6913 for (int i = 0; i < 5; i++)
6915 _Spell const& spellData = proto->Spells[i];
6917 // no spell
6918 if(!spellData.SpellId )
6919 continue;
6921 // wrong triggering type
6922 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6923 continue;
6925 // check if it is valid spell
6926 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6927 if(!spellproto)
6928 continue;
6930 ApplyEquipSpell(spellproto,item,apply,form_change);
6934 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6936 if(apply)
6938 // Cannot be used in this stance/form
6939 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6940 return;
6942 if(form_change) // check aura active state from other form
6944 bool found = false;
6945 for (int k=0; k < 3; ++k)
6947 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6948 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6950 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6952 found = true;
6953 break;
6956 if(found)
6957 break;
6960 if(found) // and skip re-cast already active aura at form change
6961 return;
6964 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6966 CastSpell(this,spellInfo,true,item);
6968 else
6970 if(form_change) // check aura compatibility
6972 // Cannot be used in this stance/form
6973 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6974 return; // and remove only not compatible at form change
6977 if(item)
6978 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6979 else
6980 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6984 void Player::UpdateEquipSpellsAtFormChange()
6986 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6988 if(m_items[i] && !m_items[i]->IsBroken())
6990 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6991 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6995 // item set bonuses not dependent from item broken state
6996 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6998 ItemSetEffect* eff = ItemSetEff[setindex];
6999 if(!eff)
7000 continue;
7002 for(uint32 y=0;y<8; ++y)
7004 SpellEntry const* spellInfo = eff->spells[y];
7005 if(!spellInfo)
7006 continue;
7008 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7009 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7014 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
7016 if(!item || item->IsBroken())
7017 return;
7019 ItemPrototype const *proto = item->GetProto();
7020 if(!proto)
7021 return;
7023 if (!Target || Target == this )
7024 return;
7026 for (int i = 0; i < 5; i++)
7028 _Spell const& spellData = proto->Spells[i];
7030 // no spell
7031 if(!spellData.SpellId )
7032 continue;
7034 // wrong triggering type
7035 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7036 continue;
7038 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7039 if(!spellInfo)
7041 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7042 continue;
7045 // not allow proc extra attack spell at extra attack
7046 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7047 return;
7049 float chance = spellInfo->procChance;
7051 if(spellData.SpellPPMRate)
7053 uint32 WeaponSpeed = GetAttackTime(attType);
7054 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7056 else if(chance > 100.0f)
7058 chance = GetWeaponProcChance();
7061 if (roll_chance_f(chance))
7062 CastSpell(Target, spellInfo->Id, true, item);
7065 // item combat enchantments
7066 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7068 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7069 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7070 if(!pEnchant) continue;
7071 for (int s=0;s<3;s++)
7073 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7074 continue;
7076 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7077 if (!spellInfo)
7079 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7080 continue;
7083 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7084 if (roll_chance_f(chance))
7086 if(IsPositiveSpell(pEnchant->spellid[s]))
7087 CastSpell(this, pEnchant->spellid[s], true, item);
7088 else
7089 CastSpell(Target, pEnchant->spellid[s], true, item);
7095 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7097 ItemPrototype const* proto = item->GetProto();
7098 // special learning case
7099 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7101 uint32 learn_spell_id = proto->Spells[0].SpellId;
7102 uint32 learning_spell_id = proto->Spells[1].SpellId;
7104 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7105 if(!spellInfo)
7107 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7108 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7109 return;
7112 Spell *spell = new Spell(this, spellInfo, false);
7113 spell->m_CastItem = item;
7114 spell->m_cast_count = cast_count; //set count of casts
7115 spell->m_currentBasePoints[0] = learning_spell_id;
7116 spell->prepare(&targets);
7117 return;
7120 // use triggered flag only for items with many spell casts and for not first cast
7121 int count = 0;
7123 // item spells casted at use
7124 for(int i = 0; i < 5; ++i)
7126 _Spell const& spellData = proto->Spells[i];
7128 // no spell
7129 if(!spellData.SpellId)
7130 continue;
7132 // wrong triggering type
7133 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7134 continue;
7136 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7137 if(!spellInfo)
7139 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7140 continue;
7143 Spell *spell = new Spell(this, spellInfo, (count > 0));
7144 spell->m_CastItem = item;
7145 spell->m_cast_count = cast_count; // set count of casts
7146 spell->m_glyphIndex = glyphIndex; // glyph index
7147 spell->prepare(&targets);
7149 ++count;
7152 // Item enchantments spells casted at use
7153 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7155 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7156 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7157 if(!pEnchant) continue;
7158 for (int s=0;s<3;s++)
7160 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7161 continue;
7163 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7164 if (!spellInfo)
7166 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7167 continue;
7170 Spell *spell = new Spell(this, spellInfo, (count > 0));
7171 spell->m_CastItem = item;
7172 spell->m_cast_count = cast_count; // set count of casts
7173 spell->m_glyphIndex = glyphIndex; // glyph index
7174 spell->prepare(&targets);
7176 ++count;
7181 void Player::_RemoveAllItemMods()
7183 sLog.outDebug("_RemoveAllItemMods start.");
7185 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7187 if(m_items[i])
7189 ItemPrototype const *proto = m_items[i]->GetProto();
7190 if(!proto)
7191 continue;
7193 // item set bonuses not dependent from item broken state
7194 if(proto->ItemSet)
7195 RemoveItemsSetItem(this,proto);
7197 if(m_items[i]->IsBroken())
7198 continue;
7200 ApplyItemEquipSpell(m_items[i],false);
7201 ApplyEnchantment(m_items[i], false);
7205 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7207 if(m_items[i])
7209 if(m_items[i]->IsBroken())
7210 continue;
7211 ItemPrototype const *proto = m_items[i]->GetProto();
7212 if(!proto)
7213 continue;
7215 uint32 attacktype = Player::GetAttackBySlot(i);
7216 if(attacktype < MAX_ATTACK)
7217 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7219 _ApplyItemBonuses(proto,i, false);
7221 if( i == EQUIPMENT_SLOT_RANGED )
7222 _ApplyAmmoBonuses();
7226 sLog.outDebug("_RemoveAllItemMods complete.");
7229 void Player::_ApplyAllItemMods()
7231 sLog.outDebug("_ApplyAllItemMods start.");
7233 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7235 if(m_items[i])
7237 if(m_items[i]->IsBroken())
7238 continue;
7240 ItemPrototype const *proto = m_items[i]->GetProto();
7241 if(!proto)
7242 continue;
7244 uint32 attacktype = Player::GetAttackBySlot(i);
7245 if(attacktype < MAX_ATTACK)
7246 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7248 _ApplyItemBonuses(proto,i, true);
7250 if( i == EQUIPMENT_SLOT_RANGED )
7251 _ApplyAmmoBonuses();
7255 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7257 if(m_items[i])
7259 ItemPrototype const *proto = m_items[i]->GetProto();
7260 if(!proto)
7261 continue;
7263 // item set bonuses not dependent from item broken state
7264 if(proto->ItemSet)
7265 AddItemsSetItem(this,m_items[i]);
7267 if(m_items[i]->IsBroken())
7268 continue;
7270 ApplyItemEquipSpell(m_items[i],true);
7271 ApplyEnchantment(m_items[i], true);
7275 sLog.outDebug("_ApplyAllItemMods complete.");
7278 void Player::_ApplyAmmoBonuses()
7280 // check ammo
7281 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7282 if(!ammo_id)
7283 return;
7285 float currentAmmoDPS;
7287 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7288 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7289 currentAmmoDPS = 0.0f;
7290 else
7291 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7293 if(currentAmmoDPS == GetAmmoDPS())
7294 return;
7296 m_ammoDPS = currentAmmoDPS;
7298 if(CanModifyStats())
7299 UpdateDamagePhysical(RANGED_ATTACK);
7302 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7304 if(!ammo_proto)
7305 return false;
7307 // check ranged weapon
7308 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7309 if(!weapon || weapon->IsBroken() )
7310 return false;
7312 ItemPrototype const* weapon_proto = weapon->GetProto();
7313 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7314 return false;
7316 // check ammo ws. weapon compatibility
7317 switch(weapon_proto->SubClass)
7319 case ITEM_SUBCLASS_WEAPON_BOW:
7320 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7321 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7322 return false;
7323 break;
7324 case ITEM_SUBCLASS_WEAPON_GUN:
7325 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7326 return false;
7327 break;
7328 default:
7329 return false;
7332 return true;
7335 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7336 Called by remove insignia spell effect */
7337 void Player::RemovedInsignia(Player* looterPlr)
7339 if (!GetBattleGroundId())
7340 return;
7342 // If not released spirit, do it !
7343 if(m_deathTimer > 0)
7345 m_deathTimer = 0;
7346 BuildPlayerRepop();
7347 RepopAtGraveyard();
7350 Corpse *corpse = GetCorpse();
7351 if (!corpse)
7352 return;
7354 // We have to convert player corpse to bones, not to be able to resurrect there
7355 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7356 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7357 if (!bones)
7358 return;
7360 // Now we must make bones lootable, and send player loot
7361 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7363 // We store the level of our player in the gold field
7364 // We retrieve this information at Player::SendLoot()
7365 bones->loot.gold = getLevel();
7366 bones->lootRecipient = looterPlr;
7367 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7370 /*Loot type MUST be
7371 1-corpse, go
7372 2-skinning
7373 3-Fishing
7376 void Player::SendLootRelease( uint64 guid )
7378 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7379 data << uint64(guid) << uint8(1);
7380 SendDirectMessage( &data );
7383 void Player::SendLoot(uint64 guid, LootType loot_type)
7385 Loot *loot = 0;
7386 PermissionTypes permission = ALL_PERMISSION;
7388 sLog.outDebug("Player::SendLoot");
7389 if (IS_GAMEOBJECT_GUID(guid))
7391 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7392 GameObject *go =
7393 ObjectAccessor::GetGameObject(*this, guid);
7395 // not check distance for GO in case owned GO (fishing bobber case, for example)
7396 // And permit out of range GO with no owner in case fishing hole
7397 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7399 SendLootRelease(guid);
7400 return;
7403 loot = &go->loot;
7405 if(go->getLootState() == GO_READY)
7407 uint32 lootid = go->GetLootId();
7409 if(lootid)
7411 sLog.outDebug(" if(lootid)");
7412 loot->clear();
7413 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7416 if(loot_type == LOOT_FISHING)
7417 go->getFishLoot(loot,this);
7419 go->SetLootState(GO_ACTIVATED);
7422 else if (IS_ITEM_GUID(guid))
7424 Item *item = GetItemByGuid( guid );
7426 if (!item)
7428 SendLootRelease(guid);
7429 return;
7432 if(loot_type == LOOT_DISENCHANTING)
7434 loot = &item->loot;
7436 if(!item->m_lootGenerated)
7438 item->m_lootGenerated = true;
7439 loot->clear();
7440 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7443 else if(loot_type == LOOT_PROSPECTING)
7445 loot = &item->loot;
7447 if(!item->m_lootGenerated)
7449 item->m_lootGenerated = true;
7450 loot->clear();
7451 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7454 else if(loot_type == LOOT_MILLING)
7456 loot = &item->loot;
7458 if(!item->m_lootGenerated)
7460 item->m_lootGenerated = true;
7461 loot->clear();
7462 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7465 else
7467 loot = &item->loot;
7469 if(!item->m_lootGenerated)
7471 item->m_lootGenerated = true;
7472 loot->clear();
7473 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7475 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7479 else if (IS_CORPSE_GUID(guid)) // remove insignia
7481 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7483 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7485 SendLootRelease(guid);
7486 return;
7489 loot = &bones->loot;
7491 if (!bones->lootForBody)
7493 bones->lootForBody = true;
7494 uint32 pLevel = bones->loot.gold;
7495 bones->loot.clear();
7496 // It may need a better formula
7497 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7498 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7501 if (bones->lootRecipient != this)
7502 permission = NONE_PERMISSION;
7504 else
7506 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7508 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7509 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7511 SendLootRelease(guid);
7512 return;
7515 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7517 SendLootRelease(guid);
7518 return;
7521 loot = &creature->loot;
7523 if(loot_type == LOOT_PICKPOCKETING)
7525 if ( !creature->lootForPickPocketed )
7527 creature->lootForPickPocketed = true;
7528 loot->clear();
7530 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7531 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7533 // Generate extra money for pick pocket loot
7534 const uint32 a = urand(0, creature->getLevel()/2);
7535 const uint32 b = urand(0, getLevel()/2);
7536 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7539 else
7541 // the player whose group may loot the corpse
7542 Player *recipient = creature->GetLootRecipient();
7543 if (!recipient)
7545 creature->SetLootRecipient(this);
7546 recipient = this;
7549 if (creature->lootForPickPocketed)
7551 creature->lootForPickPocketed = false;
7552 loot->clear();
7555 if(!creature->lootForBody)
7557 creature->lootForBody = true;
7558 loot->clear();
7560 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7561 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7563 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7565 if(Group* group = recipient->GetGroup())
7567 group->UpdateLooterGuid(creature,true);
7569 switch (group->GetLootMethod())
7571 case GROUP_LOOT:
7572 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7573 group->GroupLoot(recipient->GetGUID(), loot, creature);
7574 break;
7575 case NEED_BEFORE_GREED:
7576 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7577 break;
7578 case MASTER_LOOT:
7579 group->MasterLoot(recipient->GetGUID(), loot, creature);
7580 break;
7581 default:
7582 break;
7587 // possible only if creature->lootForBody && loot->empty() at spell cast check
7588 if (loot_type == LOOT_SKINNING)
7590 loot->clear();
7591 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7593 // set group rights only for loot_type != LOOT_SKINNING
7594 else
7596 if(Group* group = GetGroup())
7598 if( group == recipient->GetGroup() )
7600 if(group->GetLootMethod() == FREE_FOR_ALL)
7601 permission = ALL_PERMISSION;
7602 else if(group->GetLooterGuid() == GetGUID())
7604 if(group->GetLootMethod() == MASTER_LOOT)
7605 permission = MASTER_PERMISSION;
7606 else
7607 permission = ALL_PERMISSION;
7609 else
7610 permission = GROUP_PERMISSION;
7612 else
7613 permission = NONE_PERMISSION;
7615 else if(recipient == this)
7616 permission = ALL_PERMISSION;
7617 else
7618 permission = NONE_PERMISSION;
7623 SetLootGUID(guid);
7625 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7626 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7627 loot_type = LOOT_SKINNING;
7629 if(loot_type == LOOT_FISHINGHOLE)
7630 loot_type = LOOT_FISHING;
7632 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7634 data << uint64(guid);
7635 data << uint8(loot_type);
7636 data << LootView(*loot, this, permission);
7638 SendDirectMessage(&data);
7640 // add 'this' player as one of the players that are looting 'loot'
7641 if (permission != NONE_PERMISSION)
7642 loot->AddLooter(GetGUID());
7644 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7645 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7648 void Player::SendNotifyLootMoneyRemoved()
7650 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7651 GetSession()->SendPacket( &data );
7654 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7656 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7657 data << uint8(lootSlot);
7658 GetSession()->SendPacket( &data );
7661 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7663 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7664 data << Field;
7665 data << Value;
7666 GetSession()->SendPacket(&data);
7669 void Player::SendInitWorldStates()
7671 // data depends on zoneid/mapid...
7672 BattleGround* bg = GetBattleGround();
7673 uint16 NumberOfFields = 0;
7674 uint32 mapid = GetMapId();
7675 uint32 zoneid = GetZoneId();
7676 uint32 areaid = GetAreaId();
7677 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7678 // may be exist better way to do this...
7679 switch(zoneid)
7681 case 0:
7682 case 1:
7683 case 4:
7684 case 8:
7685 case 10:
7686 case 11:
7687 case 12:
7688 case 36:
7689 case 38:
7690 case 40:
7691 case 41:
7692 case 51:
7693 case 267:
7694 case 1519:
7695 case 1537:
7696 case 2257:
7697 case 2918:
7698 NumberOfFields = 8;
7699 break;
7700 case 139:
7701 NumberOfFields = 41;
7702 break;
7703 case 1377:
7704 NumberOfFields = 15;
7705 break;
7706 case 2597:
7707 NumberOfFields = 83;
7708 break;
7709 case 3277:
7710 NumberOfFields = 16;
7711 break;
7712 case 3358:
7713 case 3820:
7714 NumberOfFields = 40;
7715 break;
7716 case 3483:
7717 NumberOfFields = 27;
7718 break;
7719 case 3518:
7720 NumberOfFields = 39;
7721 break;
7722 case 3519:
7723 NumberOfFields = 38;
7724 break;
7725 case 3521:
7726 NumberOfFields = 37;
7727 break;
7728 case 3698:
7729 case 3702:
7730 case 3968:
7731 NumberOfFields = 11;
7732 break;
7733 case 3703:
7734 NumberOfFields = 11;
7735 break;
7736 default:
7737 NumberOfFields = 12;
7738 break;
7741 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7742 data << uint32(mapid); // mapid
7743 data << uint32(zoneid); // zone id
7744 data << uint32(areaid); // area id, new 2.1.0
7745 data << uint16(NumberOfFields); // count of uint64 blocks
7746 data << uint32(0x8d8) << uint32(0x0); // 1
7747 data << uint32(0x8d7) << uint32(0x0); // 2
7748 data << uint32(0x8d6) << uint32(0x0); // 3
7749 data << uint32(0x8d5) << uint32(0x0); // 4
7750 data << uint32(0x8d4) << uint32(0x0); // 5
7751 data << uint32(0x8d3) << uint32(0x0); // 6
7752 // 7 1 - Arena season in progress, 0 - end of season
7753 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7754 // 8 Arena season id
7755 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7756 if(mapid == 530) // Outland
7758 data << uint32(0x9bf) << uint32(0x0); // 7
7759 data << uint32(0x9bd) << uint32(0xF); // 8
7760 data << uint32(0x9bb) << uint32(0xF); // 9
7762 switch(zoneid)
7764 case 1:
7765 case 11:
7766 case 12:
7767 case 38:
7768 case 40:
7769 case 51:
7770 case 1519:
7771 case 1537:
7772 case 2257:
7773 break;
7774 case 2597: // AV
7775 data << uint32(0x7ae) << uint32(0x1); // 7
7776 data << uint32(0x532) << uint32(0x1); // 8
7777 data << uint32(0x531) << uint32(0x0); // 9
7778 data << uint32(0x52e) << uint32(0x0); // 10
7779 data << uint32(0x571) << uint32(0x0); // 11
7780 data << uint32(0x570) << uint32(0x0); // 12
7781 data << uint32(0x567) << uint32(0x1); // 13
7782 data << uint32(0x566) << uint32(0x1); // 14
7783 data << uint32(0x550) << uint32(0x1); // 15
7784 data << uint32(0x544) << uint32(0x0); // 16
7785 data << uint32(0x536) << uint32(0x0); // 17
7786 data << uint32(0x535) << uint32(0x1); // 18
7787 data << uint32(0x518) << uint32(0x0); // 19
7788 data << uint32(0x517) << uint32(0x0); // 20
7789 data << uint32(0x574) << uint32(0x0); // 21
7790 data << uint32(0x573) << uint32(0x0); // 22
7791 data << uint32(0x572) << uint32(0x0); // 23
7792 data << uint32(0x56f) << uint32(0x0); // 24
7793 data << uint32(0x56e) << uint32(0x0); // 25
7794 data << uint32(0x56d) << uint32(0x0); // 26
7795 data << uint32(0x56c) << uint32(0x0); // 27
7796 data << uint32(0x56b) << uint32(0x0); // 28
7797 data << uint32(0x56a) << uint32(0x1); // 29
7798 data << uint32(0x569) << uint32(0x1); // 30
7799 data << uint32(0x568) << uint32(0x1); // 13
7800 data << uint32(0x565) << uint32(0x0); // 32
7801 data << uint32(0x564) << uint32(0x0); // 33
7802 data << uint32(0x563) << uint32(0x0); // 34
7803 data << uint32(0x562) << uint32(0x0); // 35
7804 data << uint32(0x561) << uint32(0x0); // 36
7805 data << uint32(0x560) << uint32(0x0); // 37
7806 data << uint32(0x55f) << uint32(0x0); // 38
7807 data << uint32(0x55e) << uint32(0x0); // 39
7808 data << uint32(0x55d) << uint32(0x0); // 40
7809 data << uint32(0x3c6) << uint32(0x4); // 41
7810 data << uint32(0x3c4) << uint32(0x6); // 42
7811 data << uint32(0x3c2) << uint32(0x4); // 43
7812 data << uint32(0x516) << uint32(0x1); // 44
7813 data << uint32(0x515) << uint32(0x0); // 45
7814 data << uint32(0x3b6) << uint32(0x6); // 46
7815 data << uint32(0x55c) << uint32(0x0); // 47
7816 data << uint32(0x55b) << uint32(0x0); // 48
7817 data << uint32(0x55a) << uint32(0x0); // 49
7818 data << uint32(0x559) << uint32(0x0); // 50
7819 data << uint32(0x558) << uint32(0x0); // 51
7820 data << uint32(0x557) << uint32(0x0); // 52
7821 data << uint32(0x556) << uint32(0x0); // 53
7822 data << uint32(0x555) << uint32(0x0); // 54
7823 data << uint32(0x554) << uint32(0x1); // 55
7824 data << uint32(0x553) << uint32(0x1); // 56
7825 data << uint32(0x552) << uint32(0x1); // 57
7826 data << uint32(0x551) << uint32(0x1); // 58
7827 data << uint32(0x54f) << uint32(0x0); // 59
7828 data << uint32(0x54e) << uint32(0x0); // 60
7829 data << uint32(0x54d) << uint32(0x1); // 61
7830 data << uint32(0x54c) << uint32(0x0); // 62
7831 data << uint32(0x54b) << uint32(0x0); // 63
7832 data << uint32(0x545) << uint32(0x0); // 64
7833 data << uint32(0x543) << uint32(0x1); // 65
7834 data << uint32(0x542) << uint32(0x0); // 66
7835 data << uint32(0x540) << uint32(0x0); // 67
7836 data << uint32(0x53f) << uint32(0x0); // 68
7837 data << uint32(0x53e) << uint32(0x0); // 69
7838 data << uint32(0x53d) << uint32(0x0); // 70
7839 data << uint32(0x53c) << uint32(0x0); // 71
7840 data << uint32(0x53b) << uint32(0x0); // 72
7841 data << uint32(0x53a) << uint32(0x1); // 73
7842 data << uint32(0x539) << uint32(0x0); // 74
7843 data << uint32(0x538) << uint32(0x0); // 75
7844 data << uint32(0x537) << uint32(0x0); // 76
7845 data << uint32(0x534) << uint32(0x0); // 77
7846 data << uint32(0x533) << uint32(0x0); // 78
7847 data << uint32(0x530) << uint32(0x0); // 79
7848 data << uint32(0x52f) << uint32(0x0); // 80
7849 data << uint32(0x52d) << uint32(0x1); // 81
7850 break;
7851 case 3277: // WS
7852 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7853 bg->FillInitialWorldStates(data);
7854 else
7856 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7857 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7858 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7859 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7860 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7861 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7862 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7863 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7865 break;
7866 case 3358: // AB
7867 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7868 bg->FillInitialWorldStates(data);
7869 else
7871 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7872 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7873 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7874 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7875 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7876 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7877 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7878 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7879 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7880 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7881 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7882 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7883 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7884 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7885 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7886 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7887 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7888 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7889 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7890 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7891 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7892 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7893 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7894 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7895 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7896 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7897 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7898 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7899 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7900 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7901 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7902 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7904 break;
7905 case 3820: // EY
7906 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7907 bg->FillInitialWorldStates(data);
7908 else
7910 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7911 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7912 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7913 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7914 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7915 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7916 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7917 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7918 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7919 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7920 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7921 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7922 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7923 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7924 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7925 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7926 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7927 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7928 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7929 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7930 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7931 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7932 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7933 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7934 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7935 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7936 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7937 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7938 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7939 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7940 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7941 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7942 // and some more ... unknown
7944 break;
7945 case 3483: // Hellfire Peninsula
7946 data << uint32(0x9ba) << uint32(0x1); // 10
7947 data << uint32(0x9b9) << uint32(0x1); // 11
7948 data << uint32(0x9b5) << uint32(0x0); // 12
7949 data << uint32(0x9b4) << uint32(0x1); // 13
7950 data << uint32(0x9b3) << uint32(0x0); // 14
7951 data << uint32(0x9b2) << uint32(0x0); // 15
7952 data << uint32(0x9b1) << uint32(0x1); // 16
7953 data << uint32(0x9b0) << uint32(0x0); // 17
7954 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7955 data << uint32(0x9ac) << uint32(0x0); // 19
7956 data << uint32(0x9a8) << uint32(0x0); // 20
7957 data << uint32(0x9a7) << uint32(0x0); // 21
7958 data << uint32(0x9a6) << uint32(0x1); // 22
7959 break;
7960 case 3519: // Terokkar Forest
7961 data << uint32(0xa41) << uint32(0x0); // 10
7962 data << uint32(0xa40) << uint32(0x14); // 11
7963 data << uint32(0xa3f) << uint32(0x0); // 12
7964 data << uint32(0xa3e) << uint32(0x0); // 13
7965 data << uint32(0xa3d) << uint32(0x5); // 14
7966 data << uint32(0xa3c) << uint32(0x0); // 15
7967 data << uint32(0xa87) << uint32(0x0); // 16
7968 data << uint32(0xa86) << uint32(0x0); // 17
7969 data << uint32(0xa85) << uint32(0x0); // 18
7970 data << uint32(0xa84) << uint32(0x0); // 19
7971 data << uint32(0xa83) << uint32(0x0); // 20
7972 data << uint32(0xa82) << uint32(0x0); // 21
7973 data << uint32(0xa81) << uint32(0x0); // 22
7974 data << uint32(0xa80) << uint32(0x0); // 23
7975 data << uint32(0xa7e) << uint32(0x0); // 24
7976 data << uint32(0xa7d) << uint32(0x0); // 25
7977 data << uint32(0xa7c) << uint32(0x0); // 26
7978 data << uint32(0xa7b) << uint32(0x0); // 27
7979 data << uint32(0xa7a) << uint32(0x0); // 28
7980 data << uint32(0xa79) << uint32(0x0); // 29
7981 data << uint32(0x9d0) << uint32(0x5); // 30
7982 data << uint32(0x9ce) << uint32(0x0); // 31
7983 data << uint32(0x9cd) << uint32(0x0); // 32
7984 data << uint32(0x9cc) << uint32(0x0); // 33
7985 data << uint32(0xa88) << uint32(0x0); // 34
7986 data << uint32(0xad0) << uint32(0x0); // 35
7987 data << uint32(0xacf) << uint32(0x1); // 36
7988 break;
7989 case 3521: // Zangarmarsh
7990 data << uint32(0x9e1) << uint32(0x0); // 10
7991 data << uint32(0x9e0) << uint32(0x0); // 11
7992 data << uint32(0x9df) << uint32(0x0); // 12
7993 data << uint32(0xa5d) << uint32(0x1); // 13
7994 data << uint32(0xa5c) << uint32(0x0); // 14
7995 data << uint32(0xa5b) << uint32(0x1); // 15
7996 data << uint32(0xa5a) << uint32(0x0); // 16
7997 data << uint32(0xa59) << uint32(0x1); // 17
7998 data << uint32(0xa58) << uint32(0x0); // 18
7999 data << uint32(0xa57) << uint32(0x0); // 19
8000 data << uint32(0xa56) << uint32(0x0); // 20
8001 data << uint32(0xa55) << uint32(0x1); // 21
8002 data << uint32(0xa54) << uint32(0x0); // 22
8003 data << uint32(0x9e7) << uint32(0x0); // 23
8004 data << uint32(0x9e6) << uint32(0x0); // 24
8005 data << uint32(0x9e5) << uint32(0x0); // 25
8006 data << uint32(0xa00) << uint32(0x0); // 26
8007 data << uint32(0x9ff) << uint32(0x1); // 27
8008 data << uint32(0x9fe) << uint32(0x0); // 28
8009 data << uint32(0x9fd) << uint32(0x0); // 29
8010 data << uint32(0x9fc) << uint32(0x1); // 30
8011 data << uint32(0x9fb) << uint32(0x0); // 31
8012 data << uint32(0xa62) << uint32(0x0); // 32
8013 data << uint32(0xa61) << uint32(0x1); // 33
8014 data << uint32(0xa60) << uint32(0x1); // 34
8015 data << uint32(0xa5f) << uint32(0x0); // 35
8016 break;
8017 case 3698: // Nagrand Arena
8018 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8019 bg->FillInitialWorldStates(data);
8020 else
8022 data << uint32(0xa0f) << uint32(0x0); // 7
8023 data << uint32(0xa10) << uint32(0x0); // 8
8024 data << uint32(0xa11) << uint32(0x0); // 9 show
8026 break;
8027 case 3702: // Blade's Edge Arena
8028 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8029 bg->FillInitialWorldStates(data);
8030 else
8032 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8033 data << uint32(0x9f1) << uint32(0x0); // 8 green
8034 data << uint32(0x9f3) << uint32(0x0); // 9 show
8036 break;
8037 case 3968: // Ruins of Lordaeron
8038 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8039 bg->FillInitialWorldStates(data);
8040 else
8042 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8043 data << uint32(0xbb9) << uint32(0x0); // 8 green
8044 data << uint32(0xbba) << uint32(0x0); // 9 show
8046 break;
8047 case 3703: // Shattrath City
8048 break;
8049 default:
8050 data << uint32(0x914) << uint32(0x0); // 7
8051 data << uint32(0x913) << uint32(0x0); // 8
8052 data << uint32(0x912) << uint32(0x0); // 9
8053 data << uint32(0x915) << uint32(0x0); // 10
8054 break;
8056 GetSession()->SendPacket(&data);
8059 uint32 Player::GetXPRestBonus(uint32 xp)
8061 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8063 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8064 rested_bonus = xp;
8066 SetRestBonus( GetRestBonus() - rested_bonus);
8068 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8069 return rested_bonus;
8072 void Player::SetBindPoint(uint64 guid)
8074 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8075 data << uint64(guid);
8076 GetSession()->SendPacket( &data );
8079 void Player::SendTalentWipeConfirm(uint64 guid)
8081 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8082 data << uint64(guid);
8083 data << uint32(resetTalentsCost());
8084 GetSession()->SendPacket( &data );
8087 void Player::SendPetSkillWipeConfirm()
8089 Pet* pet = GetPet();
8090 if(!pet)
8091 return;
8092 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8093 data << pet->GetGUID();
8094 data << uint32(pet->resetTalentsCost());
8095 GetSession()->SendPacket( &data );
8098 /*********************************************************/
8099 /*** STORAGE SYSTEM ***/
8100 /*********************************************************/
8102 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8104 assert(i < 3);
8105 if(i < 2 && item)
8107 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8108 return;
8109 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8110 if(charges == 0)
8111 return;
8112 if(charges > 1)
8113 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8114 else if(charges <= 1)
8116 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8117 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8122 void Player::SetSheath( uint32 sheathed )
8124 switch (sheathed)
8126 case SHEATH_STATE_UNARMED: // no prepared weapon
8127 SetVirtualItemSlot(0,NULL);
8128 SetVirtualItemSlot(1,NULL);
8129 SetVirtualItemSlot(2,NULL);
8130 break;
8131 case SHEATH_STATE_MELEE: // prepared melee weapon
8133 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8134 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8135 SetVirtualItemSlot(2,NULL);
8136 }; break;
8137 case SHEATH_STATE_RANGED: // prepared ranged weapon
8138 SetVirtualItemSlot(0,NULL);
8139 SetVirtualItemSlot(1,NULL);
8140 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8141 break;
8142 default:
8143 SetVirtualItemSlot(0,NULL);
8144 SetVirtualItemSlot(1,NULL);
8145 SetVirtualItemSlot(2,NULL);
8146 break;
8148 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
8151 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8153 uint8 pClass = getClass();
8155 uint8 slots[4];
8156 slots[0] = NULL_SLOT;
8157 slots[1] = NULL_SLOT;
8158 slots[2] = NULL_SLOT;
8159 slots[3] = NULL_SLOT;
8160 switch( proto->InventoryType )
8162 case INVTYPE_HEAD:
8163 slots[0] = EQUIPMENT_SLOT_HEAD;
8164 break;
8165 case INVTYPE_NECK:
8166 slots[0] = EQUIPMENT_SLOT_NECK;
8167 break;
8168 case INVTYPE_SHOULDERS:
8169 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8170 break;
8171 case INVTYPE_BODY:
8172 slots[0] = EQUIPMENT_SLOT_BODY;
8173 break;
8174 case INVTYPE_CHEST:
8175 slots[0] = EQUIPMENT_SLOT_CHEST;
8176 break;
8177 case INVTYPE_ROBE:
8178 slots[0] = EQUIPMENT_SLOT_CHEST;
8179 break;
8180 case INVTYPE_WAIST:
8181 slots[0] = EQUIPMENT_SLOT_WAIST;
8182 break;
8183 case INVTYPE_LEGS:
8184 slots[0] = EQUIPMENT_SLOT_LEGS;
8185 break;
8186 case INVTYPE_FEET:
8187 slots[0] = EQUIPMENT_SLOT_FEET;
8188 break;
8189 case INVTYPE_WRISTS:
8190 slots[0] = EQUIPMENT_SLOT_WRISTS;
8191 break;
8192 case INVTYPE_HANDS:
8193 slots[0] = EQUIPMENT_SLOT_HANDS;
8194 break;
8195 case INVTYPE_FINGER:
8196 slots[0] = EQUIPMENT_SLOT_FINGER1;
8197 slots[1] = EQUIPMENT_SLOT_FINGER2;
8198 break;
8199 case INVTYPE_TRINKET:
8200 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8201 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8202 break;
8203 case INVTYPE_CLOAK:
8204 slots[0] = EQUIPMENT_SLOT_BACK;
8205 break;
8206 case INVTYPE_WEAPON:
8208 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8210 // suggest offhand slot only if know dual wielding
8211 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8212 if(CanDualWield())
8213 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8214 break;
8216 case INVTYPE_SHIELD:
8217 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8218 break;
8219 case INVTYPE_RANGED:
8220 slots[0] = EQUIPMENT_SLOT_RANGED;
8221 break;
8222 case INVTYPE_2HWEAPON:
8223 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8224 if (CanDualWield() && CanTitanGrip())
8225 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8226 break;
8227 case INVTYPE_TABARD:
8228 slots[0] = EQUIPMENT_SLOT_TABARD;
8229 break;
8230 case INVTYPE_WEAPONMAINHAND:
8231 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8232 break;
8233 case INVTYPE_WEAPONOFFHAND:
8234 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8235 break;
8236 case INVTYPE_HOLDABLE:
8237 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8238 break;
8239 case INVTYPE_THROWN:
8240 slots[0] = EQUIPMENT_SLOT_RANGED;
8241 break;
8242 case INVTYPE_RANGEDRIGHT:
8243 slots[0] = EQUIPMENT_SLOT_RANGED;
8244 break;
8245 case INVTYPE_BAG:
8246 slots[0] = INVENTORY_SLOT_BAG_1;
8247 slots[1] = INVENTORY_SLOT_BAG_2;
8248 slots[2] = INVENTORY_SLOT_BAG_3;
8249 slots[3] = INVENTORY_SLOT_BAG_4;
8250 break;
8251 case INVTYPE_RELIC:
8253 switch(proto->SubClass)
8255 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8256 if (pClass == CLASS_PALADIN)
8257 slots[0] = EQUIPMENT_SLOT_RANGED;
8258 break;
8259 case ITEM_SUBCLASS_ARMOR_IDOL:
8260 if (pClass == CLASS_DRUID)
8261 slots[0] = EQUIPMENT_SLOT_RANGED;
8262 break;
8263 case ITEM_SUBCLASS_ARMOR_TOTEM:
8264 if (pClass == CLASS_SHAMAN)
8265 slots[0] = EQUIPMENT_SLOT_RANGED;
8266 break;
8267 case ITEM_SUBCLASS_ARMOR_MISC:
8268 if (pClass == CLASS_WARLOCK)
8269 slots[0] = EQUIPMENT_SLOT_RANGED;
8270 break;
8271 case ITEM_SUBCLASS_ARMOR_SIGIL:
8272 if (pClass == CLASS_DEATH_KNIGHT)
8273 slots[0] = EQUIPMENT_SLOT_RANGED;
8274 break;
8276 break;
8278 default :
8279 return NULL_SLOT;
8282 if( slot != NULL_SLOT )
8284 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8286 for (int i = 0; i < 4; i++)
8288 if ( slots[i] == slot )
8289 return slot;
8293 else
8295 // search free slot at first
8296 for (int i = 0; i < 4; i++)
8298 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8300 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8301 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8302 return slots[i];
8306 // if not found free and can swap return first appropriate from used
8307 for (int i = 0; i < 4; i++)
8309 if ( slots[i] != NULL_SLOT && swap )
8310 return slots[i];
8314 // no free position
8315 return NULL_SLOT;
8318 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8320 Item *pItem;
8321 uint32 tempcount = 0;
8323 uint8 res = EQUIP_ERR_OK;
8325 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8327 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8328 if( pItem && pItem->GetEntry() == item )
8330 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8331 if(ires==EQUIP_ERR_OK)
8333 tempcount += pItem->GetCount();
8334 if( tempcount >= count )
8335 return EQUIP_ERR_OK;
8337 else
8338 res = ires;
8341 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8343 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8344 if( pItem && pItem->GetEntry() == item )
8346 tempcount += pItem->GetCount();
8347 if( tempcount >= count )
8348 return EQUIP_ERR_OK;
8351 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8353 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8354 if( pItem && pItem->GetEntry() == item )
8356 tempcount += pItem->GetCount();
8357 if( tempcount >= count )
8358 return EQUIP_ERR_OK;
8361 Bag *pBag;
8362 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8364 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8365 if( pBag )
8367 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8369 pItem = GetItemByPos( i, j );
8370 if( pItem && pItem->GetEntry() == item )
8372 tempcount += pItem->GetCount();
8373 if( tempcount >= count )
8374 return EQUIP_ERR_OK;
8380 // not found req. item count and have unequippable items
8381 return res;
8384 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8386 uint32 count = 0;
8387 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8389 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8390 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8391 count += pItem->GetCount();
8393 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8395 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8396 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8397 count += pItem->GetCount();
8399 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8401 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8402 if( pBag )
8403 count += pBag->GetItemCount(item,skipItem);
8406 if(skipItem && skipItem->GetProto()->GemProperties)
8408 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8410 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8411 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8412 count += pItem->GetGemCountWithID(item);
8416 if(inBankAlso)
8418 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8420 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8421 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8422 count += pItem->GetCount();
8424 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8426 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8427 if( pBag )
8428 count += pBag->GetItemCount(item,skipItem);
8431 if(skipItem && skipItem->GetProto()->GemProperties)
8433 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8435 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8436 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8437 count += pItem->GetGemCountWithID(item);
8442 return count;
8445 Item* Player::GetItemByGuid( uint64 guid ) const
8447 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8449 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8450 if( pItem && pItem->GetGUID() == guid )
8451 return pItem;
8453 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8455 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8456 if( pItem && pItem->GetGUID() == guid )
8457 return pItem;
8460 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8462 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8463 if( pBag )
8465 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8467 Item* pItem = pBag->GetItemByPos( j );
8468 if( pItem && pItem->GetGUID() == guid )
8469 return pItem;
8473 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8475 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8476 if( pBag )
8478 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8480 Item* pItem = pBag->GetItemByPos( j );
8481 if( pItem && pItem->GetGUID() == guid )
8482 return pItem;
8487 return NULL;
8490 Item* Player::GetItemByPos( uint16 pos ) const
8492 uint8 bag = pos >> 8;
8493 uint8 slot = pos & 255;
8494 return GetItemByPos( bag, slot );
8497 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8499 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8500 return m_items[slot];
8501 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8502 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8504 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8505 if ( pBag )
8506 return pBag->GetItemByPos(slot);
8508 return NULL;
8511 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8513 uint16 slot;
8514 switch (attackType)
8516 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8517 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8518 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8519 default: return NULL;
8522 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8523 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8524 return NULL;
8526 if(!useable)
8527 return item;
8529 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8530 return NULL;
8532 return item;
8535 Item* Player::GetShield(bool useable) const
8537 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8538 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8539 return NULL;
8541 if(!useable)
8542 return item;
8544 if( item->IsBroken())
8545 return NULL;
8547 return item;
8550 uint32 Player::GetAttackBySlot( uint8 slot )
8552 switch(slot)
8554 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8555 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8556 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8557 default: return MAX_ATTACK;
8561 bool Player::HasBankBagSlot( uint8 slot ) const
8563 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8564 if( slot < maxslot )
8565 return true;
8566 return false;
8569 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8571 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8572 return true;
8573 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8574 return true;
8575 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8576 return true;
8577 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8578 return true;
8579 return false;
8582 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8584 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8585 return true;
8586 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8587 return true;
8588 return false;
8591 bool Player::IsBankPos( uint8 bag, uint8 slot )
8593 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8594 return true;
8595 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8596 return true;
8597 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8598 return true;
8599 return false;
8602 bool Player::IsBagPos( uint16 pos )
8604 uint8 bag = pos >> 8;
8605 uint8 slot = pos & 255;
8606 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8607 return true;
8608 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8609 return true;
8610 return false;
8613 bool Player::IsValidPos( uint8 bag, uint8 slot )
8615 // post selected
8616 if(bag == NULL_BAG)
8617 return true;
8619 if (bag == INVENTORY_SLOT_BAG_0)
8621 // any post selected
8622 if (slot == NULL_SLOT)
8623 return true;
8625 // equipment
8626 if (slot < EQUIPMENT_SLOT_END)
8627 return true;
8629 // bag equip slots
8630 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8631 return true;
8633 // backpack slots
8634 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8635 return true;
8637 // keyring slots
8638 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8639 return true;
8641 // bank main slots
8642 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8643 return true;
8645 // bank bag slots
8646 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8647 return true;
8649 return false;
8652 // bag content slots
8653 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8655 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8656 if(!pBag)
8657 return false;
8659 // any post selected
8660 if (slot == NULL_SLOT)
8661 return true;
8663 return slot < pBag->GetBagSize();
8666 // bank bag content slots
8667 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8669 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8670 if(!pBag)
8671 return false;
8673 // any post selected
8674 if (slot == NULL_SLOT)
8675 return true;
8677 return slot < pBag->GetBagSize();
8680 // where this?
8681 return false;
8685 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8687 uint32 tempcount = 0;
8688 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8690 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8691 if( pItem && pItem->GetEntry() == item )
8693 tempcount += pItem->GetCount();
8694 if( tempcount >= count )
8695 return true;
8698 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8700 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8701 if( pItem && pItem->GetEntry() == item )
8703 tempcount += pItem->GetCount();
8704 if( tempcount >= count )
8705 return true;
8708 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8710 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8712 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8714 Item* pItem = GetItemByPos( i, j );
8715 if( pItem && pItem->GetEntry() == item )
8717 tempcount += pItem->GetCount();
8718 if( tempcount >= count )
8719 return true;
8725 if(inBankAlso)
8727 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8729 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8730 if( pItem && pItem->GetEntry() == item )
8732 tempcount += pItem->GetCount();
8733 if( tempcount >= count )
8734 return true;
8737 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8739 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8741 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8743 Item* pItem = GetItemByPos( i, j );
8744 if( pItem && pItem->GetEntry() == item )
8746 tempcount += pItem->GetCount();
8747 if( tempcount >= count )
8748 return true;
8755 return false;
8758 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8760 uint32 tempcount = 0;
8761 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8763 if(i==int(except_slot))
8764 continue;
8766 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8767 if( pItem && pItem->GetEntry() == item)
8769 tempcount += pItem->GetCount();
8770 if( tempcount >= count )
8771 return true;
8775 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8776 if (pProto && pProto->GemProperties)
8778 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8780 if(i==int(except_slot))
8781 continue;
8783 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8784 if( pItem && pItem->GetProto()->Socket[0].Color)
8786 tempcount += pItem->GetGemCountWithID(item);
8787 if( tempcount >= count )
8788 return true;
8793 return false;
8796 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8798 uint32 tempcount = 0;
8799 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8801 if(i==int(except_slot))
8802 continue;
8804 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8805 if (!pItem)
8806 continue;
8808 ItemPrototype const *pProto = pItem->GetProto();
8809 if (!pProto)
8810 continue;
8812 if (pProto->ItemLimitCategory == limitCategory)
8814 tempcount += pItem->GetCount();
8815 if( tempcount >= count )
8816 return true;
8819 if( pProto->Socket[0].Color)
8821 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8822 if( tempcount >= count )
8823 return true;
8827 return false;
8830 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8832 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8833 if( !pProto )
8835 if(no_space_count)
8836 *no_space_count = count;
8837 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8840 // no maximum
8841 if(pProto->MaxCount <= 0)
8842 return EQUIP_ERR_OK;
8844 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8846 if (curcount + count > uint32(pProto->MaxCount))
8848 if(no_space_count)
8849 *no_space_count = count +curcount - pProto->MaxCount;
8850 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8853 return EQUIP_ERR_OK;
8856 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8858 Item *pItem;
8859 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8861 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8862 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8863 return true;
8865 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8867 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8868 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8869 return true;
8871 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8873 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8875 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8877 pItem = GetItemByPos( i, j );
8878 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8879 return true;
8883 return false;
8886 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8888 Item* pItem2 = GetItemByPos( bag, slot );
8890 // ignore move item (this slot will be empty at move)
8891 if(pItem2==pSrcItem)
8892 pItem2 = NULL;
8894 uint32 need_space;
8896 // empty specific slot - check item fit to slot
8897 if( !pItem2 || swap )
8899 if( bag == INVENTORY_SLOT_BAG_0 )
8901 // keyring case
8902 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8903 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8905 // vanitypet case (not use, vanity pets stored as spells)
8906 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8907 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8909 // currencytoken case (disabled until proper implement)
8910 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8911 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8913 // guestbag case (disabled until proper implement)
8914 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8915 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8917 // prevent cheating
8918 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8919 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8921 else
8923 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8924 if( !pBag )
8925 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8927 ItemPrototype const* pBagProto = pBag->GetProto();
8928 if( !pBagProto )
8929 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8931 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8932 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8935 // non empty stack with space
8936 need_space = pProto->GetMaxStackSize();
8938 // non empty slot, check item type
8939 else
8941 // check item type
8942 if(pItem2->GetEntry() != pProto->ItemId)
8943 return EQUIP_ERR_ITEM_CANT_STACK;
8945 // check free space
8946 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8947 return EQUIP_ERR_ITEM_CANT_STACK;
8949 // free stack space or infinity
8950 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8953 if(need_space > count)
8954 need_space = count;
8956 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8957 if(!newPosition.isContainedIn(dest))
8959 dest.push_back(newPosition);
8960 count -= need_space;
8962 return EQUIP_ERR_OK;
8965 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
8967 // skip specific bag already processed in first called _CanStoreItem_InBag
8968 if(bag==skip_bag)
8969 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8971 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8972 if( !pBag )
8973 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8975 ItemPrototype const* pBagProto = pBag->GetProto();
8976 if( !pBagProto )
8977 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8979 // specialized bag mode or non-specilized
8980 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8981 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8983 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8984 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8986 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8988 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8989 if(j==skip_slot)
8990 continue;
8992 Item* pItem2 = GetItemByPos( bag, j );
8994 // ignore move item (this slot will be empty at move)
8995 if(pItem2==pSrcItem)
8996 pItem2 = NULL;
8998 // if merge skip empty, if !merge skip non-empty
8999 if((pItem2!=NULL)!=merge)
9000 continue;
9002 if( pItem2 )
9004 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9006 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9007 if(need_space > count)
9008 need_space = count;
9010 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9011 if(!newPosition.isContainedIn(dest))
9013 dest.push_back(newPosition);
9014 count -= need_space;
9016 if(count==0)
9017 return EQUIP_ERR_OK;
9021 else
9023 uint32 need_space = pProto->GetMaxStackSize();
9024 if(need_space > count)
9025 need_space = count;
9027 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9028 if(!newPosition.isContainedIn(dest))
9030 dest.push_back(newPosition);
9031 count -= need_space;
9033 if(count==0)
9034 return EQUIP_ERR_OK;
9038 return EQUIP_ERR_OK;
9041 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
9043 for(uint32 j = slot_begin; j < slot_end; j++)
9045 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9046 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9047 continue;
9049 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9051 // ignore move item (this slot will be empty at move)
9052 if(pItem2==pSrcItem)
9053 pItem2 = NULL;
9055 // if merge skip empty, if !merge skip non-empty
9056 if((pItem2!=NULL)!=merge)
9057 continue;
9059 if( pItem2 )
9061 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9063 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9064 if(need_space > count)
9065 need_space = count;
9066 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9067 if(!newPosition.isContainedIn(dest))
9069 dest.push_back(newPosition);
9070 count -= need_space;
9072 if(count==0)
9073 return EQUIP_ERR_OK;
9077 else
9079 uint32 need_space = pProto->GetMaxStackSize();
9080 if(need_space > count)
9081 need_space = count;
9083 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9084 if(!newPosition.isContainedIn(dest))
9086 dest.push_back(newPosition);
9087 count -= need_space;
9089 if(count==0)
9090 return EQUIP_ERR_OK;
9094 return EQUIP_ERR_OK;
9097 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9099 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9101 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9102 if( !pProto )
9104 if(no_space_count)
9105 *no_space_count = count;
9106 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9109 if(pItem && pItem->IsBindedNotWith(GetGUID()))
9111 if(no_space_count)
9112 *no_space_count = count;
9113 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9116 // check count of items (skip for auto move for same player from bank)
9117 uint32 no_similar_count = 0; // can't store this amount similar items
9118 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9119 if(res!=EQUIP_ERR_OK)
9121 if(count==no_similar_count)
9123 if(no_space_count)
9124 *no_space_count = no_similar_count;
9125 return res;
9127 count -= no_similar_count;
9130 // in specific slot
9131 if( bag != NULL_BAG && slot != NULL_SLOT )
9133 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9134 if(res!=EQUIP_ERR_OK)
9136 if(no_space_count)
9137 *no_space_count = count + no_similar_count;
9138 return res;
9141 if(count==0)
9143 if(no_similar_count==0)
9144 return EQUIP_ERR_OK;
9146 if(no_space_count)
9147 *no_space_count = count + no_similar_count;
9148 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9152 // not specific slot or have space for partly store only in specific slot
9154 // in specific bag
9155 if( bag != NULL_BAG )
9157 // search stack in bag for merge to
9158 if( pProto->Stackable != 1 )
9160 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9162 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9163 if(res!=EQUIP_ERR_OK)
9165 if(no_space_count)
9166 *no_space_count = count + no_similar_count;
9167 return res;
9170 if(count==0)
9172 if(no_similar_count==0)
9173 return EQUIP_ERR_OK;
9175 if(no_space_count)
9176 *no_space_count = count + no_similar_count;
9177 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9180 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9181 if(res!=EQUIP_ERR_OK)
9183 if(no_space_count)
9184 *no_space_count = count + no_similar_count;
9185 return res;
9188 if(count==0)
9190 if(no_similar_count==0)
9191 return EQUIP_ERR_OK;
9193 if(no_space_count)
9194 *no_space_count = count + no_similar_count;
9195 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9198 else // equipped bag
9200 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9201 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9202 if(res!=EQUIP_ERR_OK)
9203 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9205 if(res!=EQUIP_ERR_OK)
9207 if(no_space_count)
9208 *no_space_count = count + no_similar_count;
9209 return res;
9212 if(count==0)
9214 if(no_similar_count==0)
9215 return EQUIP_ERR_OK;
9217 if(no_space_count)
9218 *no_space_count = count + no_similar_count;
9219 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9224 // search free slot in bag for place to
9225 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9227 // search free slot - keyring case
9228 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9230 uint32 keyringSize = GetMaxKeyringSize();
9231 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9232 if(res!=EQUIP_ERR_OK)
9234 if(no_space_count)
9235 *no_space_count = count + no_similar_count;
9236 return res;
9239 if(count==0)
9241 if(no_similar_count==0)
9242 return EQUIP_ERR_OK;
9244 if(no_space_count)
9245 *no_space_count = count + no_similar_count;
9246 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9250 // Vanity pet case skipped as not used
9252 /* until proper implementation
9253 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9255 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9256 if(res!=EQUIP_ERR_OK)
9258 if(no_space_count)
9259 *no_space_count = count + no_similar_count;
9260 return res;
9263 if(count==0)
9265 if(no_similar_count==0)
9266 return EQUIP_ERR_OK;
9268 if(no_space_count)
9269 *no_space_count = count + no_similar_count;
9270 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9274 /* until proper implementation
9275 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9277 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9278 if(res!=EQUIP_ERR_OK)
9280 if(no_space_count)
9281 *no_space_count = count + no_similar_count;
9282 return res;
9285 if(count==0)
9287 if(no_similar_count==0)
9288 return EQUIP_ERR_OK;
9290 if(no_space_count)
9291 *no_space_count = count + no_similar_count;
9292 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9297 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9298 if(res!=EQUIP_ERR_OK)
9300 if(no_space_count)
9301 *no_space_count = count + no_similar_count;
9302 return res;
9305 if(count==0)
9307 if(no_similar_count==0)
9308 return EQUIP_ERR_OK;
9310 if(no_space_count)
9311 *no_space_count = count + no_similar_count;
9312 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9315 else // equipped bag
9317 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9318 if(res!=EQUIP_ERR_OK)
9319 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9321 if(res!=EQUIP_ERR_OK)
9323 if(no_space_count)
9324 *no_space_count = count + no_similar_count;
9325 return res;
9328 if(count==0)
9330 if(no_similar_count==0)
9331 return EQUIP_ERR_OK;
9333 if(no_space_count)
9334 *no_space_count = count + no_similar_count;
9335 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9340 // not specific bag or have space for partly store only in specific bag
9342 // search stack for merge to
9343 if( pProto->Stackable != 1 )
9345 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9346 if(res!=EQUIP_ERR_OK)
9348 if(no_space_count)
9349 *no_space_count = count + no_similar_count;
9350 return res;
9353 if(count==0)
9355 if(no_similar_count==0)
9356 return EQUIP_ERR_OK;
9358 if(no_space_count)
9359 *no_space_count = count + no_similar_count;
9360 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9363 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9364 if(res!=EQUIP_ERR_OK)
9366 if(no_space_count)
9367 *no_space_count = count + no_similar_count;
9368 return res;
9371 if(count==0)
9373 if(no_similar_count==0)
9374 return EQUIP_ERR_OK;
9376 if(no_space_count)
9377 *no_space_count = count + no_similar_count;
9378 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9381 if( pProto->BagFamily )
9383 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9385 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9386 if(res!=EQUIP_ERR_OK)
9387 continue;
9389 if(count==0)
9391 if(no_similar_count==0)
9392 return EQUIP_ERR_OK;
9394 if(no_space_count)
9395 *no_space_count = count + no_similar_count;
9396 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9401 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9403 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9404 if(res!=EQUIP_ERR_OK)
9405 continue;
9407 if(count==0)
9409 if(no_similar_count==0)
9410 return EQUIP_ERR_OK;
9412 if(no_space_count)
9413 *no_space_count = count + no_similar_count;
9414 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9419 // search free slot - special bag case
9420 if( pProto->BagFamily )
9422 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9424 uint32 keyringSize = GetMaxKeyringSize();
9425 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9426 if(res!=EQUIP_ERR_OK)
9428 if(no_space_count)
9429 *no_space_count = count + no_similar_count;
9430 return res;
9433 if(count==0)
9435 if(no_similar_count==0)
9436 return EQUIP_ERR_OK;
9438 if(no_space_count)
9439 *no_space_count = count + no_similar_count;
9440 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9444 // Vanity pet case skipped as not used
9446 /* until proper implementation
9447 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9449 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9450 if(res!=EQUIP_ERR_OK)
9452 if(no_space_count)
9453 *no_space_count = count + no_similar_count;
9454 return res;
9457 if(count==0)
9459 if(no_similar_count==0)
9460 return EQUIP_ERR_OK;
9462 if(no_space_count)
9463 *no_space_count = count + no_similar_count;
9464 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9468 /* until proper implementation
9469 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9471 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9472 if(res!=EQUIP_ERR_OK)
9474 if(no_space_count)
9475 *no_space_count = count + no_similar_count;
9476 return res;
9479 if(count==0)
9481 if(no_similar_count==0)
9482 return EQUIP_ERR_OK;
9484 if(no_space_count)
9485 *no_space_count = count + no_similar_count;
9486 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9491 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9493 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9494 if(res!=EQUIP_ERR_OK)
9495 continue;
9497 if(count==0)
9499 if(no_similar_count==0)
9500 return EQUIP_ERR_OK;
9502 if(no_space_count)
9503 *no_space_count = count + no_similar_count;
9504 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9509 // search free slot
9510 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9511 if(res!=EQUIP_ERR_OK)
9513 if(no_space_count)
9514 *no_space_count = count + no_similar_count;
9515 return res;
9518 if(count==0)
9520 if(no_similar_count==0)
9521 return EQUIP_ERR_OK;
9523 if(no_space_count)
9524 *no_space_count = count + no_similar_count;
9525 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9528 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9530 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9531 if(res!=EQUIP_ERR_OK)
9532 continue;
9534 if(count==0)
9536 if(no_similar_count==0)
9537 return EQUIP_ERR_OK;
9539 if(no_space_count)
9540 *no_space_count = count + no_similar_count;
9541 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9545 if(no_space_count)
9546 *no_space_count = count + no_similar_count;
9548 return EQUIP_ERR_INVENTORY_FULL;
9551 //////////////////////////////////////////////////////////////////////////
9552 uint8 Player::CanStoreItems( Item **pItems,int count) const
9554 Item *pItem2;
9556 // fill space table
9557 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9558 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9559 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9560 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9561 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9563 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9564 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9565 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9566 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9567 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9569 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9571 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9573 if (pItem2 && !pItem2->IsInTrade())
9575 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9579 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9581 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9583 if (pItem2 && !pItem2->IsInTrade())
9585 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9589 // Vanity pet case skipped as not used
9591 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9593 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9595 if (pItem2 && !pItem2->IsInTrade())
9597 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9601 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9603 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9605 if (pItem2 && !pItem2->IsInTrade())
9607 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9611 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9613 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9615 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9617 pItem2 = GetItemByPos( i, j );
9618 if (pItem2 && !pItem2->IsInTrade())
9620 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9626 // check free space for all items
9627 for (int k=0;k<count;k++)
9629 Item *pItem = pItems[k];
9631 // no item
9632 if (!pItem) continue;
9634 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9635 ItemPrototype const *pProto = pItem->GetProto();
9637 // strange item
9638 if( !pProto )
9639 return EQUIP_ERR_ITEM_NOT_FOUND;
9641 // item it 'bind'
9642 if(pItem->IsBindedNotWith(GetGUID()))
9643 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9645 Bag *pBag;
9646 ItemPrototype const *pBagProto;
9648 // item is 'one item only'
9649 uint8 res = CanTakeMoreSimilarItems(pItem);
9650 if(res != EQUIP_ERR_OK)
9651 return res;
9653 // search stack for merge to
9654 if( pProto->Stackable != 1 )
9656 bool b_found = false;
9658 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9660 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9661 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9663 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9664 b_found = true;
9665 break;
9668 if (b_found) continue;
9670 // Vanity pet case skipped as not used
9672 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9674 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9675 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9677 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9678 b_found = true;
9679 break;
9682 if (b_found) continue;
9684 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9686 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9687 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9689 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9690 b_found = true;
9691 break;
9694 if (b_found) continue;
9696 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9698 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9699 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9701 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9702 b_found = true;
9703 break;
9706 if (b_found) continue;
9708 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9710 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9711 if( pBag )
9713 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9715 pItem2 = GetItemByPos( t, j );
9716 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9718 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9719 b_found = true;
9720 break;
9725 if (b_found) continue;
9728 // special bag case
9729 if( pProto->BagFamily )
9731 bool b_found = false;
9732 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9734 uint32 keyringSize = GetMaxKeyringSize();
9735 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9737 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9739 inv_keys[t-KEYRING_SLOT_START] = 1;
9740 b_found = true;
9741 break;
9746 if (b_found) continue;
9748 // Vanity pet case skipped as not used
9750 /* until proper implementation
9751 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9753 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9755 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9757 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9758 b_found = true;
9759 break;
9764 if (b_found) continue;
9766 /* until proper implementation
9767 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9769 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9771 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9773 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9774 b_found = true;
9775 break;
9780 if (b_found) continue;
9783 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9785 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9786 if( pBag )
9788 pBagProto = pBag->GetProto();
9790 // not plain container check
9791 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9792 ItemCanGoIntoBag(pProto,pBagProto) )
9794 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9796 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9798 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9799 b_found = true;
9800 break;
9806 if (b_found) continue;
9809 // search free slot
9810 bool b_found = false;
9811 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9813 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9815 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9816 b_found = true;
9817 break;
9820 if (b_found) continue;
9822 // search free slot in bags
9823 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9825 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9826 if( pBag )
9828 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9830 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9832 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9833 b_found = true;
9834 break;
9840 // no free slot found?
9841 if (!b_found)
9842 return EQUIP_ERR_INVENTORY_FULL;
9845 return EQUIP_ERR_OK;
9848 //////////////////////////////////////////////////////////////////////////
9849 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9851 dest = 0;
9852 Item *pItem = Item::CreateItem( item, 1, this );
9853 if( pItem )
9855 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9856 delete pItem;
9857 return result;
9860 return EQUIP_ERR_ITEM_NOT_FOUND;
9863 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9865 dest = 0;
9866 if( pItem )
9868 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9869 ItemPrototype const *pProto = pItem->GetProto();
9870 if( pProto )
9872 if(pItem->IsBindedNotWith(GetGUID()))
9873 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9875 // check count of items (skip for auto move for same player from bank)
9876 uint8 res = CanTakeMoreSimilarItems(pItem);
9877 if(res != EQUIP_ERR_OK)
9878 return res;
9880 // check this only in game
9881 if(not_loading)
9883 // May be here should be more stronger checks; STUNNED checked
9884 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9885 if (hasUnitState(UNIT_STAT_STUNNED))
9886 return EQUIP_ERR_YOU_ARE_STUNNED;
9888 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9889 // - combat
9890 // - in-progress arenas
9891 if( !pProto->CanChangeEquipStateInCombat() )
9893 if( isInCombat() )
9894 return EQUIP_ERR_NOT_IN_COMBAT;
9896 if(BattleGround* bg = GetBattleGround())
9897 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9898 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9901 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9902 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9904 if(IsNonMeleeSpellCasted(false))
9905 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9908 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9909 if( eslot == NULL_SLOT )
9910 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9912 uint8 msg = CanUseItem( pItem , not_loading );
9913 if( msg != EQUIP_ERR_OK )
9914 return msg;
9915 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9916 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9918 // if swap ignore item (equipped also)
9919 if(uint8 res = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9920 return res;
9922 // check unique-equipped special item classes
9923 if (pProto->Class == ITEM_CLASS_QUIVER)
9925 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9927 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9929 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9931 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9932 (!swap || pBag->GetSlot() != eslot ) )
9934 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9935 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9936 else
9937 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9944 uint32 type = pProto->InventoryType;
9946 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9948 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9950 if(!CanDualWield())
9951 return EQUIP_ERR_CANT_DUAL_WIELD;
9953 else if (type == INVTYPE_2HWEAPON)
9955 if(!CanDualWield() || !CanTitanGrip())
9956 return EQUIP_ERR_CANT_DUAL_WIELD;
9959 if(IsTwoHandUsed())
9960 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9963 // equip two-hand weapon case (with possible unequip 2 items)
9964 if( type == INVTYPE_2HWEAPON )
9966 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9968 if (!CanTitanGrip())
9969 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9971 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9972 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9974 if (!CanTitanGrip())
9976 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9977 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9978 ItemPosCountVec off_dest;
9979 if( offItem && (!not_loading ||
9980 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9981 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9982 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9985 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9986 return EQUIP_ERR_OK;
9989 if( !swap )
9990 return EQUIP_ERR_ITEM_NOT_FOUND;
9991 else
9992 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9995 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9997 // Applied only to equipped items and bank bags
9998 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9999 return EQUIP_ERR_OK;
10001 Item* pItem = GetItemByPos(pos);
10003 // Applied only to existed equipped item
10004 if( !pItem )
10005 return EQUIP_ERR_OK;
10007 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10009 ItemPrototype const *pProto = pItem->GetProto();
10010 if( !pProto )
10011 return EQUIP_ERR_ITEM_NOT_FOUND;
10013 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10014 // - combat
10015 // - in-progress arenas
10016 if( !pProto->CanChangeEquipStateInCombat() )
10018 if( isInCombat() )
10019 return EQUIP_ERR_NOT_IN_COMBAT;
10021 if(BattleGround* bg = GetBattleGround())
10022 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10023 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10026 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10027 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10029 return EQUIP_ERR_OK;
10032 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10034 if( !pItem )
10035 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10037 uint32 count = pItem->GetCount();
10039 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10040 ItemPrototype const *pProto = pItem->GetProto();
10041 if( !pProto )
10042 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10044 if( pItem->IsBindedNotWith(GetGUID()) )
10045 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10047 // check count of items (skip for auto move for same player from bank)
10048 uint8 res = CanTakeMoreSimilarItems(pItem);
10049 if(res != EQUIP_ERR_OK)
10050 return res;
10052 // in specific slot
10053 if( bag != NULL_BAG && slot != NULL_SLOT )
10055 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10057 if (!pItem->IsBag())
10058 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10060 Bag *pBag = (Bag*)pItem;
10061 if( !HasBankBagSlot( slot ) )
10062 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10064 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
10065 return cantuse;
10068 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10069 if(res!=EQUIP_ERR_OK)
10070 return res;
10072 if(count==0)
10073 return EQUIP_ERR_OK;
10076 // not specific slot or have space for partly store only in specific slot
10078 // in specific bag
10079 if( bag != NULL_BAG )
10081 if( pProto->InventoryType == INVTYPE_BAG )
10083 Bag *pBag = (Bag*)pItem;
10084 if( pBag && !pBag->IsEmpty() )
10085 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10088 // search stack in bag for merge to
10089 if( pProto->Stackable != 1 )
10091 if( bag == INVENTORY_SLOT_BAG_0 )
10093 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10094 if(res!=EQUIP_ERR_OK)
10095 return res;
10097 if(count==0)
10098 return EQUIP_ERR_OK;
10100 else
10102 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10103 if(res!=EQUIP_ERR_OK)
10104 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10106 if(res!=EQUIP_ERR_OK)
10107 return res;
10109 if(count==0)
10110 return EQUIP_ERR_OK;
10114 // search free slot in bag
10115 if( bag == INVENTORY_SLOT_BAG_0 )
10117 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10118 if(res!=EQUIP_ERR_OK)
10119 return res;
10121 if(count==0)
10122 return EQUIP_ERR_OK;
10124 else
10126 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10127 if(res!=EQUIP_ERR_OK)
10128 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10130 if(res!=EQUIP_ERR_OK)
10131 return res;
10133 if(count==0)
10134 return EQUIP_ERR_OK;
10138 // not specific bag or have space for partly store only in specific bag
10140 // search stack for merge to
10141 if( pProto->Stackable != 1 )
10143 // in slots
10144 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10145 if(res!=EQUIP_ERR_OK)
10146 return res;
10148 if(count==0)
10149 return EQUIP_ERR_OK;
10151 // in special bags
10152 if( pProto->BagFamily )
10154 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10156 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10157 if(res!=EQUIP_ERR_OK)
10158 continue;
10160 if(count==0)
10161 return EQUIP_ERR_OK;
10165 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10167 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10168 if(res!=EQUIP_ERR_OK)
10169 continue;
10171 if(count==0)
10172 return EQUIP_ERR_OK;
10176 // search free place in special bag
10177 if( pProto->BagFamily )
10179 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10181 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10182 if(res!=EQUIP_ERR_OK)
10183 continue;
10185 if(count==0)
10186 return EQUIP_ERR_OK;
10190 // search free space
10191 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10192 if(res!=EQUIP_ERR_OK)
10193 return res;
10195 if(count==0)
10196 return EQUIP_ERR_OK;
10198 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10200 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10201 if(res!=EQUIP_ERR_OK)
10202 continue;
10204 if(count==0)
10205 return EQUIP_ERR_OK;
10207 return EQUIP_ERR_BANK_FULL;
10210 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10212 if( pItem )
10214 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10215 if( !isAlive() && not_loading )
10216 return EQUIP_ERR_YOU_ARE_DEAD;
10217 //if( isStunned() )
10218 // return EQUIP_ERR_YOU_ARE_STUNNED;
10219 ItemPrototype const *pProto = pItem->GetProto();
10220 if( pProto )
10222 if( pItem->IsBindedNotWith(GetGUID()) )
10223 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10224 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10225 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10226 if( pItem->GetSkill() != 0 )
10228 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10229 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10231 if( pProto->RequiredSkill != 0 )
10233 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10234 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10235 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10236 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10238 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10239 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10240 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10241 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10242 if( getLevel() < pProto->RequiredLevel )
10243 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10244 return EQUIP_ERR_OK;
10247 return EQUIP_ERR_ITEM_NOT_FOUND;
10250 bool Player::CanUseItem( ItemPrototype const *pProto )
10252 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10254 if( pProto )
10256 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10257 return false;
10258 if( pProto->RequiredSkill != 0 )
10260 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10261 return false;
10262 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10263 return false;
10265 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10266 return false;
10267 if( getLevel() < pProto->RequiredLevel )
10268 return false;
10269 return true;
10271 return false;
10274 uint8 Player::CanUseAmmo( uint32 item ) const
10276 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10277 if( !isAlive() )
10278 return EQUIP_ERR_YOU_ARE_DEAD;
10279 //if( isStunned() )
10280 // return EQUIP_ERR_YOU_ARE_STUNNED;
10281 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10282 if( pProto )
10284 if( pProto->InventoryType!= INVTYPE_AMMO )
10285 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10286 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10287 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10288 if( pProto->RequiredSkill != 0 )
10290 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10291 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10292 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10293 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10295 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10296 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10297 /*if( GetReputation() < pProto->RequiredReputation )
10298 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10300 if( getLevel() < pProto->RequiredLevel )
10301 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10303 // Requires No Ammo
10304 if(GetDummyAura(46699))
10305 return EQUIP_ERR_BAG_FULL6;
10307 return EQUIP_ERR_OK;
10309 return EQUIP_ERR_ITEM_NOT_FOUND;
10312 void Player::SetAmmo( uint32 item )
10314 if(!item)
10315 return;
10317 // already set
10318 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10319 return;
10321 // check ammo
10322 if(item)
10324 uint8 msg = CanUseAmmo( item );
10325 if( msg != EQUIP_ERR_OK )
10327 SendEquipError( msg, NULL, NULL );
10328 return;
10332 SetUInt32Value(PLAYER_AMMO_ID, item);
10334 _ApplyAmmoBonuses();
10337 void Player::RemoveAmmo()
10339 SetUInt32Value(PLAYER_AMMO_ID, 0);
10341 m_ammoDPS = 0.0f;
10343 if(CanModifyStats())
10344 UpdateDamagePhysical(RANGED_ATTACK);
10347 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10348 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10350 uint32 count = 0;
10351 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10352 count += itr->count;
10354 Item *pItem = Item::CreateItem( item, count, this );
10355 if( pItem )
10357 ItemAddedQuestCheck( item, count );
10358 if(randomPropertyId)
10359 pItem->SetItemRandomProperties(randomPropertyId);
10360 pItem = StoreItem( dest, pItem, update );
10362 return pItem;
10365 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10367 if( !pItem )
10368 return NULL;
10370 Item* lastItem = pItem;
10372 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10374 uint16 pos = itr->pos;
10375 uint32 count = itr->count;
10377 ++itr;
10379 if(itr == dest.end())
10381 lastItem = _StoreItem(pos,pItem,count,false,update);
10382 break;
10385 lastItem = _StoreItem(pos,pItem,count,true,update);
10388 return lastItem;
10391 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10392 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10394 if( !pItem )
10395 return NULL;
10397 uint8 bag = pos >> 8;
10398 uint8 slot = pos & 255;
10400 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10402 Item *pItem2 = GetItemByPos( bag, slot );
10404 if( !pItem2 )
10406 if(clone)
10407 pItem = pItem->CloneItem(count,this);
10408 else
10409 pItem->SetCount(count);
10411 if(!pItem)
10412 return NULL;
10414 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10415 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10416 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10417 pItem->SetBinding( true );
10419 if( bag == INVENTORY_SLOT_BAG_0 )
10421 m_items[slot] = pItem;
10422 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10423 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10424 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10426 pItem->SetSlot( slot );
10427 pItem->SetContainer( NULL );
10429 if( IsInWorld() && update )
10431 pItem->AddToWorld();
10432 pItem->SendUpdateToPlayer( this );
10435 pItem->SetState(ITEM_CHANGED, this);
10437 else
10439 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10440 if( pBag )
10442 pBag->StoreItem( slot, pItem, update );
10443 if( IsInWorld() && update )
10445 pItem->AddToWorld();
10446 pItem->SendUpdateToPlayer( this );
10448 pItem->SetState(ITEM_CHANGED, this);
10449 pBag->SetState(ITEM_CHANGED, this);
10453 AddEnchantmentDurations(pItem);
10454 AddItemDurations(pItem);
10456 return pItem;
10458 else
10460 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10461 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10462 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10463 pItem2->SetBinding( true );
10465 pItem2->SetCount( pItem2->GetCount() + count );
10466 if( IsInWorld() && update )
10467 pItem2->SendUpdateToPlayer( this );
10469 if(!clone)
10471 // delete item (it not in any slot currently)
10472 if( IsInWorld() && update )
10474 pItem->RemoveFromWorld();
10475 pItem->DestroyForPlayer( this );
10478 RemoveEnchantmentDurations(pItem);
10479 RemoveItemDurations(pItem);
10481 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10482 pItem->SetState(ITEM_REMOVED, this);
10484 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10485 AddEnchantmentDurations(pItem2);
10487 pItem2->SetState(ITEM_CHANGED, this);
10489 return pItem2;
10493 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10495 Item *pItem = Item::CreateItem( item, 1, this );
10496 if( pItem )
10498 ItemAddedQuestCheck( item, 1 );
10499 Item * retItem = EquipItem( pos, pItem, update );
10501 return retItem;
10503 return NULL;
10506 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10508 if( pItem )
10510 AddEnchantmentDurations(pItem);
10511 AddItemDurations(pItem);
10513 uint8 bag = pos >> 8;
10514 uint8 slot = pos & 255;
10516 Item *pItem2 = GetItemByPos( bag, slot );
10518 if( !pItem2 )
10520 VisualizeItem( slot, pItem);
10522 if(isAlive())
10524 ItemPrototype const *pProto = pItem->GetProto();
10526 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10527 if(pProto && pProto->ItemSet)
10528 AddItemsSetItem(this,pItem);
10530 _ApplyItemMods(pItem, slot, true);
10532 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10534 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10536 if (getClass() == CLASS_ROGUE)
10537 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10539 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10541 if (!spellProto)
10542 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10543 else
10545 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10547 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10548 data << uint64(GetGUID());
10549 data << uint8(1);
10550 data << uint32(cooldownSpell);
10551 data << uint32(0);
10552 GetSession()->SendPacket(&data);
10557 if( IsInWorld() && update )
10559 pItem->AddToWorld();
10560 pItem->SendUpdateToPlayer( this );
10563 ApplyEquipCooldown(pItem);
10565 if( slot == EQUIPMENT_SLOT_MAINHAND )
10566 UpdateExpertise(BASE_ATTACK);
10567 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10568 UpdateExpertise(OFF_ATTACK);
10570 else
10572 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10573 if( IsInWorld() && update )
10574 pItem2->SendUpdateToPlayer( this );
10576 // delete item (it not in any slot currently)
10577 //pItem->DeleteFromDB();
10578 if( IsInWorld() && update )
10580 pItem->RemoveFromWorld();
10581 pItem->DestroyForPlayer( this );
10584 RemoveEnchantmentDurations(pItem);
10585 RemoveItemDurations(pItem);
10587 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10588 pItem->SetState(ITEM_REMOVED, this);
10589 pItem2->SetState(ITEM_CHANGED, this);
10591 ApplyEquipCooldown(pItem2);
10593 return pItem2;
10597 return pItem;
10600 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10602 if( pItem )
10604 AddEnchantmentDurations(pItem);
10605 AddItemDurations(pItem);
10607 uint8 slot = pos & 255;
10608 VisualizeItem( slot, pItem);
10610 if( IsInWorld() )
10612 pItem->AddToWorld();
10613 pItem->SendUpdateToPlayer( this );
10618 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10620 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10621 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10622 // entry // Size: 1
10623 // inspected enchantments // Size: 6
10624 // ? // Size: 5
10625 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10626 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10627 // // = 16
10629 if(pItem)
10631 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10633 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10634 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10636 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10637 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10639 // Use SetInt16Value to prevent set high part to FFFF for negative value
10640 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10641 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10643 else
10645 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10647 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10648 SetUInt32Value(VisibleBase + 0, 0);
10650 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10651 SetUInt32Value(VisibleBase + 1 + i, 0);
10653 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10654 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10658 void Player::VisualizeItem( uint8 slot, Item *pItem)
10660 if(!pItem)
10661 return;
10663 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10664 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10665 pItem->SetBinding( true );
10667 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10669 m_items[slot] = pItem;
10670 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10671 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10672 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10673 pItem->SetSlot( slot );
10674 pItem->SetContainer( NULL );
10676 if( slot < EQUIPMENT_SLOT_END )
10677 SetVisibleItemSlot(slot,pItem);
10679 pItem->SetState(ITEM_CHANGED, this);
10682 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10684 // note: removeitem does not actually change the item
10685 // it only takes the item out of storage temporarily
10686 // note2: if removeitem is to be used for delinking
10687 // the item must be removed from the player's updatequeue
10689 Item *pItem = GetItemByPos( bag, slot );
10690 if( pItem )
10692 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10694 RemoveEnchantmentDurations(pItem);
10695 RemoveItemDurations(pItem);
10697 if( bag == INVENTORY_SLOT_BAG_0 )
10699 if ( slot < INVENTORY_SLOT_BAG_END )
10701 ItemPrototype const *pProto = pItem->GetProto();
10702 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10704 if(pProto && pProto->ItemSet)
10705 RemoveItemsSetItem(this,pProto);
10707 _ApplyItemMods(pItem, slot, false);
10709 // remove item dependent auras and casts (only weapon and armor slots)
10710 if(slot < EQUIPMENT_SLOT_END)
10711 RemoveItemDependentAurasAndCasts(pItem);
10713 // remove held enchantments
10714 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10716 if (pItem->GetItemSuffixFactor())
10718 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10719 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10721 else
10723 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10724 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10729 m_items[slot] = NULL;
10730 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10732 if ( slot < EQUIPMENT_SLOT_END )
10733 SetVisibleItemSlot(slot,NULL);
10735 else
10737 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10738 if( pBag )
10739 pBag->RemoveItem(slot, update);
10741 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10742 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10743 pItem->SetSlot( NULL_SLOT );
10744 if( IsInWorld() && update )
10745 pItem->SendUpdateToPlayer( this );
10747 if( slot == EQUIPMENT_SLOT_MAINHAND )
10748 UpdateExpertise(BASE_ATTACK);
10749 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10750 UpdateExpertise(OFF_ATTACK);
10754 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10755 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10757 if(Item* it = GetItemByPos(bag,slot))
10759 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10760 RemoveItem( bag,slot,update);
10761 it->RemoveFromUpdateQueueOf(this);
10762 if(it->IsInWorld())
10764 it->RemoveFromWorld();
10765 it->DestroyForPlayer( this );
10770 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10771 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10773 // update quest counters
10774 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10776 // store item
10777 Item* pLastItem = StoreItem( dest, pItem, update);
10779 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10780 if(pLastItem==pItem)
10782 // update owner for last item (this can be original item with wrong owner
10783 if(pLastItem->GetOwnerGUID() != GetGUID())
10784 pLastItem->SetOwnerGUID(GetGUID());
10786 // if this original item then it need create record in inventory
10787 // in case trade we already have item in other player inventory
10788 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10792 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10794 Item *pItem = GetItemByPos( bag, slot );
10795 if( pItem )
10797 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10799 // start from destroy contained items (only equipped bag can have its)
10800 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10802 for (int i = 0; i < MAX_BAG_SIZE; i++)
10803 DestroyItem(slot,i,update);
10806 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10807 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10809 RemoveEnchantmentDurations(pItem);
10810 RemoveItemDurations(pItem);
10812 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10814 if( bag == INVENTORY_SLOT_BAG_0 )
10816 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10818 // equipment and equipped bags can have applied bonuses
10819 if ( slot < INVENTORY_SLOT_BAG_END )
10821 ItemPrototype const *pProto = pItem->GetProto();
10823 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10824 if(pProto && pProto->ItemSet)
10825 RemoveItemsSetItem(this,pProto);
10827 _ApplyItemMods(pItem, slot, false);
10830 if ( slot < EQUIPMENT_SLOT_END )
10832 // remove item dependent auras and casts (only weapon and armor slots)
10833 RemoveItemDependentAurasAndCasts(pItem);
10835 // equipment visual show
10836 SetVisibleItemSlot(slot,NULL);
10839 m_items[slot] = NULL;
10841 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10842 pBag->RemoveItem(slot, update);
10844 if( IsInWorld() && update )
10846 pItem->RemoveFromWorld();
10847 pItem->DestroyForPlayer(this);
10850 //pItem->SetOwnerGUID(0);
10851 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10852 pItem->SetSlot( NULL_SLOT );
10853 pItem->SetState(ITEM_REMOVED, this);
10857 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10859 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10860 Item *pItem;
10861 ItemPrototype const *pProto;
10862 uint32 remcount = 0;
10864 // in inventory
10865 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10867 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10868 if( pItem && pItem->GetEntry() == item )
10870 if( pItem->GetCount() + remcount <= count )
10872 // all items in inventory can unequipped
10873 remcount += pItem->GetCount();
10874 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10876 if(remcount >=count)
10877 return;
10879 else
10881 pProto = pItem->GetProto();
10882 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10883 pItem->SetCount( pItem->GetCount() - count + remcount );
10884 if( IsInWorld() & update )
10885 pItem->SendUpdateToPlayer( this );
10886 pItem->SetState(ITEM_CHANGED, this);
10887 return;
10891 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10893 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10894 if( pItem && pItem->GetEntry() == item )
10896 if( pItem->GetCount() + remcount <= count )
10898 // all keys can be unequipped
10899 remcount += pItem->GetCount();
10900 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10902 if(remcount >=count)
10903 return;
10905 else
10907 pProto = pItem->GetProto();
10908 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10909 pItem->SetCount( pItem->GetCount() - count + remcount );
10910 if( IsInWorld() & update )
10911 pItem->SendUpdateToPlayer( this );
10912 pItem->SetState(ITEM_CHANGED, this);
10913 return;
10918 // in inventory bags
10919 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10921 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10923 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10925 pItem = pBag->GetItemByPos(j);
10926 if( pItem && pItem->GetEntry() == item )
10928 // all items in bags can be unequipped
10929 if( pItem->GetCount() + remcount <= count )
10931 remcount += pItem->GetCount();
10932 DestroyItem( i, j, update );
10934 if(remcount >=count)
10935 return;
10937 else
10939 pProto = pItem->GetProto();
10940 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10941 pItem->SetCount( pItem->GetCount() - count + remcount );
10942 if( IsInWorld() && update )
10943 pItem->SendUpdateToPlayer( this );
10944 pItem->SetState(ITEM_CHANGED, this);
10945 return;
10952 // in equipment and bag list
10953 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10955 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10956 if( pItem && pItem->GetEntry() == item )
10958 if( pItem->GetCount() + remcount <= count )
10960 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10962 remcount += pItem->GetCount();
10963 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10965 if(remcount >=count)
10966 return;
10969 else
10971 pProto = pItem->GetProto();
10972 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10973 pItem->SetCount( pItem->GetCount() - count + remcount );
10974 if( IsInWorld() & update )
10975 pItem->SendUpdateToPlayer( this );
10976 pItem->SetState(ITEM_CHANGED, this);
10977 return;
10983 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10985 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10987 // in inventory
10988 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10990 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10991 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10992 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10994 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10996 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10997 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10998 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11001 // in inventory bags
11002 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11004 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11005 if( pBag )
11007 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11009 Item* pItem = pBag->GetItemByPos(j);
11010 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11011 DestroyItem( i, j, update);
11016 // in equipment and bag list
11017 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11019 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11020 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11021 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11025 void Player::DestroyConjuredItems( bool update )
11027 // used when entering arena
11028 // destroys all conjured items
11029 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11031 // in inventory
11032 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11034 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11035 if( pItem && pItem->GetProto() &&
11036 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11037 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11038 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11041 // in inventory bags
11042 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11044 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11045 if( pBag )
11047 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11049 Item* pItem = pBag->GetItemByPos(j);
11050 if( pItem && pItem->GetProto() &&
11051 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11052 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11053 DestroyItem( i, j, update);
11058 // in equipment and bag list
11059 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11061 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11062 if( pItem && pItem->GetProto() &&
11063 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11064 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11065 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11069 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11071 if(!pItem)
11072 return;
11074 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11076 if( pItem->GetCount() <= count )
11078 count-= pItem->GetCount();
11080 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11082 else
11084 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11085 pItem->SetCount( pItem->GetCount() - count );
11086 count = 0;
11087 if( IsInWorld() & update )
11088 pItem->SendUpdateToPlayer( this );
11089 pItem->SetState(ITEM_CHANGED, this);
11093 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11095 uint8 srcbag = src >> 8;
11096 uint8 srcslot = src & 255;
11098 uint8 dstbag = dst >> 8;
11099 uint8 dstslot = dst & 255;
11101 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11102 if( !pSrcItem )
11104 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11105 return;
11108 // not let split all items (can be only at cheating)
11109 if(pSrcItem->GetCount() == count)
11111 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11112 return;
11115 // not let split more existed items (can be only at cheating)
11116 if(pSrcItem->GetCount() < count)
11118 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11119 return;
11122 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11124 //best error message found for attempting to split while looting
11125 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11126 return;
11129 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11130 Item *pNewItem = pSrcItem->CloneItem( count, this );
11131 if( !pNewItem )
11133 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11134 return;
11137 if( IsInventoryPos( dst ) )
11139 // change item amount before check (for unique max count check)
11140 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11142 ItemPosCountVec dest;
11143 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11144 if( msg != EQUIP_ERR_OK )
11146 delete pNewItem;
11147 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11148 SendEquipError( msg, pSrcItem, NULL );
11149 return;
11152 if( IsInWorld() )
11153 pSrcItem->SendUpdateToPlayer( this );
11154 pSrcItem->SetState(ITEM_CHANGED, this);
11155 StoreItem( dest, pNewItem, true);
11157 else if( IsBankPos ( dst ) )
11159 // change item amount before check (for unique max count check)
11160 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11162 ItemPosCountVec dest;
11163 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11164 if( msg != EQUIP_ERR_OK )
11166 delete pNewItem;
11167 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11168 SendEquipError( msg, pSrcItem, NULL );
11169 return;
11172 if( IsInWorld() )
11173 pSrcItem->SendUpdateToPlayer( this );
11174 pSrcItem->SetState(ITEM_CHANGED, this);
11175 BankItem( dest, pNewItem, true);
11177 else if( IsEquipmentPos ( dst ) )
11179 // change item amount before check (for unique max count check), provide space for splitted items
11180 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11182 uint16 dest;
11183 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11184 if( msg != EQUIP_ERR_OK )
11186 delete pNewItem;
11187 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11188 SendEquipError( msg, pSrcItem, NULL );
11189 return;
11192 if( IsInWorld() )
11193 pSrcItem->SendUpdateToPlayer( this );
11194 pSrcItem->SetState(ITEM_CHANGED, this);
11195 EquipItem( dest, pNewItem, true);
11196 AutoUnequipOffhandIfNeed();
11200 void Player::SwapItem( uint16 src, uint16 dst )
11202 uint8 srcbag = src >> 8;
11203 uint8 srcslot = src & 255;
11205 uint8 dstbag = dst >> 8;
11206 uint8 dstslot = dst & 255;
11208 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11209 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11211 if( !pSrcItem )
11212 return;
11214 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11216 if(!isAlive() )
11218 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11219 return;
11222 // SRC checks
11224 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11226 //best error message found for attempting to swap while looting
11227 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11228 return;
11231 // check unequip potability for equipped items and bank bags
11232 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11234 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11235 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11236 if(msg != EQUIP_ERR_OK)
11238 SendEquipError( msg, pSrcItem, pDstItem );
11239 return;
11243 // prevent put equipped/bank bag in self
11244 if( IsBagPos ( src ) && srcslot == dstbag)
11246 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11247 return;
11250 // DST checks
11252 if (pDstItem)
11254 if(pDstItem->m_lootGenerated) // prevent swap looting item
11256 //best error message found for attempting to swap while looting
11257 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11258 return;
11261 // check unequip potability for equipped items and bank bags
11262 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11264 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11265 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11266 if(msg != EQUIP_ERR_OK)
11268 SendEquipError( msg, pSrcItem, pDstItem );
11269 return;
11274 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11275 // or swap empty bag with another empty or not empty bag (with items exchange)
11277 // Move case
11278 if( !pDstItem )
11280 if( IsInventoryPos( dst ) )
11282 ItemPosCountVec dest;
11283 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11284 if( msg != EQUIP_ERR_OK )
11286 SendEquipError( msg, pSrcItem, NULL );
11287 return;
11290 RemoveItem(srcbag, srcslot, true);
11291 StoreItem( dest, pSrcItem, true);
11293 else if( IsBankPos ( dst ) )
11295 ItemPosCountVec dest;
11296 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11297 if( msg != EQUIP_ERR_OK )
11299 SendEquipError( msg, pSrcItem, NULL );
11300 return;
11303 RemoveItem(srcbag, srcslot, true);
11304 BankItem( dest, pSrcItem, true);
11306 else if( IsEquipmentPos ( dst ) )
11308 uint16 dest;
11309 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11310 if( msg != EQUIP_ERR_OK )
11312 SendEquipError( msg, pSrcItem, NULL );
11313 return;
11316 RemoveItem(srcbag, srcslot, true);
11317 EquipItem( dest, pSrcItem, true);
11318 AutoUnequipOffhandIfNeed();
11321 return;
11324 // attempt merge to / fill target item
11325 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11327 uint8 msg;
11328 ItemPosCountVec sDest;
11329 uint16 eDest;
11330 if( IsInventoryPos( dst ) )
11331 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11332 else if( IsBankPos ( dst ) )
11333 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11334 else if( IsEquipmentPos ( dst ) )
11335 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11336 else
11337 return;
11339 // can be merge/fill
11340 if(msg == EQUIP_ERR_OK)
11342 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11344 RemoveItem(srcbag, srcslot, true);
11346 if( IsInventoryPos( dst ) )
11347 StoreItem( sDest, pSrcItem, true);
11348 else if( IsBankPos ( dst ) )
11349 BankItem( sDest, pSrcItem, true);
11350 else if( IsEquipmentPos ( dst ) )
11352 EquipItem( eDest, pSrcItem, true);
11353 AutoUnequipOffhandIfNeed();
11356 else
11358 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11359 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11360 pSrcItem->SetState(ITEM_CHANGED, this);
11361 pDstItem->SetState(ITEM_CHANGED, this);
11362 if( IsInWorld() )
11364 pSrcItem->SendUpdateToPlayer( this );
11365 pDstItem->SendUpdateToPlayer( this );
11368 return;
11372 // impossible merge/fill, do real swap
11373 uint8 msg;
11375 // check src->dest move possibility
11376 ItemPosCountVec sDest;
11377 uint16 eDest;
11378 if( IsInventoryPos( dst ) )
11379 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11380 else if( IsBankPos( dst ) )
11381 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11382 else if( IsEquipmentPos( dst ) )
11384 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11385 if( msg == EQUIP_ERR_OK )
11386 msg = CanUnequipItem( eDest, true );
11389 if( msg != EQUIP_ERR_OK )
11391 SendEquipError( msg, pSrcItem, pDstItem );
11392 return;
11395 // check dest->src move possibility
11396 ItemPosCountVec sDest2;
11397 uint16 eDest2;
11398 if( IsInventoryPos( src ) )
11399 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11400 else if( IsBankPos( src ) )
11401 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11402 else if( IsEquipmentPos( src ) )
11404 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11405 if( msg == EQUIP_ERR_OK )
11406 msg = CanUnequipItem( eDest2, true);
11409 if( msg != EQUIP_ERR_OK )
11411 SendEquipError( msg, pDstItem, pSrcItem );
11412 return;
11415 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11416 if(pSrcItem->IsBag() && pDstItem->IsBag())
11418 Bag* emptyBag = NULL;
11419 Bag* fullBag = NULL;
11420 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11422 emptyBag = (Bag*)pSrcItem;
11423 fullBag = (Bag*)pDstItem;
11425 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11427 emptyBag = (Bag*)pDstItem;
11428 fullBag = (Bag*)pSrcItem;
11431 // bag swap (with items exchange) case
11432 if(emptyBag && fullBag)
11434 ItemPrototype const* emotyProto = emptyBag->GetProto();
11436 uint32 count = 0;
11438 for(int i=0; i < fullBag->GetBagSize(); ++i)
11440 Item *bagItem = fullBag->GetItemByPos(i);
11441 if (!bagItem)
11442 continue;
11444 ItemPrototype const* bagItemProto = bagItem->GetProto();
11445 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11447 // one from items not go to empry target bag
11448 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11449 return;
11452 ++count;
11456 if (count > emptyBag->GetBagSize())
11458 // too small targeted bag
11459 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11460 return;
11463 // Items swap
11464 count = 0; // will pos in new bag
11465 for(int i=0; i< fullBag->GetBagSize(); ++i)
11467 Item *bagItem = fullBag->GetItemByPos(i);
11468 if (!bagItem)
11469 continue;
11471 fullBag->RemoveItem(i, true);
11472 emptyBag->StoreItem(count, bagItem, true);
11473 bagItem->SetState(ITEM_CHANGED, this);
11475 ++count;
11480 // now do moves, remove...
11481 RemoveItem(dstbag, dstslot, false);
11482 RemoveItem(srcbag, srcslot, false);
11484 // add to dest
11485 if( IsInventoryPos( dst ) )
11486 StoreItem(sDest, pSrcItem, true);
11487 else if( IsBankPos( dst ) )
11488 BankItem(sDest, pSrcItem, true);
11489 else if( IsEquipmentPos( dst ) )
11490 EquipItem(eDest, pSrcItem, true);
11492 // add to src
11493 if( IsInventoryPos( src ) )
11494 StoreItem(sDest2, pDstItem, true);
11495 else if( IsBankPos( src ) )
11496 BankItem(sDest2, pDstItem, true);
11497 else if( IsEquipmentPos( src ) )
11498 EquipItem(eDest2, pDstItem, true);
11500 AutoUnequipOffhandIfNeed();
11503 void Player::AddItemToBuyBackSlot( Item *pItem )
11505 if( pItem )
11507 uint32 slot = m_currentBuybackSlot;
11508 // if current back slot non-empty search oldest or free
11509 if(m_items[slot])
11511 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11512 uint32 oldest_slot = BUYBACK_SLOT_START;
11514 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11516 // found empty
11517 if(!m_items[i])
11519 slot = i;
11520 break;
11523 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11525 if(oldest_time > i_time)
11527 oldest_time = i_time;
11528 oldest_slot = i;
11532 // find oldest
11533 slot = oldest_slot;
11536 RemoveItemFromBuyBackSlot( slot, true );
11537 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11539 m_items[slot] = pItem;
11540 time_t base = time(NULL);
11541 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11542 uint32 eslot = slot - BUYBACK_SLOT_START;
11544 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11545 ItemPrototype const *pProto = pItem->GetProto();
11546 if( pProto )
11547 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11548 else
11549 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11550 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11552 // move to next (for non filled list is move most optimized choice)
11553 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11554 ++m_currentBuybackSlot;
11558 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11560 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11561 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11562 return m_items[slot];
11563 return NULL;
11566 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11568 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11569 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11571 Item *pItem = m_items[slot];
11572 if( pItem )
11574 pItem->RemoveFromWorld();
11575 if(del) pItem->SetState(ITEM_REMOVED, this);
11578 m_items[slot] = NULL;
11580 uint32 eslot = slot - BUYBACK_SLOT_START;
11581 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11582 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11583 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11585 // if current backslot is filled set to now free slot
11586 if(m_items[m_currentBuybackSlot])
11587 m_currentBuybackSlot = slot;
11591 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11593 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11594 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11595 data << uint8(msg);
11597 if(msg)
11599 data << uint64(pItem ? pItem->GetGUID() : 0);
11600 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11601 data << uint8(0); // not 0 there...
11603 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11605 uint32 level = 0;
11607 if(pItem)
11608 if(ItemPrototype const* proto = pItem->GetProto())
11609 level = proto->RequiredLevel;
11611 data << uint32(level); // new 2.4.0
11614 GetSession()->SendPacket(&data);
11617 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11619 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11620 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11621 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11622 data << uint32(item);
11623 if( param > 0 )
11624 data << uint32(param);
11625 data << uint8(msg);
11626 GetSession()->SendPacket(&data);
11629 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11631 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11632 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11633 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11634 data << uint64(guid);
11635 if( param > 0 )
11636 data << uint32(param);
11637 data << uint8(msg);
11638 GetSession()->SendPacket(&data);
11641 void Player::ClearTrade()
11643 tradeGold = 0;
11644 acceptTrade = false;
11645 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11646 tradeItems[i] = NULL_SLOT;
11649 void Player::TradeCancel(bool sendback)
11651 if(pTrader)
11653 // send yellow "Trade canceled" message to both traders
11654 WorldSession* ws;
11655 ws = GetSession();
11656 if(sendback)
11657 ws->SendCancelTrade();
11658 ws = pTrader->GetSession();
11659 if(!ws->PlayerLogout())
11660 ws->SendCancelTrade();
11662 // cleanup
11663 ClearTrade();
11664 pTrader->ClearTrade();
11665 // prevent loss of reference
11666 pTrader->pTrader = NULL;
11667 pTrader = NULL;
11671 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11673 if(m_itemDuration.empty())
11674 return;
11676 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11678 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11680 Item* item = *itr;
11681 ++itr; // current element can be erased in UpdateDuration
11683 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11684 item->UpdateDuration(this,time);
11688 void Player::UpdateEnchantTime(uint32 time)
11690 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11692 assert(itr->item);
11693 next=itr;
11694 if(!itr->item->GetEnchantmentId(itr->slot))
11696 next = m_enchantDuration.erase(itr);
11698 else if(itr->leftduration <= time)
11700 ApplyEnchantment(itr->item,itr->slot,false,false);
11701 itr->item->ClearEnchantment(itr->slot);
11702 next = m_enchantDuration.erase(itr);
11704 else if(itr->leftduration > time)
11706 itr->leftduration -= time;
11707 ++next;
11712 void Player::AddEnchantmentDurations(Item *item)
11714 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11716 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11717 continue;
11719 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11720 if( duration > 0 )
11721 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11725 void Player::RemoveEnchantmentDurations(Item *item)
11727 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11729 if(itr->item == item)
11731 // save duration in item
11732 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11733 itr = m_enchantDuration.erase(itr);
11735 else
11736 ++itr;
11740 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11742 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11743 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11745 next = itr;
11746 if(itr->slot==slot)
11748 if(itr->item && itr->item->GetEnchantmentId(slot))
11750 // remove from stats
11751 ApplyEnchantment(itr->item,slot,false,false);
11752 // remove visual
11753 itr->item->ClearEnchantment(slot);
11755 // remove from update list
11756 next = m_enchantDuration.erase(itr);
11758 else
11759 ++next;
11762 // remove enchants from inventory items
11763 // NOTE: no need to remove these from stats, since these aren't equipped
11764 // in inventory
11765 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11767 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11768 if( pItem && pItem->GetEnchantmentId(slot) )
11769 pItem->ClearEnchantment(slot);
11772 // in inventory bags
11773 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11775 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11776 if( pBag )
11778 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11780 Item* pItem = pBag->GetItemByPos(j);
11781 if( pItem && pItem->GetEnchantmentId(slot) )
11782 pItem->ClearEnchantment(slot);
11788 // duration == 0 will remove item enchant
11789 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11791 if(!item)
11792 return;
11794 if(slot >= MAX_ENCHANTMENT_SLOT)
11795 return;
11797 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11799 if(itr->item == item && itr->slot == slot)
11801 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11802 m_enchantDuration.erase(itr);
11803 break;
11806 if(item && duration > 0 )
11808 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11809 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11813 void Player::ApplyEnchantment(Item *item,bool apply)
11815 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11816 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11819 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11821 if(!item)
11822 return;
11824 if(!item->IsEquipped())
11825 return;
11827 if(slot >= MAX_ENCHANTMENT_SLOT)
11828 return;
11830 uint32 enchant_id = item->GetEnchantmentId(slot);
11831 if(!enchant_id)
11832 return;
11834 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11835 if(!pEnchant)
11836 return;
11838 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11839 return;
11841 for (int s=0; s<3; s++)
11843 uint32 enchant_display_type = pEnchant->type[s];
11844 uint32 enchant_amount = pEnchant->amount[s];
11845 uint32 enchant_spell_id = pEnchant->spellid[s];
11847 switch(enchant_display_type)
11849 case ITEM_ENCHANTMENT_TYPE_NONE:
11850 break;
11851 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11852 // processed in Player::CastItemCombatSpell
11853 break;
11854 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11855 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11856 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11857 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11858 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11859 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11860 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11861 break;
11862 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11863 if(enchant_spell_id)
11865 if(apply)
11867 int32 basepoints = 0;
11868 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11869 if (item->GetItemRandomPropertyId())
11871 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11872 if (item_rand)
11874 // Search enchant_amount
11875 for (int k=0; k<3; k++)
11877 if(item_rand->enchant_id[k] == enchant_id)
11879 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11880 break;
11885 // Cast custom spell vs all equal basepoints getted from enchant_amount
11886 if (basepoints)
11887 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11888 else
11889 CastSpell(this,enchant_spell_id,true,item);
11891 else
11892 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11894 break;
11895 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11896 if (!enchant_amount)
11898 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11899 if(item_rand)
11901 for (int k=0; k<3; k++)
11903 if(item_rand->enchant_id[k] == enchant_id)
11905 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11906 break;
11912 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11913 break;
11914 case ITEM_ENCHANTMENT_TYPE_STAT:
11916 if (!enchant_amount)
11918 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11919 if(item_rand_suffix)
11921 for (int k=0; k<3; k++)
11923 if(item_rand_suffix->enchant_id[k] == enchant_id)
11925 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11926 break;
11932 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11933 switch (enchant_spell_id)
11935 case ITEM_MOD_AGILITY:
11936 sLog.outDebug("+ %u AGILITY",enchant_amount);
11937 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11938 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11939 break;
11940 case ITEM_MOD_STRENGTH:
11941 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11942 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11943 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11944 break;
11945 case ITEM_MOD_INTELLECT:
11946 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11947 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11948 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11949 break;
11950 case ITEM_MOD_SPIRIT:
11951 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11952 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11953 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11954 break;
11955 case ITEM_MOD_STAMINA:
11956 sLog.outDebug("+ %u STAMINA",enchant_amount);
11957 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11958 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11959 break;
11960 case ITEM_MOD_DEFENSE_SKILL_RATING:
11961 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11962 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11963 break;
11964 case ITEM_MOD_DODGE_RATING:
11965 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11966 sLog.outDebug("+ %u DODGE", enchant_amount);
11967 break;
11968 case ITEM_MOD_PARRY_RATING:
11969 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11970 sLog.outDebug("+ %u PARRY", enchant_amount);
11971 break;
11972 case ITEM_MOD_BLOCK_RATING:
11973 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11974 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11975 break;
11976 case ITEM_MOD_HIT_MELEE_RATING:
11977 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11978 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11979 break;
11980 case ITEM_MOD_HIT_RANGED_RATING:
11981 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11982 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11983 break;
11984 case ITEM_MOD_HIT_SPELL_RATING:
11985 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11986 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11987 break;
11988 case ITEM_MOD_CRIT_MELEE_RATING:
11989 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11990 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11991 break;
11992 case ITEM_MOD_CRIT_RANGED_RATING:
11993 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11994 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11995 break;
11996 case ITEM_MOD_CRIT_SPELL_RATING:
11997 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11998 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11999 break;
12000 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12001 // in Enchantments
12002 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12003 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12004 // break;
12005 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12006 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12007 // break;
12008 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12009 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12010 // break;
12011 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12012 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12013 // break;
12014 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12015 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12016 // break;
12017 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12018 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12019 // break;
12020 // case ITEM_MOD_HASTE_MELEE_RATING:
12021 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12022 // break;
12023 // case ITEM_MOD_HASTE_RANGED_RATING:
12024 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12025 // break;
12026 case ITEM_MOD_HASTE_SPELL_RATING:
12027 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12028 break;
12029 case ITEM_MOD_HIT_RATING:
12030 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12031 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12032 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12033 sLog.outDebug("+ %u HIT", enchant_amount);
12034 break;
12035 case ITEM_MOD_CRIT_RATING:
12036 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12037 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12038 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12039 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12040 break;
12041 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12042 // case ITEM_MOD_HIT_TAKEN_RATING:
12043 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12044 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12045 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12046 // break;
12047 // case ITEM_MOD_CRIT_TAKEN_RATING:
12048 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12049 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12050 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12051 // break;
12052 case ITEM_MOD_RESILIENCE_RATING:
12053 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12054 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12055 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12056 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12057 break;
12058 case ITEM_MOD_HASTE_RATING:
12059 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12060 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12061 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12062 sLog.outDebug("+ %u HASTE", enchant_amount);
12063 break;
12064 case ITEM_MOD_EXPERTISE_RATING:
12065 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12066 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12067 break;
12068 case ITEM_MOD_ATTACK_POWER:
12069 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12070 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12071 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12072 break;
12073 case ITEM_MOD_RANGED_ATTACK_POWER:
12074 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12075 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12076 break;
12077 case ITEM_MOD_FERAL_ATTACK_POWER:
12078 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12079 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12080 break;
12081 case ITEM_MOD_SPELL_HEALING_DONE:
12082 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12083 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
12084 break;
12085 case ITEM_MOD_SPELL_DAMAGE_DONE:
12086 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12087 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
12088 break;
12089 case ITEM_MOD_MANA_REGENERATION:
12090 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12091 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12092 break;
12093 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12094 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12095 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12096 break;
12097 case ITEM_MOD_SPELL_POWER:
12098 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12099 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12100 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12101 break;
12102 default:
12103 break;
12105 break;
12107 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12109 if(getClass() == CLASS_SHAMAN)
12111 float addValue = 0.0f;
12112 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12114 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12115 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12117 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12119 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12120 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12123 break;
12125 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12126 // processed in Player::CastItemUseSpell
12127 break;
12128 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12129 // nothing do..
12130 break;
12131 default:
12132 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12133 break;
12134 } /*switch(enchant_display_type)*/
12135 } /*for*/
12137 // visualize enchantment at player and equipped items
12138 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
12140 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
12141 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
12144 if(apply_dur)
12146 if(apply)
12148 // set duration
12149 uint32 duration = item->GetEnchantmentDuration(slot);
12150 if(duration > 0)
12151 AddEnchantmentDuration(item,slot,duration);
12153 else
12155 // duration == 0 will remove EnchantDuration
12156 AddEnchantmentDuration(item,slot,0);
12161 void Player::SendEnchantmentDurations()
12163 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
12165 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
12169 void Player::SendItemDurations()
12171 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
12173 (*itr)->SendTimeUpdate(this);
12177 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12179 if(!item) // prevent crash
12180 return;
12182 // last check 2.0.10
12183 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12184 data << GetGUID(); // player GUID
12185 data << uint32(received); // 0=looted, 1=from npc
12186 data << uint32(created); // 0=received, 1=created
12187 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12188 data << (uint8)item->GetBagSlot(); // bagslot
12189 // item slot, but when added to stack: 0xFFFFFFFF
12190 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
12191 data << uint32(item->GetEntry()); // item id
12192 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12193 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12194 data << uint32(count); // count of items
12195 data << GetItemCount(item->GetEntry()); // count of items in inventory
12197 if (broadcast && GetGroup())
12198 GetGroup()->BroadcastPacket(&data);
12199 else
12200 GetSession()->SendPacket(&data);
12203 /*********************************************************/
12204 /*** QUEST SYSTEM ***/
12205 /*********************************************************/
12207 void Player::PrepareQuestMenu( uint64 guid )
12209 Object *pObject;
12210 QuestRelations* pObjectQR;
12211 QuestRelations* pObjectQIR;
12212 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12213 if( pCreature )
12215 pObject = (Object*)pCreature;
12216 pObjectQR = &objmgr.mCreatureQuestRelations;
12217 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12219 else
12221 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12222 if( pGameObject )
12224 pObject = (Object*)pGameObject;
12225 pObjectQR = &objmgr.mGOQuestRelations;
12226 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12228 else
12229 return;
12232 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12233 qm.ClearMenu();
12235 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12237 uint32 quest_id = i->second;
12238 QuestStatus status = GetQuestStatus( quest_id );
12239 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12240 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12241 else if ( status == QUEST_STATUS_INCOMPLETE )
12242 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12243 else if (status == QUEST_STATUS_AVAILABLE )
12244 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12247 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12249 uint32 quest_id = i->second;
12250 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12251 if(!pQuest) continue;
12253 QuestStatus status = GetQuestStatus( quest_id );
12255 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12256 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12257 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12258 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12262 void Player::SendPreparedQuest( uint64 guid )
12264 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12265 if( questMenu.Empty() )
12266 return;
12268 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12270 uint32 status = qmi0.m_qIcon;
12272 // single element case
12273 if ( questMenu.MenuItemCount() == 1 )
12275 // Auto open -- maybe also should verify there is no greeting
12276 uint32 quest_id = qmi0.m_qId;
12277 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12278 if ( pQuest )
12280 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12281 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12282 else if( status == DIALOG_STATUS_INCOMPLETE )
12283 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12284 // Send completable on repeatable quest if player don't have quest
12285 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12286 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12287 else
12288 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12291 // multiply entries
12292 else
12294 QEmote qe;
12295 qe._Delay = 0;
12296 qe._Emote = 0;
12297 std::string title = "";
12298 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12299 if( pCreature )
12301 uint32 textid = pCreature->GetNpcTextId();
12302 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12303 if( !gossiptext )
12305 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12306 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12307 title = "";
12309 else
12311 qe = gossiptext->Options[0].Emotes[0];
12313 if(!gossiptext->Options[0].Text_0.empty())
12315 title = gossiptext->Options[0].Text_0;
12317 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12318 if (loc_idx >= 0)
12320 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12321 if (nl)
12323 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12324 title = nl->Text_0[0][loc_idx];
12328 else
12330 title = gossiptext->Options[0].Text_1;
12332 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12333 if (loc_idx >= 0)
12335 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12336 if (nl)
12338 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12339 title = nl->Text_1[0][loc_idx];
12345 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12349 bool Player::IsActiveQuest( uint32 quest_id ) const
12351 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12353 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12356 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12358 Object *pObject;
12359 QuestRelations* pObjectQR;
12360 QuestRelations* pObjectQIR;
12362 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12363 if( pCreature )
12365 pObject = (Object*)pCreature;
12366 pObjectQR = &objmgr.mCreatureQuestRelations;
12367 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12369 else
12371 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12372 if( pGameObject )
12374 pObject = (Object*)pGameObject;
12375 pObjectQR = &objmgr.mGOQuestRelations;
12376 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12378 else
12379 return NULL;
12382 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12383 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12385 if (itr->second == nextQuestID)
12386 return objmgr.GetQuestTemplate(nextQuestID);
12389 return NULL;
12392 bool Player::CanSeeStartQuest( Quest const *pQuest )
12394 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12395 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12396 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12397 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12399 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12402 return false;
12405 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12407 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12408 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12409 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12410 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12411 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12412 && SatisfyQuestDay( pQuest, msg );
12415 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12417 if( !SatisfyQuestLog( msg ) )
12418 return false;
12420 uint32 srcitem = pQuest->GetSrcItemId();
12421 if( srcitem > 0 )
12423 uint32 count = pQuest->GetSrcItemCount();
12424 ItemPosCountVec dest;
12425 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12427 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12428 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12429 return true;
12430 else if( msg != EQUIP_ERR_OK )
12432 SendEquipError( msg, NULL, NULL );
12433 return false;
12436 return true;
12439 bool Player::CanCompleteQuest( uint32 quest_id )
12441 if( quest_id )
12443 QuestStatusData& q_status = mQuestStatus[quest_id];
12444 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12445 return false; // not allow re-complete quest
12447 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12449 if(!qInfo)
12450 return false;
12452 // auto complete quest
12453 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12454 return true;
12456 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12459 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12461 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12463 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12464 return false;
12468 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12470 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12472 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12473 continue;
12475 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12476 return false;
12480 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12481 return false;
12483 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12484 return false;
12486 if ( qInfo->GetRewOrReqMoney() < 0 )
12488 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12489 return false;
12492 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12493 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12494 return false;
12496 return true;
12499 return false;
12502 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12504 // Solve problem that player don't have the quest and try complete it.
12505 // if repeatable she must be able to complete event if player don't have it.
12506 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12507 if( !CanTakeQuest(pQuest, false) )
12508 return false;
12510 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12511 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12512 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12513 return false;
12515 if( !CanRewardQuest(pQuest, false) )
12516 return false;
12518 return true;
12521 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12523 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12524 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12525 return false;
12527 // daily quest can't be rewarded (25 daily quest already completed)
12528 if(!SatisfyQuestDay(pQuest,true))
12529 return false;
12531 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12532 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12533 return false;
12535 // prevent receive reward with quest items in bank
12536 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12538 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12540 if( pQuest->ReqItemCount[i]!= 0 &&
12541 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12543 if(msg)
12544 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12545 return false;
12550 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12551 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12552 return false;
12554 return true;
12557 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12559 // prevent receive reward with quest items in bank or for not completed quest
12560 if(!CanRewardQuest(pQuest,msg))
12561 return false;
12563 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12565 if( pQuest->RewChoiceItemId[reward] )
12567 ItemPosCountVec dest;
12568 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12569 if( res != EQUIP_ERR_OK )
12571 SendEquipError( res, NULL, NULL );
12572 return false;
12577 if ( pQuest->GetRewItemsCount() > 0 )
12579 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12581 if( pQuest->RewItemId[i] )
12583 ItemPosCountVec dest;
12584 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12585 if( res != EQUIP_ERR_OK )
12587 SendEquipError( res, NULL, NULL );
12588 return false;
12594 return true;
12597 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12599 uint16 log_slot = FindQuestSlot( 0 );
12600 assert(log_slot < MAX_QUEST_LOG_SIZE);
12602 uint32 quest_id = pQuest->GetQuestId();
12604 // if not exist then created with set uState==NEW and rewarded=false
12605 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12607 // check for repeatable quests status reset
12608 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12609 questStatusData.m_explored = false;
12611 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12613 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12614 questStatusData.m_itemcount[i] = 0;
12617 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12619 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12620 questStatusData.m_creatureOrGOcount[i] = 0;
12623 GiveQuestSourceItem( pQuest );
12624 AdjustQuestReqItemCount( pQuest, questStatusData );
12626 if( pQuest->GetRepObjectiveFaction() )
12627 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12629 uint32 qtime = 0;
12630 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12632 uint32 limittime = pQuest->GetLimitTime();
12634 // shared timed quest
12635 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12636 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12638 AddTimedQuest( quest_id );
12639 questStatusData.m_timer = limittime * 1000;
12640 qtime = static_cast<uint32>(time(NULL)) + limittime;
12642 else
12643 questStatusData.m_timer = 0;
12645 SetQuestSlot(log_slot, quest_id, qtime);
12647 if (questStatusData.uState != QUEST_NEW)
12648 questStatusData.uState = QUEST_CHANGED;
12650 //starting initial quest script
12651 if(questGiver && pQuest->GetQuestStartScript()!=0)
12652 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12654 UpdateForQuestsGO();
12657 void Player::CompleteQuest( uint32 quest_id )
12659 if( quest_id )
12661 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12663 uint16 log_slot = FindQuestSlot( quest_id );
12664 if( log_slot < MAX_QUEST_LOG_SIZE)
12665 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12667 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12669 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12670 RewardQuest(qInfo,0,this,false);
12671 else
12672 SendQuestComplete( quest_id );
12677 void Player::IncompleteQuest( uint32 quest_id )
12679 if( quest_id )
12681 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12683 uint16 log_slot = FindQuestSlot( quest_id );
12684 if( log_slot < MAX_QUEST_LOG_SIZE)
12685 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12689 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12691 uint32 quest_id = pQuest->GetQuestId();
12693 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12695 if ( pQuest->ReqItemId[i] )
12696 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12699 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12700 // SetTimedQuest( 0 );
12701 m_timedquests.erase(pQuest->GetQuestId());
12703 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12705 if( pQuest->RewChoiceItemId[reward] )
12707 ItemPosCountVec dest;
12708 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12710 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12711 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12716 if ( pQuest->GetRewItemsCount() > 0 )
12718 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12720 if( pQuest->RewItemId[i] )
12722 ItemPosCountVec dest;
12723 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12725 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12726 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12732 RewardReputation( pQuest );
12734 if( pQuest->GetRewSpellCast() > 0 )
12735 CastSpell( this, pQuest->GetRewSpellCast(), true);
12736 else if( pQuest->GetRewSpell() > 0)
12737 CastSpell( this, pQuest->GetRewSpell(), true);
12739 uint16 log_slot = FindQuestSlot( quest_id );
12740 if( log_slot < MAX_QUEST_LOG_SIZE)
12741 SetQuestSlot(log_slot,0);
12743 QuestStatusData& q_status = mQuestStatus[quest_id];
12745 // Not give XP in case already completed once repeatable quest
12746 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12748 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12749 GiveXP( XP , NULL );
12750 else
12751 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12753 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12754 ModifyMoney( pQuest->GetRewOrReqMoney() );
12756 // honor reward
12757 if(pQuest->GetRewHonorableKills())
12758 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12760 // title reward
12761 if(pQuest->GetCharTitleId())
12763 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12764 SetTitle(titleEntry);
12767 if(pQuest->GetBonusTalents())
12769 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12770 InitTalentForLevel();
12773 // Send reward mail
12774 if(pQuest->GetRewMailTemplateId())
12776 MailMessageType mailType;
12777 uint32 senderGuidOrEntry;
12778 switch(questGiver->GetTypeId())
12780 case TYPEID_UNIT:
12781 mailType = MAIL_CREATURE;
12782 senderGuidOrEntry = questGiver->GetEntry();
12783 break;
12784 case TYPEID_GAMEOBJECT:
12785 mailType = MAIL_GAMEOBJECT;
12786 senderGuidOrEntry = questGiver->GetEntry();
12787 break;
12788 case TYPEID_ITEM:
12789 mailType = MAIL_ITEM;
12790 senderGuidOrEntry = questGiver->GetEntry();
12791 break;
12792 case TYPEID_PLAYER:
12793 mailType = MAIL_NORMAL;
12794 senderGuidOrEntry = questGiver->GetGUIDLow();
12795 break;
12796 default:
12797 mailType = MAIL_NORMAL;
12798 senderGuidOrEntry = GetGUIDLow();
12799 break;
12802 Loot questMailLoot;
12804 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12806 // fill mail
12807 MailItemsInfo mi; // item list preparing
12809 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12810 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12812 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12814 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12816 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12817 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12822 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12825 if(pQuest->IsDaily())
12827 SetDailyQuestStatus(quest_id);
12828 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12831 if ( !pQuest->IsRepeatable() )
12832 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12833 else
12834 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12836 q_status.m_rewarded = true;
12838 if(announce)
12839 SendQuestReward( pQuest, XP, questGiver );
12841 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12842 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12846 void Player::FailQuest( uint32 quest_id )
12848 if( quest_id )
12850 IncompleteQuest( quest_id );
12852 uint16 log_slot = FindQuestSlot( quest_id );
12853 if( log_slot < MAX_QUEST_LOG_SIZE)
12855 SetQuestSlotTimer(log_slot, 1 );
12856 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12858 SendQuestFailed( quest_id );
12862 void Player::FailTimedQuest( uint32 quest_id )
12864 if( quest_id )
12866 QuestStatusData& q_status = mQuestStatus[quest_id];
12868 q_status.m_timer = 0;
12869 if (q_status.uState != QUEST_NEW)
12870 q_status.uState = QUEST_CHANGED;
12872 IncompleteQuest( quest_id );
12874 uint16 log_slot = FindQuestSlot( quest_id );
12875 if( log_slot < MAX_QUEST_LOG_SIZE)
12877 SetQuestSlotTimer(log_slot, 1 );
12878 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12880 SendQuestTimerFailed( quest_id );
12884 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12886 int32 zoneOrSort = qInfo->GetZoneOrSort();
12887 int32 skillOrClass = qInfo->GetSkillOrClass();
12889 // skip zone zoneOrSort and 0 case skillOrClass
12890 if( zoneOrSort >= 0 && skillOrClass == 0 )
12891 return true;
12893 int32 questSort = -zoneOrSort;
12894 uint8 reqSortClass = ClassByQuestSort(questSort);
12896 // check class sort cases in zoneOrSort
12897 if( reqSortClass != 0 && getClass() != reqSortClass)
12899 if( msg )
12900 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12901 return false;
12904 // check class
12905 if( skillOrClass < 0 )
12907 uint8 reqClass = -int32(skillOrClass);
12908 if(getClass() != reqClass)
12910 if( msg )
12911 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12912 return false;
12915 // check skill
12916 else if( skillOrClass > 0 )
12918 uint32 reqSkill = skillOrClass;
12919 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12921 if( msg )
12922 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12923 return false;
12927 return true;
12930 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12932 if( getLevel() < qInfo->GetMinLevel() )
12934 if( msg )
12935 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12936 return false;
12938 return true;
12941 bool Player::SatisfyQuestLog( bool msg )
12943 // exist free slot
12944 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12945 return true;
12947 if( msg )
12949 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12950 GetSession()->SendPacket( &data );
12951 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12953 return false;
12956 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12958 // No previous quest (might be first quest in a series)
12959 if( qInfo->prevQuests.empty())
12960 return true;
12962 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12964 uint32 prevId = abs(*iter);
12966 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12967 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12969 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12971 // If any of the positive previous quests completed, return true
12972 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12974 // skip one-from-all exclusive group
12975 if(qPrevInfo->GetExclusiveGroup() >= 0)
12976 return true;
12978 // each-from-all exclusive group ( < 0)
12979 // can be start if only all quests in prev quest exclusive group completed and rewarded
12980 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12981 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12983 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12985 for(; iter != end; ++iter)
12987 uint32 exclude_Id = iter->second;
12989 // skip checked quest id, only state of other quests in group is interesting
12990 if(exclude_Id == prevId)
12991 continue;
12993 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12995 // alternative quest from group also must be completed and rewarded(reported)
12996 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12998 if( msg )
12999 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13000 return false;
13003 return true;
13005 // If any of the negative previous quests active, return true
13006 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13007 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13009 // skip one-from-all exclusive group
13010 if(qPrevInfo->GetExclusiveGroup() >= 0)
13011 return true;
13013 // each-from-all exclusive group ( < 0)
13014 // can be start if only all quests in prev quest exclusive group active
13015 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13016 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13018 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13020 for(; iter != end; ++iter)
13022 uint32 exclude_Id = iter->second;
13024 // skip checked quest id, only state of other quests in group is interesting
13025 if(exclude_Id == prevId)
13026 continue;
13028 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13030 // alternative quest from group also must be active
13031 if( i_exstatus == mQuestStatus.end() ||
13032 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13033 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13035 if( msg )
13036 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13037 return false;
13040 return true;
13045 // Has only positive prev. quests in non-rewarded state
13046 // and negative prev. quests in non-active state
13047 if( msg )
13048 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13050 return false;
13053 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13055 uint32 reqraces = qInfo->GetRequiredRaces();
13056 if ( reqraces == 0 )
13057 return true;
13058 if( (reqraces & getRaceMask()) == 0 )
13060 if( msg )
13061 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13062 return false;
13064 return true;
13067 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13069 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13070 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13072 if( msg )
13073 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13074 return false;
13077 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13078 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13080 if( msg )
13081 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13082 return false;
13085 return true;
13088 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13090 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13091 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13093 if( msg )
13094 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13095 return false;
13097 return true;
13100 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13102 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13104 if( msg )
13105 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13106 return false;
13108 return true;
13111 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13113 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13114 if(qInfo->GetExclusiveGroup() <= 0)
13115 return true;
13117 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13118 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13120 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13122 for(; iter != end; ++iter)
13124 uint32 exclude_Id = iter->second;
13126 // skip checked quest id, only state of other quests in group is interesting
13127 if(exclude_Id == qInfo->GetQuestId())
13128 continue;
13130 // not allow have daily quest if daily quest from exclusive group already recently completed
13131 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13132 if( !SatisfyQuestDay(Nquest, false) )
13134 if( msg )
13135 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13136 return false;
13139 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13141 // alternative quest already started or completed
13142 if( i_exstatus != mQuestStatus.end()
13143 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13145 if( msg )
13146 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13147 return false;
13150 return true;
13153 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13155 if(!qInfo->GetNextQuestInChain())
13156 return true;
13158 // next quest in chain already started or completed
13159 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13160 if( itr != mQuestStatus.end()
13161 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13163 if( msg )
13164 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13165 return false;
13168 // check for all quests further up the chain
13169 // only necessary if there are quest chains with more than one quest that can be skipped
13170 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13171 return true;
13174 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13176 // No previous quest in chain
13177 if( qInfo->prevChainQuests.empty())
13178 return true;
13180 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13182 uint32 prevId = *iter;
13184 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13186 if( i_prevstatus != mQuestStatus.end() )
13188 // If any of the previous quests in chain active, return false
13189 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13190 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13192 if( msg )
13193 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13194 return false;
13198 // check for all quests further down the chain
13199 // only necessary if there are quest chains with more than one quest that can be skipped
13200 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13201 // return false;
13204 // No previous quest in chain active
13205 return true;
13208 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13210 if(!qInfo->IsDaily())
13211 return true;
13213 bool have_slot = false;
13214 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13216 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13217 if(qInfo->GetQuestId()==id)
13218 return false;
13220 if(!id)
13221 have_slot = true;
13224 if(!have_slot)
13226 if( msg )
13227 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13228 return false;
13231 return true;
13234 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13236 uint32 srcitem = pQuest->GetSrcItemId();
13237 if( srcitem > 0 )
13239 uint32 count = pQuest->GetSrcItemCount();
13240 if( count <= 0 )
13241 count = 1;
13243 ItemPosCountVec dest;
13244 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13245 if( msg == EQUIP_ERR_OK )
13247 Item * item = StoreNewItem(dest, srcitem, true);
13248 SendNewItem(item, count, true, false);
13249 return true;
13251 // player already have max amount required item, just report success
13252 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13253 return true;
13254 else
13255 SendEquipError( msg, NULL, NULL );
13256 return false;
13259 return true;
13262 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13264 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13265 if( qInfo )
13267 uint32 srcitem = qInfo->GetSrcItemId();
13268 if( srcitem > 0 )
13270 uint32 count = qInfo->GetSrcItemCount();
13271 if( count <= 0 )
13272 count = 1;
13274 // exist one case when destroy source quest item not possible:
13275 // non un-equippable item (equipped non-empty bag, for example)
13276 uint8 res = CanUnequipItems(srcitem,count);
13277 if(res != EQUIP_ERR_OK)
13279 if(msg)
13280 SendEquipError( res, NULL, NULL );
13281 return false;
13284 DestroyItemCount(srcitem, count, true, true);
13287 return true;
13290 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13292 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13293 if( qInfo )
13295 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13296 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13297 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13298 && !qInfo->IsRepeatable() )
13299 return itr->second.m_rewarded;
13301 return false;
13303 return false;
13306 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13308 if( quest_id )
13310 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13311 if( itr != mQuestStatus.end() )
13312 return itr->second.m_status;
13314 return QUEST_STATUS_NONE;
13317 bool Player::CanShareQuest(uint32 quest_id) const
13319 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13320 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13322 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13323 if( itr != mQuestStatus.end() )
13324 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13326 return false;
13329 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13331 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13332 if( qInfo )
13334 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13336 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13337 m_timedquests.erase(qInfo->GetQuestId());
13340 QuestStatusData& q_status = mQuestStatus[quest_id];
13342 q_status.m_status = status;
13343 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13346 UpdateForQuestsGO();
13349 // not used in MaNGOS, but used in scripting code
13350 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13352 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13353 if( !qInfo )
13354 return 0;
13356 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13357 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13358 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13360 return 0;
13363 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13365 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13367 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13369 uint32 reqitemcount = pQuest->ReqItemCount[i];
13370 if( reqitemcount != 0 )
13372 uint32 quest_id = pQuest->GetQuestId();
13373 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13375 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13376 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13382 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13384 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13385 if ( GetQuestSlotQuestId(i) == quest_id )
13386 return i;
13388 return MAX_QUEST_LOG_SIZE;
13391 void Player::AreaExploredOrEventHappens( uint32 questId )
13393 if( questId )
13395 uint16 log_slot = FindQuestSlot( questId );
13396 if( log_slot < MAX_QUEST_LOG_SIZE)
13398 QuestStatusData& q_status = mQuestStatus[questId];
13400 if(!q_status.m_explored)
13402 q_status.m_explored = true;
13403 if (q_status.uState != QUEST_NEW)
13404 q_status.uState = QUEST_CHANGED;
13407 if( CanCompleteQuest( questId ) )
13408 CompleteQuest( questId );
13412 //not used in mangosd, function for external script library
13413 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13415 if( Group *pGroup = GetGroup() )
13417 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13419 Player *pGroupGuy = itr->getSource();
13421 // for any leave or dead (with not released body) group member at appropriate distance
13422 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13423 pGroupGuy->AreaExploredOrEventHappens(questId);
13426 else
13427 AreaExploredOrEventHappens(questId);
13430 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13432 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13434 uint32 questid = GetQuestSlotQuestId(i);
13435 if ( questid == 0 )
13436 continue;
13438 QuestStatusData& q_status = mQuestStatus[questid];
13440 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13441 continue;
13443 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13444 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13445 continue;
13447 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13449 uint32 reqitem = qInfo->ReqItemId[j];
13450 if ( reqitem == entry )
13452 uint32 reqitemcount = qInfo->ReqItemCount[j];
13453 uint32 curitemcount = q_status.m_itemcount[j];
13454 if ( curitemcount < reqitemcount )
13456 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13457 q_status.m_itemcount[j] += additemcount;
13458 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13460 SendQuestUpdateAddItem( qInfo, j, additemcount );
13462 if ( CanCompleteQuest( questid ) )
13463 CompleteQuest( questid );
13464 return;
13468 UpdateForQuestsGO();
13469 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13472 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13474 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13476 uint32 questid = GetQuestSlotQuestId(i);
13477 if(!questid)
13478 continue;
13479 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13480 if ( !qInfo )
13481 continue;
13482 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13483 continue;
13485 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13487 uint32 reqitem = qInfo->ReqItemId[j];
13488 if ( reqitem == entry )
13490 QuestStatusData& q_status = mQuestStatus[questid];
13492 uint32 reqitemcount = qInfo->ReqItemCount[j];
13493 uint32 curitemcount;
13494 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13495 curitemcount = q_status.m_itemcount[j];
13496 else
13497 curitemcount = GetItemCount(entry,true);
13498 if ( curitemcount < reqitemcount + count )
13500 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13501 q_status.m_itemcount[j] = curitemcount - remitemcount;
13502 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13504 IncompleteQuest( questid );
13506 return;
13510 UpdateForQuestsGO();
13513 void Player::KilledMonster( uint32 entry, uint64 guid )
13515 uint32 addkillcount = 1;
13516 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13517 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13519 uint32 questid = GetQuestSlotQuestId(i);
13520 if(!questid)
13521 continue;
13523 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13524 if( !qInfo )
13525 continue;
13526 // just if !ingroup || !noraidgroup || raidgroup
13527 QuestStatusData& q_status = mQuestStatus[questid];
13528 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13530 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13532 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13534 // skip GO activate objective or none
13535 if(qInfo->ReqCreatureOrGOId[j] <=0)
13536 continue;
13538 // skip Cast at creature objective
13539 if(qInfo->ReqSpell[j] !=0 )
13540 continue;
13542 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13544 if ( reqkill == entry )
13546 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13547 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13548 if ( curkillcount < reqkillcount )
13550 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13551 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13553 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13555 if ( CanCompleteQuest( questid ) )
13556 CompleteQuest( questid );
13558 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13559 continue;
13567 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13569 bool isCreature = IS_CREATURE_GUID(guid);
13571 uint32 addCastCount = 1;
13572 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13574 uint32 questid = GetQuestSlotQuestId(i);
13575 if(!questid)
13576 continue;
13578 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13579 if ( !qInfo )
13580 continue;
13582 QuestStatusData& q_status = mQuestStatus[questid];
13584 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13586 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13588 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13590 // skip kill creature objective (0) or wrong spell casts
13591 if(qInfo->ReqSpell[j] != spell_id )
13592 continue;
13594 uint32 reqTarget = 0;
13596 if(isCreature)
13598 // creature activate objectives
13599 if(qInfo->ReqCreatureOrGOId[j] > 0)
13600 // checked at quest_template loading
13601 reqTarget = qInfo->ReqCreatureOrGOId[j];
13603 else
13605 // GO activate objective
13606 if(qInfo->ReqCreatureOrGOId[j] < 0)
13607 // checked at quest_template loading
13608 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13611 // other not this creature/GO related objectives
13612 if( reqTarget != entry )
13613 continue;
13615 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13616 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13617 if ( curCastCount < reqCastCount )
13619 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13620 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13622 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13625 if ( CanCompleteQuest( questid ) )
13626 CompleteQuest( questid );
13628 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13629 break;
13636 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13638 uint32 addTalkCount = 1;
13639 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13641 uint32 questid = GetQuestSlotQuestId(i);
13642 if(!questid)
13643 continue;
13645 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13646 if ( !qInfo )
13647 continue;
13649 QuestStatusData& q_status = mQuestStatus[questid];
13651 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13653 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13655 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13657 // skip spell casts and Gameobject objectives
13658 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13659 continue;
13661 uint32 reqTarget = 0;
13663 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13664 // checked at quest_template loading
13665 reqTarget = qInfo->ReqCreatureOrGOId[j];
13666 else
13667 continue;
13669 if ( reqTarget == entry )
13671 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13672 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13673 if ( curTalkCount < reqTalkCount )
13675 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13676 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13678 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13680 if ( CanCompleteQuest( questid ) )
13681 CompleteQuest( questid );
13683 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13684 continue;
13692 void Player::MoneyChanged( uint32 count )
13694 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13696 uint32 questid = GetQuestSlotQuestId(i);
13697 if (!questid)
13698 continue;
13700 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13701 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13703 QuestStatusData& q_status = mQuestStatus[questid];
13705 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13707 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13709 if ( CanCompleteQuest( questid ) )
13710 CompleteQuest( questid );
13713 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13715 if(int32(count) < -qInfo->GetRewOrReqMoney())
13716 IncompleteQuest( questid );
13722 bool Player::HasQuestForItem( uint32 itemid ) const
13724 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13726 uint32 questid = GetQuestSlotQuestId(i);
13727 if ( questid == 0 )
13728 continue;
13730 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13731 if(qs_itr == mQuestStatus.end())
13732 continue;
13734 QuestStatusData const& q_status = qs_itr->second;
13736 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13738 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13739 if(!qinfo)
13740 continue;
13742 // hide quest if player is in raid-group and quest is no raid quest
13743 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13744 continue;
13746 // There should be no mixed ReqItem/ReqSource drop
13747 // This part for ReqItem drop
13748 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13750 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13751 return true;
13753 // This part - for ReqSource
13754 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13756 // examined item is a source item
13757 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13759 uint32 idx = qinfo->ReqSourceRef[j]-1;
13761 // total count of created ReqItems and SourceItems is less than ReqItemCount
13762 if(qinfo->ReqItemId[idx] != 0 &&
13763 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13764 return true;
13766 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13767 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13769 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13770 return true;
13772 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13773 else if(qinfo->ReqSpell[idx] != 0)
13775 // not casted and need more reagents/item for use.
13776 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13777 return true;
13783 return false;
13786 void Player::SendQuestComplete( uint32 quest_id )
13788 if( quest_id )
13790 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13791 data << uint32(quest_id);
13792 GetSession()->SendPacket( &data );
13793 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13797 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13799 uint32 questid = pQuest->GetQuestId();
13800 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13801 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13802 data << uint32(questid);
13804 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13806 data << uint32(XP);
13807 data << uint32(pQuest->GetRewOrReqMoney());
13809 else
13811 data << uint32(0);
13812 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13815 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13816 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13817 GetSession()->SendPacket( &data );
13819 if (pQuest->GetQuestCompleteScript() != 0)
13820 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13823 void Player::SendQuestFailed( uint32 quest_id )
13825 if( quest_id )
13827 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13828 data << quest_id;
13829 data << uint32(0); // failed reason (4 for inventory is full)
13830 GetSession()->SendPacket( &data );
13831 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13835 void Player::SendQuestTimerFailed( uint32 quest_id )
13837 if( quest_id )
13839 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13840 data << quest_id;
13841 GetSession()->SendPacket( &data );
13842 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13846 void Player::SendCanTakeQuestResponse( uint32 msg )
13848 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13849 data << uint32(msg);
13850 GetSession()->SendPacket( &data );
13851 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13854 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13856 if( pPlayer )
13858 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13859 data << uint64(pPlayer->GetGUID());
13860 data << uint8(msg); // valid values: 0-8
13861 GetSession()->SendPacket( &data );
13862 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13866 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13868 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13869 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13870 //data << pQuest->ReqItemId[item_idx];
13871 //data << count;
13872 GetSession()->SendPacket( &data );
13875 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13877 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13879 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13880 if (entry < 0)
13881 // client expected gameobject template id in form (id|0x80000000)
13882 entry = (-entry) | 0x80000000;
13884 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13885 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13886 data << uint32(pQuest->GetQuestId());
13887 data << uint32(entry);
13888 data << uint32(old_count + add_count);
13889 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13890 data << uint64(guid);
13891 GetSession()->SendPacket(&data);
13893 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13894 if( log_slot < MAX_QUEST_LOG_SIZE)
13895 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13898 /*********************************************************/
13899 /*** LOAD SYSTEM ***/
13900 /*********************************************************/
13902 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13904 bool delete_result = true;
13905 if(!result)
13907 // 0 1 2 3 4 5 6 7 8 9
13908 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13909 if(!result) return false;
13911 else delete_result = false;
13913 Field *fields = result->Fetch();
13915 if(!LoadValues( fields[1].GetString()))
13917 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13918 if(delete_result) delete result;
13919 return false;
13922 // overwrite possible wrong/corrupted guid
13923 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13925 m_name = fields[2].GetCppString();
13927 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13928 SetMapId(fields[6].GetUInt32());
13929 // the instance id is not needed at character enum
13931 m_Played_time[0] = fields[7].GetUInt32();
13932 m_Played_time[1] = fields[8].GetUInt32();
13934 m_atLoginFlags = fields[9].GetUInt32();
13936 // I don't see these used anywhere ..
13937 /*_LoadGroup();
13939 _LoadBoundInstances();*/
13941 if (delete_result) delete result;
13943 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13944 m_items[i] = NULL;
13946 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13947 m_deathState = DEAD;
13949 return true;
13952 void Player::_LoadDeclinedNames(QueryResult* result)
13954 if(!result)
13955 return;
13957 if(m_declinedname)
13958 delete m_declinedname;
13960 m_declinedname = new DeclinedName;
13961 Field *fields = result->Fetch();
13962 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13963 m_declinedname->name[i] = fields[i].GetCppString();
13965 delete result;
13968 void Player::_LoadArenaTeamInfo(QueryResult *result)
13970 // arenateamid, played_week, played_season, personal_rating
13971 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13972 if (!result)
13973 return;
13977 Field *fields = result->Fetch();
13979 uint32 arenateamid = fields[0].GetUInt32();
13980 uint32 played_week = fields[1].GetUInt32();
13981 uint32 played_season = fields[2].GetUInt32();
13982 uint32 personal_rating = fields[3].GetUInt32();
13984 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13985 if(!aTeam)
13987 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13988 continue;
13990 uint8 arenaSlot = aTeam->GetSlot();
13992 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13993 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13994 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13995 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13996 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13997 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13999 }while (result->NextRow());
14000 delete result;
14003 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14005 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14006 if(!result)
14007 return false;
14009 Field *fields = result->Fetch();
14011 x = fields[0].GetFloat();
14012 y = fields[1].GetFloat();
14013 z = fields[2].GetFloat();
14014 o = fields[3].GetFloat();
14015 mapid = fields[4].GetUInt32();
14016 in_flight = !fields[5].GetCppString().empty();
14018 delete result;
14019 return true;
14022 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14024 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14025 if( !result )
14026 return false;
14028 Field *fields = result->Fetch();
14030 data = StrSplit(fields[0].GetCppString(), " ");
14032 delete result;
14034 return true;
14037 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14039 if(index >= data.size())
14040 return 0;
14042 return (uint32)atoi(data[index].c_str());
14045 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14047 float result;
14048 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14049 memcpy(&result, &temp, sizeof(result));
14051 return result;
14054 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14056 Tokens data;
14057 if(!LoadValuesArrayFromDB(data,guid))
14058 return 0;
14060 return GetUInt32ValueFromArray(data,index);
14063 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14065 float result;
14066 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14067 memcpy(&result, &temp, sizeof(result));
14069 return result;
14072 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14074 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
14075 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
14076 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14078 if(!result)
14080 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14081 return false;
14084 Field *fields = result->Fetch();
14086 uint32 dbAccountId = fields[1].GetUInt32();
14088 // check if the character's account in the db and the logged in account match.
14089 // player should be able to load/delete character only with correct account!
14090 if( dbAccountId != GetSession()->GetAccountId() )
14092 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14093 delete result;
14094 return false;
14097 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14099 m_name = fields[3].GetCppString();
14101 // check name limitations
14102 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14104 delete result;
14105 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14106 return false;
14109 if(!LoadValues( fields[2].GetString()))
14111 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
14112 delete result;
14113 return false;
14116 // overwrite possible wrong/corrupted guid
14117 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14119 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14120 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14122 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
14123 SetVisibleItemSlot(slot,NULL);
14125 if (m_items[slot])
14127 delete m_items[slot];
14128 m_items[slot] = NULL;
14132 // update money limits
14133 if(GetMoney() > MAX_MONEY_AMOUNT)
14134 SetMoney(MAX_MONEY_AMOUNT);
14136 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14137 outDebugValues();
14139 m_race = fields[4].GetUInt8();
14140 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14141 //Other way is to saves m_team into characters table.
14142 setFactionForRace(m_race);
14143 SetCharm(0);
14145 m_class = fields[5].GetUInt8();
14147 // load home bind and check in same time class/race pair, it used later for restore broken positions
14148 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14149 return false;
14151 InitPrimaryProffesions(); // to max set before any spell loaded
14153 // init saved position, and fix it later if problematic
14154 uint32 transGUID = fields[24].GetUInt32();
14155 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
14156 SetMapId(fields[9].GetUInt32());
14157 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
14159 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14161 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14163 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
14164 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14165 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14167 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14169 // check arena teams integrity
14170 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14172 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14173 if(!arena_team_id)
14174 continue;
14176 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14177 if(at->HaveMember(GetGUID()))
14178 continue;
14180 // arena team not exist or not member, cleanup fields
14181 for(int j =0; j < 6; ++j)
14182 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14185 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14187 if(!IsPositionValid())
14189 sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14190 RelocateToHomebind();
14192 transGUID = 0;
14194 m_movementInfo.t_x = 0.0f;
14195 m_movementInfo.t_y = 0.0f;
14196 m_movementInfo.t_z = 0.0f;
14197 m_movementInfo.t_o = 0.0f;
14200 uint32 bgid = fields[34].GetUInt32();
14201 uint32 bgteam = fields[35].GetUInt32();
14203 if(bgid) //saved in BattleGround
14205 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14207 // check entry point and fix to homebind if need
14208 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14209 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14210 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14212 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid);
14214 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14216 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14217 uint32 queueSlot = AddBattleGroundQueueId(bgQueueTypeId);
14219 SetBattleGroundId(currentBg->GetInstanceID());
14220 SetBGTeam(bgteam);
14222 //join player to battleground group
14223 currentBg->PlayerRelogin(this);
14224 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14226 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14228 else
14230 Relocate(GetBattleGroundEntryPoint());
14231 //RemoveArenaAuras(true);
14234 else
14236 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14237 // if server restart after player save in BG or area
14238 // player can have current coordinates in to BG/Arean map, fix this
14239 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14241 // return to BG master
14242 SetMapId(fields[36].GetUInt32());
14243 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14245 // check entry point and fix to homebind if need
14246 mapEntry = sMapStore.LookupEntry(GetMapId());
14247 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14248 RelocateToHomebind();
14252 if (transGUID != 0)
14254 m_movementInfo.t_x = fields[20].GetFloat();
14255 m_movementInfo.t_y = fields[21].GetFloat();
14256 m_movementInfo.t_z = fields[22].GetFloat();
14257 m_movementInfo.t_o = fields[23].GetFloat();
14259 if( !MaNGOS::IsValidMapCoord(
14260 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14261 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14262 // transport size limited
14263 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14265 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14266 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14267 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14269 RelocateToHomebind();
14271 m_movementInfo.t_x = 0.0f;
14272 m_movementInfo.t_y = 0.0f;
14273 m_movementInfo.t_z = 0.0f;
14274 m_movementInfo.t_o = 0.0f;
14276 transGUID = 0;
14280 if (transGUID != 0)
14282 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14284 if( (*iter)->GetGUIDLow() == transGUID)
14286 m_transport = *iter;
14287 m_transport->AddPassenger(this);
14288 SetMapId(m_transport->GetMapId());
14289 break;
14293 if(!m_transport)
14295 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14296 guid,transGUID);
14298 RelocateToHomebind();
14300 m_movementInfo.t_x = 0.0f;
14301 m_movementInfo.t_y = 0.0f;
14302 m_movementInfo.t_z = 0.0f;
14303 m_movementInfo.t_o = 0.0f;
14305 transGUID = 0;
14309 // NOW player must have valid map
14310 // load the player's map here if it's not already loaded
14311 Map *map = GetMap();
14313 // since the player may not be bound to the map yet, make sure subsequent
14314 // getmap calls won't create new maps
14315 SetInstanceId(map->GetInstanceId());
14317 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14318 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14320 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14321 if(at)
14322 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14323 else
14324 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14327 SaveRecallPosition();
14329 time_t now = time(NULL);
14330 time_t logoutTime = time_t(fields[16].GetUInt64());
14332 // since last logout (in seconds)
14333 uint64 time_diff = uint64(now - logoutTime);
14335 // set value, including drunk invisibility detection
14336 // calculate sobering. after 15 minutes logged out, the player will be sober again
14337 float soberFactor;
14338 if(time_diff > 15*MINUTE)
14339 soberFactor = 0;
14340 else
14341 soberFactor = 1-time_diff/(15.0f*MINUTE);
14342 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14343 SetDrunkValue(newDrunkenValue);
14345 m_rest_bonus = fields[15].GetFloat();
14346 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14347 float bubble0 = 0.031;
14348 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14349 float bubble1 = 0.125;
14351 if((int32)fields[16].GetUInt32() > 0)
14353 float bubble = fields[17].GetUInt32() > 0
14354 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14355 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14357 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14360 m_cinematic = fields[12].GetUInt32();
14361 m_Played_time[0]= fields[13].GetUInt32();
14362 m_Played_time[1]= fields[14].GetUInt32();
14364 m_resetTalentsCost = fields[18].GetUInt32();
14365 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14367 // reserve some flags
14368 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14370 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14371 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14373 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14375 uint32 extraflags = fields[25].GetUInt32();
14377 m_stableSlots = fields[26].GetUInt32();
14378 if(m_stableSlots > 4)
14380 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14381 m_stableSlots = 4;
14384 m_atLoginFlags = fields[27].GetUInt32();
14386 // Honor system
14387 // Update Honor kills data
14388 m_lastHonorUpdateTime = logoutTime;
14389 UpdateHonorFields();
14391 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14392 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14393 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14395 std::string taxi_nodes = fields[31].GetCppString();
14397 delete result;
14399 // clear channel spell data (if saved at channel spell casting)
14400 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14401 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14403 // clear charm/summon related fields
14404 SetCharm(NULL);
14405 SetPet(NULL);
14406 SetCharmerGUID(0);
14407 SetOwnerGUID(0);
14408 SetCreatorGUID(0);
14410 // reset some aura modifiers before aura apply
14411 SetFarSightGUID(0);
14412 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14413 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14415 _LoadSkills();
14417 // make sure the unit is considered out of combat for proper loading
14418 ClearInCombat();
14420 // make sure the unit is considered not in duel for proper loading
14421 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14422 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14424 // remember loaded power/health values to restore after stats initialization and modifier applying
14425 uint32 savedHealth = GetHealth();
14426 uint32 savedPower[MAX_POWERS];
14427 for(uint32 i = 0; i < MAX_POWERS; ++i)
14428 savedPower[i] = GetPower(Powers(i));
14430 // reset stats before loading any modifiers
14431 InitStatsForLevel();
14432 InitTaxiNodesForLevel();
14433 InitGlyphsForLevel();
14434 InitRunes();
14436 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14438 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14439 //_LoadMail();
14441 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14442 _LoadGlyphAuras();
14444 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14445 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14446 m_deathState = DEAD;
14448 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14450 // after spell load, learn rewarded spell if need also
14451 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14452 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14454 // after spell and quest load
14455 InitTalentForLevel();
14456 learnDefaultSpells();
14458 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14460 // must be before inventory (some items required reputation check)
14461 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14463 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14465 // update items with duration and realtime
14466 UpdateItemDuration(time_diff, true);
14468 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14470 // unread mails and next delivery time, actual mails not loaded
14471 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14473 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14475 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14476 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14477 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14479 if(!HasTitle(curTitle))
14480 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14483 // Not finish taxi flight path
14484 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14486 // problems with taxi path loading
14487 TaxiNodesEntry const* nodeEntry = NULL;
14488 if(uint32 node_id = m_taxi.GetTaxiSource())
14489 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14491 if(!nodeEntry) // don't know taxi start node, to homebind
14493 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14494 RelocateToHomebind();
14495 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14497 else // have start node, to it
14499 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14500 SetMapId(nodeEntry->map_id);
14501 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14502 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14504 m_taxi.ClearTaxiDestinations();
14506 else if(uint32 node_id = m_taxi.GetTaxiSource())
14508 // save source node as recall coord to prevent recall and fall from sky
14509 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14510 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14511 m_recallMap = nodeEntry->map_id;
14512 m_recallX = nodeEntry->x;
14513 m_recallY = nodeEntry->y;
14514 m_recallZ = nodeEntry->z;
14516 // flight will started later
14519 // has to be called after last Relocate() in Player::LoadFromDB
14520 SetFallInformation(0, GetPositionZ());
14522 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14524 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14525 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14526 if(!isAlive())
14527 RemoveAllAurasOnDeath();
14529 //apply all stat bonuses from items and auras
14530 SetCanModifyStats(true);
14531 UpdateAllStats();
14533 // restore remembered power/health values (but not more max values)
14534 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14535 for(uint32 i = 0; i < MAX_POWERS; ++i)
14536 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14538 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14539 outDebugValues();
14541 // GM state
14542 if(GetSession()->GetSecurity() > SEC_PLAYER)
14544 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14546 default:
14547 case 0: break; // disable
14548 case 1: SetGameMaster(true); break; // enable
14549 case 2: // save state
14550 if(extraflags & PLAYER_EXTRA_GM_ON)
14551 SetGameMaster(true);
14552 break;
14555 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14557 default:
14558 case 0: SetGMVisible(false); break; // invisible
14559 case 1: break; // visible
14560 case 2: // save state
14561 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14562 SetGMVisible(false);
14563 break;
14566 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14568 default:
14569 case 0: break; // disable
14570 case 1: SetAcceptTicket(true); break; // enable
14571 case 2: // save state
14572 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14573 SetAcceptTicket(true);
14574 break;
14577 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14579 default:
14580 case 0: break; // disable
14581 case 1: SetGMChat(true); break; // enable
14582 case 2: // save state
14583 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14584 SetGMChat(true);
14585 break;
14588 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14590 default:
14591 case 0: break; // disable
14592 case 1: SetAcceptWhispers(true); break; // enable
14593 case 2: // save state
14594 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14595 SetAcceptWhispers(true);
14596 break;
14600 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14602 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14603 m_achievementMgr.CheckAllAchievementCriteria();
14604 return true;
14607 bool Player::isAllowedToLoot(Creature* creature)
14609 if(Player* recipient = creature->GetLootRecipient())
14611 if (recipient == this)
14612 return true;
14613 if( Group* otherGroup = recipient->GetGroup())
14615 Group* thisGroup = GetGroup();
14616 if(!thisGroup)
14617 return false;
14618 return thisGroup == otherGroup;
14620 return false;
14622 else
14623 // prevent other players from looting if the recipient got disconnected
14624 return !creature->hasLootRecipient();
14627 void Player::_LoadActions(QueryResult *result)
14629 m_actionButtons.clear();
14631 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14633 if(result)
14637 Field *fields = result->Fetch();
14639 uint8 button = fields[0].GetUInt8();
14641 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14643 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14645 while( result->NextRow() );
14647 delete result;
14651 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14653 m_Auras.clear();
14654 for (int i = 0; i < TOTAL_AURAS; i++)
14655 m_modAuras[i].clear();
14657 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14659 if(result)
14663 Field *fields = result->Fetch();
14664 uint64 caster_guid = fields[0].GetUInt64();
14665 uint32 spellid = fields[1].GetUInt32();
14666 uint32 effindex = fields[2].GetUInt32();
14667 uint32 stackcount = fields[3].GetUInt32();
14668 int32 damage = (int32)fields[4].GetUInt32();
14669 int32 maxduration = (int32)fields[5].GetUInt32();
14670 int32 remaintime = (int32)fields[6].GetUInt32();
14671 int32 remaincharges = (int32)fields[7].GetUInt32();
14673 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14674 if(!spellproto)
14676 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14677 continue;
14680 if(effindex >= 3)
14682 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14683 continue;
14686 // negative effects should continue counting down after logout
14687 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14689 if(remaintime <= int32(timediff))
14690 continue;
14692 remaintime -= timediff;
14695 // prevent wrong values of remaincharges
14696 if(spellproto->procCharges)
14698 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14699 remaincharges = spellproto->procCharges;
14701 else
14702 remaincharges = 0;
14704 //do not load single target auras (unless they were cast by the player)
14705 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14706 continue;
14708 for(uint32 i=0; i<stackcount; i++)
14710 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14711 if(!damage)
14712 damage = aura->GetModifier()->m_amount;
14713 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14714 AddAura(aura);
14715 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14718 while( result->NextRow() );
14720 delete result;
14723 if(m_class == CLASS_WARRIOR)
14724 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14727 void Player::_LoadGlyphAuras()
14729 for (uint8 i = 0; i <= MAX_GLYPH_SLOT_INDEX; ++i)
14731 if (uint32 glyph = GetGlyph(i))
14733 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14735 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14737 if(gp->TypeFlags == gs->TypeFlags)
14739 CastSpell(this, gp->SpellId, true);
14740 continue;
14742 else
14743 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14745 else
14746 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14748 else
14749 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14751 // On any error remove glyph
14752 SetGlyph(i, 0);
14757 void Player::LoadCorpse()
14759 if( isAlive() )
14761 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14763 else
14765 if(Corpse *corpse = GetCorpse())
14767 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14769 else
14771 //Prevent Dead Player login without corpse
14772 ResurrectPlayer(0.5f);
14777 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14779 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
14780 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14781 //NOTE: the "order by `bag`" is important because it makes sure
14782 //the bagMap is filled before items in the bags are loaded
14783 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14784 //expected to be equipped before offhand items (TODO: fixme)
14786 uint32 zone = GetZoneId();
14788 if (result)
14790 std::list<Item*> problematicItems;
14792 // prevent items from being added to the queue when stored
14793 m_itemUpdateQueueBlocked = true;
14796 Field *fields = result->Fetch();
14797 uint32 bag_guid = fields[1].GetUInt32();
14798 uint8 slot = fields[2].GetUInt8();
14799 uint32 item_guid = fields[3].GetUInt32();
14800 uint32 item_id = fields[4].GetUInt32();
14802 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14804 if(!proto)
14806 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14807 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14808 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14809 continue;
14812 Item *item = NewItemOrBag(proto);
14814 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14816 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14817 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14818 item->FSetState(ITEM_REMOVED);
14819 item->SaveToDB(); // it also deletes item object !
14820 continue;
14823 // not allow have in alive state item limited to another map/zone
14824 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14826 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14827 item->FSetState(ITEM_REMOVED);
14828 item->SaveToDB(); // it also deletes item object !
14829 continue;
14832 // "Conjured items disappear if you are logged out for more than 15 minutes"
14833 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14835 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14836 item->FSetState(ITEM_REMOVED);
14837 item->SaveToDB(); // it also deletes item object !
14838 continue;
14841 bool success = true;
14843 if (!bag_guid)
14845 // the item is not in a bag
14846 item->SetContainer( NULL );
14847 item->SetSlot(slot);
14849 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14851 ItemPosCountVec dest;
14852 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14853 item = StoreItem(dest, item, true);
14854 else
14855 success = false;
14857 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14859 uint16 dest;
14860 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14861 QuickEquipItem(dest, item);
14862 else
14863 success = false;
14865 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14867 ItemPosCountVec dest;
14868 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14869 item = BankItem(dest, item, true);
14870 else
14871 success = false;
14874 if(success)
14876 // store bags that may contain items in them
14877 if(item->IsBag() && IsBagPos(item->GetPos()))
14878 bagMap[item_guid] = (Bag*)item;
14881 else
14883 item->SetSlot(NULL_SLOT);
14884 // the item is in a bag, find the bag
14885 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14886 if(itr != bagMap.end())
14887 itr->second->StoreItem(slot, item, true );
14888 else
14889 success = false;
14892 // item's state may have changed after stored
14893 if (success)
14894 item->SetState(ITEM_UNCHANGED, this);
14895 else
14897 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);
14898 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14899 problematicItems.push_back(item);
14901 } while (result->NextRow());
14903 delete result;
14904 m_itemUpdateQueueBlocked = false;
14906 // send by mail problematic items
14907 while(!problematicItems.empty())
14909 // fill mail
14910 MailItemsInfo mi; // item list preparing
14912 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14914 Item* item = problematicItems.front();
14915 problematicItems.pop_front();
14917 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14920 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14922 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14925 //if(isAlive())
14926 _ApplyAllItemMods();
14929 // load mailed item which should receive current player
14930 void Player::_LoadMailedItems(Mail *mail)
14932 // data needs to be at first place for Item::LoadFromDB
14933 QueryResult* result = CharacterDatabase.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail->messageID);
14934 if(!result)
14935 return;
14939 Field *fields = result->Fetch();
14940 uint32 item_guid_low = fields[1].GetUInt32();
14941 uint32 item_template = fields[2].GetUInt32();
14943 mail->AddItem(item_guid_low, item_template);
14945 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14947 if(!proto)
14949 sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14950 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14951 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14952 continue;
14955 Item *item = NewItemOrBag(proto);
14957 if(!item->LoadFromDB(item_guid_low, 0, result))
14959 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14960 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14961 item->FSetState(ITEM_REMOVED);
14962 item->SaveToDB(); // it also deletes item object !
14963 continue;
14966 AddMItem(item);
14967 } while (result->NextRow());
14969 delete result;
14972 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14974 //set a count of unread mails
14975 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14976 if (resultUnread)
14978 Field *fieldMail = resultUnread->Fetch();
14979 unReadMails = fieldMail[0].GetUInt8();
14980 delete resultUnread;
14983 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14984 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14985 if (resultDelivery)
14987 Field *fieldMail = resultDelivery->Fetch();
14988 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14989 delete resultDelivery;
14993 void Player::_LoadMail()
14995 m_mail.clear();
14996 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14997 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
14998 if(result)
15002 Field *fields = result->Fetch();
15003 Mail *m = new Mail;
15004 m->messageID = fields[0].GetUInt32();
15005 m->messageType = fields[1].GetUInt8();
15006 m->sender = fields[2].GetUInt32();
15007 m->receiver = fields[3].GetUInt32();
15008 m->subject = fields[4].GetCppString();
15009 m->itemTextId = fields[5].GetUInt32();
15010 bool has_items = fields[6].GetBool();
15011 m->expire_time = (time_t)fields[7].GetUInt64();
15012 m->deliver_time = (time_t)fields[8].GetUInt64();
15013 m->money = fields[9].GetUInt32();
15014 m->COD = fields[10].GetUInt32();
15015 m->checked = fields[11].GetUInt32();
15016 m->stationery = fields[12].GetUInt8();
15017 m->mailTemplateId = fields[13].GetInt16();
15019 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15021 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15022 m->mailTemplateId = 0;
15025 m->state = MAIL_STATE_UNCHANGED;
15027 if (has_items)
15028 _LoadMailedItems(m);
15030 m_mail.push_back(m);
15031 } while( result->NextRow() );
15032 delete result;
15034 m_mailsLoaded = true;
15037 void Player::LoadPet()
15039 //fixme: the pet should still be loaded if the player is not in world
15040 // just not added to the map
15041 if(IsInWorld())
15043 Pet *pet = new Pet;
15044 if(!pet->LoadPetFromDB(this,0,0,true))
15045 delete pet;
15049 void Player::_LoadQuestStatus(QueryResult *result)
15051 mQuestStatus.clear();
15053 uint32 slot = 0;
15055 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15056 //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());
15058 if(result)
15062 Field *fields = result->Fetch();
15064 uint32 quest_id = fields[0].GetUInt32();
15065 // used to be new, no delete?
15066 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15067 if( pQuest )
15069 // find or create
15070 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15072 uint32 qstatus = fields[1].GetUInt32();
15073 if(qstatus < MAX_QUEST_STATUS)
15074 questStatusData.m_status = QuestStatus(qstatus);
15075 else
15077 questStatusData.m_status = QUEST_STATUS_NONE;
15078 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15081 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15082 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15084 time_t quest_time = time_t(fields[4].GetUInt64());
15086 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15088 AddTimedQuest( quest_id );
15090 if (quest_time <= sWorld.GetGameTime())
15091 questStatusData.m_timer = 1;
15092 else
15093 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
15095 else
15096 quest_time = 0;
15098 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15099 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15100 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15101 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15102 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15103 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15104 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15105 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15107 questStatusData.uState = QUEST_UNCHANGED;
15109 // add to quest log
15110 if( slot < MAX_QUEST_LOG_SIZE &&
15111 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
15112 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
15113 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15115 SetQuestSlot(slot,quest_id,quest_time);
15117 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15118 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
15120 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15121 if(questStatusData.m_creatureOrGOcount[idx])
15122 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
15124 ++slot;
15127 if(questStatusData.m_rewarded)
15129 // learn rewarded spell if unknown
15130 learnQuestRewardedSpells(pQuest);
15132 // set rewarded title if any
15133 if(pQuest->GetCharTitleId())
15135 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15136 SetTitle(titleEntry);
15139 if(pQuest->GetBonusTalents())
15140 m_questRewardTalentCount+=pQuest->GetBonusTalents();
15143 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15146 while( result->NextRow() );
15148 delete result;
15151 // clear quest log tail
15152 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15153 SetQuestSlot(i,0);
15156 void Player::_LoadDailyQuestStatus(QueryResult *result)
15158 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15159 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15161 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15163 if(result)
15165 uint32 quest_daily_idx = 0;
15169 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15171 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15172 break;
15175 Field *fields = result->Fetch();
15177 uint32 quest_id = fields[0].GetUInt32();
15179 // save _any_ from daily quest times (it must be after last reset anyway)
15180 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15182 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15183 if( !pQuest )
15184 continue;
15186 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15187 ++quest_daily_idx;
15189 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15191 while( result->NextRow() );
15193 delete result;
15196 m_DailyQuestChanged = false;
15199 void Player::_LoadReputation(QueryResult *result)
15201 m_factions.clear();
15203 // Set initial reputations (so everything is nifty before DB data load)
15204 SetInitialFactions();
15206 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15208 if(result)
15212 Field *fields = result->Fetch();
15214 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
15215 if( factionEntry && (factionEntry->reputationListID >= 0))
15217 FactionState* faction = &m_factions[factionEntry->reputationListID];
15219 // update standing to current
15220 faction->Standing = int32(fields[1].GetUInt32());
15222 uint32 dbFactionFlags = fields[2].GetUInt32();
15224 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
15225 SetFactionVisible(faction); // have internal checks for forced invisibility
15227 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
15228 SetFactionInactive(faction,true); // have internal checks for visibility requirement
15230 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
15231 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15232 else // DB not at war
15234 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15235 if( faction->Flags & FACTION_FLAG_VISIBLE )
15236 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15239 // set atWar for hostile
15240 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
15241 SetFactionAtWar(faction,true);
15243 // reset changed flag if values similar to saved in DB
15244 if(faction->Flags==dbFactionFlags)
15245 faction->Changed = false;
15248 while( result->NextRow() );
15250 delete result;
15254 void Player::_LoadSpells(QueryResult *result)
15256 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15258 if(result)
15262 Field *fields = result->Fetch();
15264 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15266 while( result->NextRow() );
15268 delete result;
15272 void Player::_LoadTutorials(QueryResult *result)
15274 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15276 if(result)
15280 Field *fields = result->Fetch();
15282 for (int iI=0; iI<8; iI++)
15283 m_Tutorials[iI] = fields[iI].GetUInt32();
15285 while( result->NextRow() );
15287 delete result;
15290 m_TutorialsChanged = false;
15293 void Player::_LoadGroup(QueryResult *result)
15295 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15296 if(result)
15298 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15299 delete result;
15300 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15301 if(group)
15303 uint8 subgroup = group->GetMemberGroup(GetGUID());
15304 SetGroup(group, subgroup);
15305 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15307 // the group leader may change the instance difficulty while the player is offline
15308 SetDifficulty(group->GetDifficulty());
15314 void Player::_LoadBoundInstances(QueryResult *result)
15316 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15317 m_boundInstances[i].clear();
15319 Group *group = GetGroup();
15321 //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));
15322 if(result)
15326 Field *fields = result->Fetch();
15327 bool perm = fields[1].GetBool();
15328 uint32 mapId = fields[2].GetUInt32();
15329 uint32 instanceId = fields[0].GetUInt32();
15330 uint8 difficulty = fields[3].GetUInt8();
15331 time_t resetTime = (time_t)fields[4].GetUInt64();
15332 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15333 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15334 // and in that case it is not used
15336 if(!perm && group)
15338 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);
15339 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15340 continue;
15343 // since non permanent binds are always solo bind, they can always be reset
15344 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15345 if(save) BindToInstance(save, perm, true);
15346 } while(result->NextRow());
15347 delete result;
15351 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15353 // some instances only have one difficulty
15354 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15355 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15357 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15358 if(itr != m_boundInstances[difficulty].end())
15359 return &itr->second;
15360 else
15361 return NULL;
15364 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15366 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15367 UnbindInstance(itr, difficulty, unload);
15370 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15372 if(itr != m_boundInstances[difficulty].end())
15374 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15375 itr->second.save->RemovePlayer(this); // save can become invalid
15376 m_boundInstances[difficulty].erase(itr++);
15380 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15382 if(save)
15384 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15385 if(bind.save)
15387 // update the save when the group kills a boss
15388 if(permanent != bind.perm || save != bind.save)
15389 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());
15391 else
15392 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15394 if(bind.save != save)
15396 if(bind.save) bind.save->RemovePlayer(this);
15397 save->AddPlayer(this);
15400 if(permanent) save->SetCanReset(false);
15402 bind.save = save;
15403 bind.perm = permanent;
15404 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());
15405 return &bind;
15407 else
15408 return NULL;
15411 void Player::SendRaidInfo()
15413 uint32 counter = 0;
15415 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15417 size_t p_counter = data.wpos();
15418 data << uint32(counter); // placeholder
15420 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15422 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15424 if(itr->second.perm)
15426 InstanceSave *save = itr->second.save;
15427 data << uint32(save->GetMapId());
15428 data << uint32(save->GetResetTime() - time(NULL));
15429 data << uint32(save->GetInstanceId());
15430 data << uint32(save->GetDifficulty());
15431 ++counter;
15435 data.put<uint32>(p_counter,counter);
15436 GetSession()->SendPacket(&data);
15440 - called on every successful teleportation to a map
15442 void Player::SendSavedInstances()
15444 bool hasBeenSaved = false;
15445 WorldPacket data;
15447 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15449 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15451 if(itr->second.perm) // only permanent binds are sent
15453 hasBeenSaved = true;
15454 break;
15459 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15460 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15461 data << uint32(hasBeenSaved);
15462 GetSession()->SendPacket(&data);
15464 if(!hasBeenSaved)
15465 return;
15467 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15469 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15471 if(itr->second.perm)
15473 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15474 data << uint32(itr->second.save->GetMapId());
15475 GetSession()->SendPacket(&data);
15481 /// convert the player's binds to the group
15482 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15484 bool has_binds = false;
15485 bool has_solo = false;
15487 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15488 assert(player_guid);
15490 // copy all binds to the group, when changing leader it's assumed the character
15491 // will not have any solo binds
15493 if(player)
15495 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15497 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15499 has_binds = true;
15500 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15501 // permanent binds are not removed
15502 if(!itr->second.perm)
15504 player->UnbindInstance(itr, i, true); // increments itr
15505 has_solo = true;
15507 else
15508 ++itr;
15513 // if the player's not online we don't know what binds it has
15514 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
15515 // the following should not get executed when changing leaders
15516 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15519 bool Player::_LoadHomeBind(QueryResult *result)
15521 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15522 if(!info)
15524 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15525 return false;
15528 bool ok = false;
15529 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15530 if (result)
15532 Field *fields = result->Fetch();
15533 m_homebindMapId = fields[0].GetUInt32();
15534 m_homebindZoneId = fields[1].GetUInt16();
15535 m_homebindX = fields[2].GetFloat();
15536 m_homebindY = fields[3].GetFloat();
15537 m_homebindZ = fields[4].GetFloat();
15538 delete result;
15540 // accept saved data only for valid position (and non instanceable)
15541 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15542 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15544 ok = true;
15546 else
15547 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15550 if(!ok)
15552 m_homebindMapId = info->mapId;
15553 m_homebindZoneId = info->zoneId;
15554 m_homebindX = info->positionX;
15555 m_homebindY = info->positionY;
15556 m_homebindZ = info->positionZ;
15558 CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15561 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15562 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15564 return true;
15567 /*********************************************************/
15568 /*** SAVE SYSTEM ***/
15569 /*********************************************************/
15571 void Player::SaveToDB()
15573 // delay auto save at any saves (manual, in code, or autosave)
15574 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15576 // first save/honor gain after midnight will also update the player's honor fields
15577 UpdateHonorFields();
15579 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15580 //save, far from tavern/city
15581 //save, but in tavern/city
15582 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15583 outDebugValues();
15585 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15586 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15587 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15588 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15589 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15590 uint32 tmp_displayid = GetDisplayId();
15592 // Set player sit state to standing on save, also stealth and shifted form
15593 SetStandState(UNIT_STAND_STATE_STAND); // stand state
15594 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // stand flags?
15595 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15596 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15597 SetDisplayId(GetNativeDisplayId());
15599 bool inworld = IsInWorld();
15601 CharacterDatabase.BeginTransaction();
15603 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15605 std::string sql_name = m_name;
15606 CharacterDatabase.escape_string(sql_name);
15608 std::ostringstream ss;
15609 ss << "INSERT INTO characters (guid,account,name,race,class,"
15610 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15611 "taximask, online, cinematic, "
15612 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15613 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15614 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15615 << GetGUIDLow() << ", "
15616 << GetSession()->GetAccountId() << ", '"
15617 << sql_name << "', "
15618 << m_race << ", "
15619 << m_class << ", ";
15621 if(!IsBeingTeleported())
15623 ss << GetMapId() << ", "
15624 << (uint32)GetDifficulty() << ", "
15625 << finiteAlways(GetPositionX()) << ", "
15626 << finiteAlways(GetPositionY()) << ", "
15627 << finiteAlways(GetPositionZ()) << ", "
15628 << finiteAlways(GetOrientation()) << ", '";
15630 else
15632 ss << GetTeleportDest().mapid << ", "
15633 << (uint32)GetDifficulty() << ", "
15634 << finiteAlways(GetTeleportDest().x) << ", "
15635 << finiteAlways(GetTeleportDest().y) << ", "
15636 << finiteAlways(GetTeleportDest().z) << ", "
15637 << finiteAlways(GetTeleportDest().o) << ", '";
15640 uint16 i;
15641 for( i = 0; i < m_valuesCount; i++ )
15643 ss << GetUInt32Value(i) << " ";
15646 ss << "', ";
15648 ss << m_taxi; // string with TaxiMaskSize numbers
15650 ss << ", ";
15651 ss << (inworld ? 1 : 0);
15653 ss << ", ";
15654 ss << m_cinematic;
15656 ss << ", ";
15657 ss << m_Played_time[0];
15658 ss << ", ";
15659 ss << m_Played_time[1];
15661 ss << ", ";
15662 ss << finiteAlways(m_rest_bonus);
15663 ss << ", ";
15664 ss << (uint64)time(NULL);
15665 ss << ", ";
15666 ss << is_save_resting;
15667 ss << ", ";
15668 ss << m_resetTalentsCost;
15669 ss << ", ";
15670 ss << (uint64)m_resetTalentsTime;
15672 ss << ", ";
15673 ss << finiteAlways(m_movementInfo.t_x);
15674 ss << ", ";
15675 ss << finiteAlways(m_movementInfo.t_y);
15676 ss << ", ";
15677 ss << finiteAlways(m_movementInfo.t_z);
15678 ss << ", ";
15679 ss << finiteAlways(m_movementInfo.t_o);
15680 ss << ", ";
15681 if (m_transport)
15682 ss << m_transport->GetGUIDLow();
15683 else
15684 ss << "0";
15686 ss << ", ";
15687 ss << m_ExtraFlags;
15689 ss << ", ";
15690 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15692 ss << ", ";
15693 ss << uint32(m_atLoginFlags);
15695 ss << ", ";
15696 ss << GetZoneId();
15698 ss << ", ";
15699 ss << (uint64)m_deathExpireTime;
15701 ss << ", '";
15702 ss << m_taxi.SaveTaxiDestinationsToString();
15703 ss << "', '0', ";
15704 ss << GetBattleGroundId();
15705 ss << ", ";
15706 ss << GetBGTeam();
15707 ss << ", ";
15708 ss << m_bgEntryPoint.mapid << ", "
15709 << finiteAlways(m_bgEntryPoint.x) << ", "
15710 << finiteAlways(m_bgEntryPoint.y) << ", "
15711 << finiteAlways(m_bgEntryPoint.z) << ", "
15712 << finiteAlways(m_bgEntryPoint.o);
15713 ss << ")";
15715 CharacterDatabase.Execute( ss.str().c_str() );
15717 if(m_mailsUpdated) //save mails only when needed
15718 _SaveMail();
15720 _SaveInventory();
15721 _SaveQuestStatus();
15722 _SaveDailyQuestStatus();
15723 _SaveTutorials();
15724 _SaveSpells();
15725 _SaveSpellCooldowns();
15726 _SaveActions();
15727 _SaveAuras();
15728 _SaveReputation();
15730 CharacterDatabase.CommitTransaction();
15732 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15733 SetDisplayId(tmp_displayid);
15734 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15735 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15736 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15737 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15739 // save pet (hunter pet level and experience and all type pets health/mana).
15740 if(Pet* pet = GetPet())
15741 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15742 m_achievementMgr.SaveToDB();
15745 // fast save function for item/money cheating preventing - save only inventory and money state
15746 void Player::SaveInventoryAndGoldToDB()
15748 _SaveInventory();
15749 //money is in data field
15750 SaveDataFieldToDB();
15753 void Player::_SaveActions()
15755 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15757 switch (itr->second.uState)
15759 case ACTIONBUTTON_NEW:
15760 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15761 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15762 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15763 ++itr;
15764 break;
15765 case ACTIONBUTTON_CHANGED:
15766 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15767 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15768 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15769 ++itr;
15770 break;
15771 case ACTIONBUTTON_DELETED:
15772 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15773 m_actionButtons.erase(itr++);
15774 break;
15775 default:
15776 ++itr;
15777 break;
15782 void Player::_SaveAuras()
15784 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15786 AuraMap const& auras = GetAuras();
15788 if (auras.empty())
15789 return;
15791 spellEffectPair lastEffectPair = auras.begin()->first;
15792 uint32 stackCounter = 1;
15794 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15796 if(itr == auras.end() || lastEffectPair != itr->first)
15798 AuraMap::const_iterator itr2 = itr;
15799 // save previous spellEffectPair to db
15800 itr2--;
15801 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15803 //skip all auras from spells that are passive or need a shapeshift
15804 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15806 //do not save single target auras (unless they were cast by the player)
15807 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15809 uint8 i;
15810 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15811 for (i = 0; i < 3; i++)
15812 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15813 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15814 break;
15816 if (i == 3)
15818 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15819 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15820 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->GetAuraCharges()));
15825 if(itr == auras.end())
15826 break;
15829 if (lastEffectPair == itr->first)
15830 stackCounter++;
15831 else
15833 lastEffectPair = itr->first;
15834 stackCounter = 1;
15839 void Player::_SaveInventory()
15841 // force items in buyback slots to new state
15842 // and remove those that aren't already
15843 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15845 Item *item = m_items[i];
15846 if (!item || item->GetState() == ITEM_NEW) continue;
15847 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15848 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15849 m_items[i]->FSetState(ITEM_NEW);
15852 // update enchantment durations
15853 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15855 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15858 // if no changes
15859 if (m_itemUpdateQueue.empty()) return;
15861 // do not save if the update queue is corrupt
15862 bool error = false;
15863 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15865 Item *item = m_itemUpdateQueue[i];
15866 if(!item || item->GetState() == ITEM_REMOVED) continue;
15867 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15869 if (test == NULL)
15871 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());
15872 error = true;
15874 else if (test != item)
15876 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());
15877 error = true;
15881 if (error)
15883 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15884 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15885 return;
15888 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15890 Item *item = m_itemUpdateQueue[i];
15891 if(!item) continue;
15893 Bag *container = item->GetContainer();
15894 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15896 switch(item->GetState())
15898 case ITEM_NEW:
15899 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());
15900 break;
15901 case ITEM_CHANGED:
15902 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());
15903 break;
15904 case ITEM_REMOVED:
15905 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15906 break;
15907 case ITEM_UNCHANGED:
15908 break;
15911 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15913 m_itemUpdateQueue.clear();
15916 void Player::_SaveMail()
15918 if (!m_mailsLoaded)
15919 return;
15921 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15923 Mail *m = (*itr);
15924 if (m->state == MAIL_STATE_CHANGED)
15926 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15927 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15928 if(m->removedItems.size())
15930 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15931 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15932 m->removedItems.clear();
15934 m->state = MAIL_STATE_UNCHANGED;
15936 else if (m->state == MAIL_STATE_DELETED)
15938 if (m->HasItems())
15939 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15940 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15941 if (m->itemTextId)
15942 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15943 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15944 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15948 //deallocate deleted mails...
15949 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15951 if ((*itr)->state == MAIL_STATE_DELETED)
15953 Mail* m = *itr;
15954 m_mail.erase(itr);
15955 delete m;
15956 itr = m_mail.begin();
15958 else
15959 ++itr;
15962 m_mailsUpdated = false;
15965 void Player::_SaveQuestStatus()
15967 // we don't need transactions here.
15968 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15970 switch (i->second.uState)
15972 case QUEST_NEW :
15973 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15974 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15975 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15976 break;
15977 case QUEST_CHANGED :
15978 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15979 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15980 break;
15981 case QUEST_UNCHANGED:
15982 break;
15984 i->second.uState = QUEST_UNCHANGED;
15988 void Player::_SaveDailyQuestStatus()
15990 if(!m_DailyQuestChanged)
15991 return;
15993 m_DailyQuestChanged = false;
15995 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15997 // we don't need transactions here.
15998 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15999 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16000 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16001 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
16002 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16005 void Player::_SaveReputation()
16007 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
16009 if (itr->second.Changed)
16011 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
16012 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
16013 itr->second.Changed = false;
16018 void Player::_SaveSpells()
16020 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16022 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16023 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16025 // add only changed/new not dependent spells
16026 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16027 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);
16029 if (itr->second->state == PLAYERSPELL_REMOVED)
16031 delete itr->second;
16032 m_spells.erase(itr++);
16034 else
16036 itr->second->state = PLAYERSPELL_UNCHANGED;
16037 ++itr;
16043 void Player::_SaveTutorials()
16045 if(!m_TutorialsChanged)
16046 return;
16048 uint32 Rows=0;
16049 // it's better than rebuilding indexes multiple times
16050 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
16051 if(result)
16053 Rows = result->Fetch()[0].GetUInt32();
16054 delete result;
16057 if (Rows)
16059 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
16060 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
16062 else
16064 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
16067 m_TutorialsChanged = false;
16070 void Player::outDebugValues() const
16072 if(!sLog.IsOutDebug()) // optimize disabled debug output
16073 return;
16075 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16076 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16077 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16078 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
16079 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16080 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16081 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16082 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16083 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16084 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16085 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16086 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16089 /*********************************************************/
16090 /*** FLOOD FILTER SYSTEM ***/
16091 /*********************************************************/
16093 void Player::UpdateSpeakTime()
16095 // ignore chat spam protection for GMs in any mode
16096 if(GetSession()->GetSecurity() > SEC_PLAYER)
16097 return;
16099 time_t current = time (NULL);
16100 if(m_speakTime > current)
16102 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16103 if(!max_count)
16104 return;
16106 ++m_speakCount;
16107 if(m_speakCount >= max_count)
16109 // prevent overwrite mute time, if message send just before mutes set, for example.
16110 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16111 if(GetSession()->m_muteTime < new_mute)
16112 GetSession()->m_muteTime = new_mute;
16114 m_speakCount = 0;
16117 else
16118 m_speakCount = 0;
16120 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16123 bool Player::CanSpeak() const
16125 return GetSession()->m_muteTime <= time (NULL);
16128 /*********************************************************/
16129 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16130 /*********************************************************/
16132 void Player::SendAttackSwingNotInRange()
16134 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16135 GetSession()->SendPacket( &data );
16138 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16140 std::ostringstream ss;
16141 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16142 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16143 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16144 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16145 sLog.outDebug(ss.str().c_str());
16146 CharacterDatabase.Execute(ss.str().c_str());
16149 void Player::SaveDataFieldToDB()
16151 std::ostringstream ss;
16152 ss<<"UPDATE characters SET data='";
16154 for(uint16 i = 0; i < m_valuesCount; i++ )
16156 ss << GetUInt32Value(i) << " ";
16158 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16160 CharacterDatabase.Execute(ss.str().c_str());
16163 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16165 std::ostringstream ss2;
16166 ss2<<"UPDATE characters SET data='";
16167 int i=0;
16168 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16170 ss2<<tokens[i]<<" ";
16172 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16174 return CharacterDatabase.Execute(ss2.str().c_str());
16177 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16179 char buf[11];
16180 snprintf(buf,11,"%u",value);
16182 if(index >= tokens.size())
16183 return;
16185 tokens[index] = buf;
16188 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16190 Tokens tokens;
16191 if(!LoadValuesArrayFromDB(tokens,guid))
16192 return;
16194 if(index >= tokens.size())
16195 return;
16197 char buf[11];
16198 snprintf(buf,11,"%u",value);
16199 tokens[index] = buf;
16201 SaveValuesArrayInDB(tokens,guid);
16204 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16206 uint32 temp;
16207 memcpy(&temp, &value, sizeof(value));
16208 Player::SetUInt32ValueInDB(index, temp, guid);
16211 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16213 Tokens tokens;
16214 if(!LoadValuesArrayFromDB(tokens, guid))
16215 return;
16217 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
16218 uint8 race = unit_bytes0 & 0xFF;
16219 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
16221 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
16222 if(!info)
16223 return;
16225 unit_bytes0 &= ~(0xFF << 16);
16226 unit_bytes0 |= (gender << 16);
16227 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
16229 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16230 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16232 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16234 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16235 player_bytes2 &= ~0xFF;
16236 player_bytes2 |= facialHair;
16237 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16239 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16240 player_bytes3 &= ~0xFF;
16241 player_bytes3 |= gender;
16242 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16244 SaveValuesArrayInDB(tokens, guid);
16247 void Player::SendAttackSwingNotStanding()
16249 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16250 GetSession()->SendPacket( &data );
16253 void Player::SendAttackSwingDeadTarget()
16255 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16256 GetSession()->SendPacket( &data );
16259 void Player::SendAttackSwingCantAttack()
16261 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16262 GetSession()->SendPacket( &data );
16265 void Player::SendAttackSwingCancelAttack()
16267 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16268 GetSession()->SendPacket( &data );
16271 void Player::SendAttackSwingBadFacingAttack()
16273 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16274 GetSession()->SendPacket( &data );
16277 void Player::SendAutoRepeatCancel()
16279 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16280 data.append(GetPackGUID()); // may be it's target guid
16281 GetSession()->SendPacket( &data );
16284 void Player::PlaySound(uint32 Sound, bool OnlySelf)
16286 WorldPacket data(SMSG_PLAY_SOUND, 4);
16287 data << Sound;
16288 if (OnlySelf)
16289 GetSession()->SendPacket( &data );
16290 else
16291 SendMessageToSet( &data, true );
16294 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16296 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16297 data << Area;
16298 data << Experience;
16299 GetSession()->SendPacket(&data);
16302 void Player::SendDungeonDifficulty(bool IsInGroup)
16304 uint8 val = 0x00000001;
16305 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16306 data << (uint32)GetDifficulty();
16307 data << uint32(val);
16308 data << uint32(IsInGroup);
16309 GetSession()->SendPacket(&data);
16312 void Player::SendResetFailedNotify(uint32 mapid)
16314 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16315 data << uint32(mapid);
16316 GetSession()->SendPacket(&data);
16319 /// Reset all solo instances and optionally send a message on success for each
16320 void Player::ResetInstances(uint8 method)
16322 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16324 // we assume that when the difficulty changes, all instances that can be reset will be
16325 uint8 dif = GetDifficulty();
16327 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16329 InstanceSave *p = itr->second.save;
16330 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16331 if(!entry || !p->CanReset())
16333 ++itr;
16334 continue;
16337 if(method == INSTANCE_RESET_ALL)
16339 // the "reset all instances" method can only reset normal maps
16340 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16342 ++itr;
16343 continue;
16347 // if the map is loaded, reset it
16348 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16349 if(map && map->IsDungeon())
16350 ((InstanceMap*)map)->Reset(method);
16352 // since this is a solo instance there should not be any players inside
16353 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16354 SendResetInstanceSuccess(p->GetMapId());
16356 p->DeleteFromDB();
16357 m_boundInstances[dif].erase(itr++);
16359 // the following should remove the instance save from the manager and delete it as well
16360 p->RemovePlayer(this);
16364 void Player::SendResetInstanceSuccess(uint32 MapId)
16366 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16367 data << MapId;
16368 GetSession()->SendPacket(&data);
16371 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16373 // TODO: find what other fail reasons there are besides players in the instance
16374 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16375 data << reason;
16376 data << MapId;
16377 GetSession()->SendPacket(&data);
16380 /*********************************************************/
16381 /*** Update timers ***/
16382 /*********************************************************/
16384 ///checks the 15 afk reports per 5 minutes limit
16385 void Player::UpdateAfkReport(time_t currTime)
16387 if(m_bgAfkReportedTimer <= currTime)
16389 m_bgAfkReportedCount = 0;
16390 m_bgAfkReportedTimer = currTime+5*MINUTE;
16394 void Player::UpdateContestedPvP(uint32 diff)
16396 if(!m_contestedPvPTimer||isInCombat())
16397 return;
16398 if(m_contestedPvPTimer <= diff)
16400 ResetContestedPvP();
16402 else
16403 m_contestedPvPTimer -= diff;
16406 void Player::UpdatePvPFlag(time_t currTime)
16408 if(!IsPvP())
16409 return;
16410 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16411 return;
16413 UpdatePvP(false);
16416 void Player::UpdateDuelFlag(time_t currTime)
16418 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16419 return;
16421 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16422 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16424 duel->startTimer = 0;
16425 duel->startTime = currTime;
16426 duel->opponent->duel->startTimer = 0;
16427 duel->opponent->duel->startTime = currTime;
16430 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16432 if(!pet)
16433 pet = GetPet();
16435 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16437 //returning of reagents only for players, so best done here
16438 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16439 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16441 if(spellInfo)
16443 for(uint32 i = 0; i < 7; ++i)
16445 if(spellInfo->Reagent[i] > 0)
16447 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16448 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16449 if( msg == EQUIP_ERR_OK )
16451 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16452 if(IsInWorld())
16453 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16458 m_temporaryUnsummonedPetNumber = 0;
16461 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16462 return;
16464 // only if current pet in slot
16465 switch(pet->getPetType())
16467 case MINI_PET:
16468 m_miniPet = 0;
16469 break;
16470 case GUARDIAN_PET:
16471 m_guardianPets.erase(pet->GetGUID());
16472 break;
16473 default:
16474 if(GetPetGUID() == pet->GetGUID())
16475 SetPet(NULL);
16476 break;
16479 pet->CombatStop();
16481 if(returnreagent)
16483 switch(pet->GetEntry())
16485 //warlock pets except imp are removed(?) when logging out
16486 case 1860:
16487 case 1863:
16488 case 417:
16489 case 17252:
16490 mode = PET_SAVE_NOT_IN_SLOT;
16491 break;
16495 pet->SavePetToDB(mode);
16497 pet->CleanupsBeforeDelete();
16498 pet->AddObjectToRemoveList();
16499 pet->m_removed = true;
16501 if(pet->isControlled())
16503 WorldPacket data(SMSG_PET_SPELLS, 8);
16504 data << uint64(0);
16505 data << uint32(0);
16506 GetSession()->SendPacket(&data);
16508 if(GetGroup())
16509 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16513 void Player::RemoveMiniPet()
16515 if(Pet* pet = GetMiniPet())
16517 pet->Remove(PET_SAVE_AS_DELETED);
16518 m_miniPet = 0;
16522 Pet* Player::GetMiniPet()
16524 if(!m_miniPet)
16525 return NULL;
16526 return ObjectAccessor::GetPet(m_miniPet);
16529 void Player::RemoveGuardians()
16531 while(!m_guardianPets.empty())
16533 uint64 guid = *m_guardianPets.begin();
16534 if(Pet* pet = ObjectAccessor::GetPet(guid))
16535 pet->Remove(PET_SAVE_AS_DELETED);
16537 m_guardianPets.erase(guid);
16541 bool Player::HasGuardianWithEntry(uint32 entry)
16543 // pet guid middle part is entry (and creature also)
16544 // and in guardian list must be guardians with same entry _always_
16545 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16546 if(GUID_ENPART(*itr)==entry)
16547 return true;
16549 return false;
16552 void Player::Uncharm()
16554 Unit* charm = GetCharm();
16555 if(!charm)
16556 return;
16558 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16559 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16562 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16564 *data << (uint8)msgtype;
16565 *data << (uint32)language;
16566 *data << (uint64)GetGUID();
16567 *data << (uint32)language; //language 2.1.0 ?
16568 *data << (uint64)GetGUID();
16569 *data << (uint32)(text.length()+1);
16570 *data << text;
16571 *data << (uint8)chatTag();
16574 void Player::Say(const std::string& text, const uint32 language)
16576 WorldPacket data(SMSG_MESSAGECHAT, 200);
16577 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16578 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16581 void Player::Yell(const std::string& text, const uint32 language)
16583 WorldPacket data(SMSG_MESSAGECHAT, 200);
16584 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16585 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16588 void Player::TextEmote(const std::string& text)
16590 WorldPacket data(SMSG_MESSAGECHAT, 200);
16591 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16592 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16595 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16597 if (language != LANG_ADDON) // if not addon data
16598 language = LANG_UNIVERSAL; // whispers should always be readable
16600 Player *rPlayer = objmgr.GetPlayer(receiver);
16602 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16603 if(!rPlayer->isDND() || isGameMaster())
16605 WorldPacket data(SMSG_MESSAGECHAT, 200);
16606 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16607 rPlayer->GetSession()->SendPacket(&data);
16609 data.Initialize(SMSG_MESSAGECHAT, 200);
16610 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16611 GetSession()->SendPacket(&data);
16613 else
16615 // announce to player that player he is whispering to is dnd and cannot receive his message
16616 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16619 if(!isAcceptWhispers())
16621 SetAcceptWhispers(true);
16622 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16625 // announce to player that player he is whispering to is afk
16626 if(rPlayer->isAFK())
16627 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16629 // if player whisper someone, auto turn of dnd to be able to receive an answer
16630 if(isDND() && !rPlayer->isGameMaster())
16631 ToggleDND();
16634 void Player::PetSpellInitialize()
16636 Pet* pet = GetPet();
16638 if(!pet)
16639 return;
16641 sLog.outDebug("Pet Spells Groups");
16643 CharmInfo *charmInfo = pet->GetCharmInfo();
16645 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16646 data << uint64(pet->GetGUID());
16647 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16648 data << uint32(0);
16649 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16651 // action bar loop
16652 for(uint32 i = 0; i < 10; i++)
16654 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16657 size_t spellsCountPos = data.wpos();
16659 // spells count
16660 uint8 addlist = 0;
16661 data << uint8(addlist); // placeholder
16663 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16665 // spells loop
16666 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16668 if(itr->second->state == PETSPELL_REMOVED)
16669 continue;
16671 data << uint16(itr->first);
16672 data << uint16(itr->second->active); // pet spell active state isn't boolean
16673 ++addlist;
16677 data.put<uint8>(spellsCountPos, addlist);
16679 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16680 data << uint8(cooldownsCount);
16682 time_t curTime = time(NULL);
16684 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16686 time_t cooldown = 0;
16688 if(itr->second > curTime)
16689 cooldown = (itr->second - curTime) * 1000;
16691 data << uint16(itr->first); // spellid
16692 data << uint16(0); // spell category?
16693 data << uint32(itr->second); // cooldown
16694 data << uint32(0); // category cooldown
16697 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16699 time_t cooldown = 0;
16701 if(itr->second > curTime)
16702 cooldown = (itr->second - curTime) * 1000;
16704 data << uint16(itr->first); // spellid
16705 data << uint16(0); // spell category?
16706 data << uint32(0); // cooldown
16707 data << uint32(itr->second); // category cooldown
16710 GetSession()->SendPacket(&data);
16713 void Player::PossessSpellInitialize()
16715 Unit* charm = GetCharm();
16717 if(!charm)
16718 return;
16720 CharmInfo *charmInfo = charm->GetCharmInfo();
16722 if(!charmInfo)
16724 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16725 return;
16728 uint8 addlist = 0;
16729 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16731 //16
16732 data << uint64(charm->GetGUID());
16733 data << uint32(0x00000000);
16734 data << uint32(0);
16735 data << uint8(0) << uint8(0) << uint16(0);
16737 for(uint32 i = 0; i < 10; i++) //40
16739 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16742 data << uint8(addlist); //1
16744 uint8 count = 0;
16745 data << uint8(count); // cooldowns count
16747 GetSession()->SendPacket(&data);
16750 void Player::CharmSpellInitialize()
16752 Unit* charm = GetCharm();
16754 if(!charm)
16755 return;
16757 CharmInfo *charmInfo = charm->GetCharmInfo();
16758 if(!charmInfo)
16760 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16761 return;
16764 uint8 addlist = 0;
16766 if(charm->GetTypeId() != TYPEID_PLAYER)
16768 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16770 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16772 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16774 if(charmInfo->GetCharmSpell(i)->spellId)
16775 ++addlist;
16780 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16782 data << uint64(charm->GetGUID());
16783 data << uint32(0x00000000);
16784 data << uint32(0);
16785 if(charm->GetTypeId() != TYPEID_PLAYER)
16786 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16787 else
16788 data << uint8(0) << uint8(0);
16789 data << uint16(0);
16791 for(uint32 i = 0; i < 10; i++) //40
16793 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16796 data << uint8(addlist); //1
16798 if(addlist)
16800 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16802 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16803 if(cspell->spellId)
16805 data << uint16(cspell->spellId);
16806 data << uint16(cspell->active);
16811 uint8 count = 0;
16812 data << uint8(count); // cooldowns count
16814 GetSession()->SendPacket(&data);
16817 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16819 if (!mod || !spellInfo)
16820 return false;
16822 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16824 // prevent apply to any spell except spell that trigger expire
16825 if(spell)
16827 if(mod->lastAffected != spell)
16828 return false;
16830 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16831 return false;
16834 return spellmgr.IsAffectedByMod(spellInfo, mod);
16837 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16839 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16841 for(int eff=0;eff<96;++eff)
16843 uint64 _mask = 0;
16844 uint64 _mask2= 0;
16845 if (eff<64) _mask = uint64(1) << (eff- 0);
16846 else _mask2= uint64(1) << (eff-64);
16847 if ( mod->mask & _mask || mod->mask2 & _mask2)
16849 int32 val = 0;
16850 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16852 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16853 val += (*itr)->value;
16855 val += apply ? mod->value : -(mod->value);
16856 WorldPacket data(Opcode, (1+1+4));
16857 data << uint8(eff);
16858 data << uint8(mod->op);
16859 data << int32(val);
16860 SendDirectMessage(&data);
16864 if (apply)
16865 m_spellMods[mod->op].push_back(mod);
16866 else
16868 if (mod->charges == -1)
16869 --m_SpellModRemoveCount;
16870 m_spellMods[mod->op].remove(mod);
16871 delete mod;
16875 void Player::RemoveSpellMods(Spell const* spell)
16877 if(!spell || (m_SpellModRemoveCount == 0))
16878 return;
16880 for(int i=0;i<MAX_SPELLMOD;++i)
16882 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16884 SpellModifier *mod = *itr;
16885 ++itr;
16887 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16889 RemoveAurasDueToSpell(mod->spellId);
16890 if (m_spellMods[i].empty())
16891 break;
16892 else
16893 itr = m_spellMods[i].begin();
16899 // send Proficiency
16900 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16902 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16903 data << pr1 << pr2;
16904 GetSession()->SendPacket (&data);
16907 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16909 QueryResult *result = NULL;
16910 if(type==10)
16911 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16912 else
16913 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16914 if(result)
16916 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.
16917 { // and SendPetitionQueryOpcode reads data from the DB
16918 Field *fields = result->Fetch();
16919 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16920 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16922 // send update if charter owner in game
16923 Player* owner = objmgr.GetPlayer(ownerguid);
16924 if(owner)
16925 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16927 } while ( result->NextRow() );
16929 delete result;
16931 if(type==10)
16932 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16933 else
16934 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16937 CharacterDatabase.BeginTransaction();
16938 if(type == 10)
16940 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16941 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16943 else
16945 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16946 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16948 CharacterDatabase.CommitTransaction();
16951 void Player::LeaveAllArenaTeams(uint64 guid)
16953 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));
16954 if(!result)
16955 return;
16959 Field *fields = result->Fetch();
16960 uint32 at_id = fields[0].GetUInt32();
16961 if(at_id != 0)
16963 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16964 if(at)
16965 at->DelMember(guid);
16967 } while (result->NextRow());
16969 delete result;
16972 void Player::SetRestBonus (float rest_bonus_new)
16974 // Prevent resting on max level
16975 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16976 rest_bonus_new = 0;
16978 if(rest_bonus_new < 0)
16979 rest_bonus_new = 0;
16981 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16983 if(rest_bonus_new > rest_bonus_max)
16984 m_rest_bonus = rest_bonus_max;
16985 else
16986 m_rest_bonus = rest_bonus_new;
16988 // update data for client
16989 if(m_rest_bonus>10)
16990 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16991 else if(m_rest_bonus<=1)
16992 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16994 //RestTickUpdate
16995 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16998 void Player::HandleStealthedUnitsDetection()
17000 std::list<Unit*> stealthedUnits;
17002 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17003 Cell cell(p);
17004 cell.data.Part.reserved = ALL_DISTRICT;
17005 cell.SetNoCreate();
17007 MaNGOS::AnyStealthedCheck u_check;
17008 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17010 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17011 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17013 CellLock<GridReadGuard> cell_lock(cell, p);
17014 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
17015 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
17017 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
17019 if((*i)==this)
17021 i = stealthedUnits.erase(i);
17022 continue;
17025 if ((*i)->isVisibleForOrDetect(this,true))
17028 (*i)->SendUpdateToPlayer(this);
17029 m_clientGUIDs.insert((*i)->GetGUID());
17031 #ifdef MANGOS_DEBUG
17032 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17033 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17034 #endif
17036 // target aura duration for caster show only if target exist at caster client
17037 // send data at target visibility change (adding to client)
17038 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17039 SendAurasForTarget(*i);
17041 i = stealthedUnits.erase(i);
17042 continue;
17045 ++i;
17049 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
17051 if(nodes.size() < 2)
17052 return false;
17054 // not let cheating with start flight mounted
17055 if(IsMounted())
17057 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17058 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17059 GetSession()->SendPacket(&data);
17060 return false;
17063 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17065 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17066 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17067 GetSession()->SendPacket(&data);
17068 return false;
17071 // 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
17072 if(GetSession()->isLogingOut() ||
17073 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
17074 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
17075 IsNonMeleeSpellCasted(false) ||
17076 isInCombat())
17078 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17079 data << uint32(ERR_TAXIPLAYERBUSY);
17080 GetSession()->SendPacket(&data);
17081 return false;
17084 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17085 return false;
17087 uint32 sourcenode = nodes[0];
17089 // starting node too far away (cheat?)
17090 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17091 if( !node || node->map_id != GetMapId() ||
17092 (node->x - GetPositionX())*(node->x - GetPositionX())+
17093 (node->y - GetPositionY())*(node->y - GetPositionY())+
17094 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17095 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
17097 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17098 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17099 GetSession()->SendPacket(&data);
17100 return false;
17103 // Prepare to flight start now
17105 // stop combat at start taxi flight if any
17106 CombatStop();
17108 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17109 TradeCancel(true);
17111 // clean not finished taxi path if any
17112 m_taxi.ClearTaxiDestinations();
17114 // 0 element current node
17115 m_taxi.AddTaxiDestination(sourcenode);
17117 // fill destinations path tail
17118 uint32 sourcepath = 0;
17119 uint32 totalcost = 0;
17121 uint32 prevnode = sourcenode;
17122 uint32 lastnode = 0;
17124 for(uint32 i = 1; i < nodes.size(); ++i)
17126 uint32 path, cost;
17128 lastnode = nodes[i];
17129 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17131 if(!path)
17133 m_taxi.ClearTaxiDestinations();
17134 return false;
17137 totalcost += cost;
17139 if(prevnode == sourcenode)
17140 sourcepath = path;
17142 m_taxi.AddTaxiDestination(lastnode);
17144 prevnode = lastnode;
17147 if(!mount_id) // if not provide then attempt use default.
17148 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
17150 if (mount_id == 0 || sourcepath == 0)
17152 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17153 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17154 GetSession()->SendPacket(&data);
17155 m_taxi.ClearTaxiDestinations();
17156 return false;
17159 uint32 money = GetMoney();
17161 if(npc)
17163 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17166 if(money < totalcost)
17168 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17169 data << uint32(ERR_TAXINOTENOUGHMONEY);
17170 GetSession()->SendPacket(&data);
17171 m_taxi.ClearTaxiDestinations();
17172 return false;
17175 //Checks and preparations done, DO FLIGHT
17176 ModifyMoney(-(int32)totalcost);
17178 // prevent stealth flight
17179 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17181 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17182 data << uint32(ERR_TAXIOK);
17183 GetSession()->SendPacket(&data);
17185 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17187 GetSession()->SendDoFlight(mount_id, sourcepath);
17189 return true;
17192 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17194 // last check 2.0.10
17195 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17196 data << GetGUID();
17197 data << uint8(0x0); // flags (0x1, 0x2)
17198 time_t curTime = time(NULL);
17199 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17201 if (itr->second->state == PLAYERSPELL_REMOVED)
17202 continue;
17203 uint32 unSpellId = itr->first;
17204 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17205 if (!spellInfo)
17207 ASSERT(spellInfo);
17208 continue;
17211 // Not send cooldown for this spells
17212 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17213 continue;
17215 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17217 data << unSpellId;
17218 data << unTimeMs; // in m.secs
17219 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
17222 GetSession()->SendPacket(&data);
17225 void Player::InitDataForForm(bool reapplyMods)
17227 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17228 if(ssEntry && ssEntry->attackSpeed)
17230 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17231 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17232 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17234 else
17235 SetRegularAttackTime();
17237 switch(m_form)
17239 case FORM_CAT:
17241 if(getPowerType()!=POWER_ENERGY)
17242 setPowerType(POWER_ENERGY);
17243 break;
17245 case FORM_BEAR:
17246 case FORM_DIREBEAR:
17248 if(getPowerType()!=POWER_RAGE)
17249 setPowerType(POWER_RAGE);
17250 break;
17252 default: // 0, for example
17254 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17255 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17256 setPowerType(Powers(cEntry->powerType));
17257 break;
17261 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17262 if (!reapplyMods)
17263 UpdateEquipSpellsAtFormChange();
17265 UpdateAttackPowerAndDamage();
17266 UpdateAttackPowerAndDamage(true);
17269 // Return true is the bought item has a max count to force refresh of window by caller
17270 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17272 // cheating attempt
17273 if(count < 1) count = 1;
17275 if(!isAlive())
17276 return false;
17278 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17279 if( !pProto )
17281 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17282 return false;
17285 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
17286 if (!pCreature)
17288 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17289 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17290 return false;
17293 VendorItemData const* vItems = pCreature->GetVendorItems();
17294 if(!vItems || vItems->Empty())
17296 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17297 return false;
17300 size_t vendor_slot = vItems->FindItemSlot(item);
17301 if(vendor_slot >= vItems->GetItemCount())
17303 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17304 return false;
17307 VendorItem const* crItem = vItems->m_items[vendor_slot];
17309 // check current item amount if it limited
17310 if( crItem->maxcount != 0 )
17312 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17314 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17315 return false;
17319 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17321 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17322 return false;
17325 if(crItem->ExtendedCost)
17327 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17328 if(!iece)
17330 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17331 return false;
17334 // honor points price
17335 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17337 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17338 return false;
17341 // arena points price
17342 if(GetArenaPoints() < (iece->reqarenapoints * count))
17344 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17345 return false;
17348 // item base price
17349 for (uint8 i = 0; i < 5; ++i)
17351 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17353 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17354 return false;
17358 // check for personal arena rating requirement
17359 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17361 // probably not the proper equip err
17362 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17363 return false;
17367 uint32 price = pProto->BuyPrice * count;
17369 // reputation discount
17370 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17372 if( GetMoney() < price )
17374 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17375 return false;
17378 uint8 bag = 0; // init for case invalid bagGUID
17380 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17382 Bag *pBag;
17383 if( bagguid == GetGUID() )
17385 bag = INVENTORY_SLOT_BAG_0;
17387 else
17389 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17391 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17392 if( pBag )
17394 if( bagguid == pBag->GetGUID() )
17396 bag = i;
17397 break;
17404 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17406 ItemPosCountVec dest;
17407 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17408 if( msg != EQUIP_ERR_OK )
17410 SendEquipError( msg, NULL, NULL );
17411 return false;
17414 ModifyMoney( -(int32)price );
17415 if(crItem->ExtendedCost) // case for new honor system
17417 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17418 if(iece->reqhonorpoints)
17419 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17420 if(iece->reqarenapoints)
17421 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17422 for (uint8 i = 0; i < 5; ++i)
17424 if(iece->reqitem[i])
17425 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17429 if(Item *it = StoreNewItem( dest, item, true ))
17431 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17433 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17434 data << pCreature->GetGUID();
17435 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17436 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17437 data << (uint32)count;
17438 GetSession()->SendPacket(&data);
17440 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17443 else if( IsEquipmentPos( bag, slot ) )
17445 if(pProto->BuyCount * count != 1)
17447 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17448 return false;
17451 uint16 dest;
17452 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17453 if( msg != EQUIP_ERR_OK )
17455 SendEquipError( msg, NULL, NULL );
17456 return false;
17459 ModifyMoney( -(int32)price );
17460 if(crItem->ExtendedCost) // case for new honor system
17462 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17463 if(iece->reqhonorpoints)
17464 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17465 if(iece->reqarenapoints)
17466 ModifyArenaPoints( - int32(iece->reqarenapoints));
17467 for (uint8 i = 0; i < 5; ++i)
17469 if(iece->reqitem[i])
17470 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17474 if(Item *it = EquipNewItem( dest, item, true ))
17476 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17478 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17479 data << pCreature->GetGUID();
17480 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17481 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17482 data << (uint32)count;
17483 GetSession()->SendPacket(&data);
17485 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17487 AutoUnequipOffhandIfNeed();
17490 else
17492 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17493 return false;
17496 return crItem->maxcount!=0;
17499 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17501 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17502 // the personal rating of the arena team must match the required limit as well
17503 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17504 uint32 max_personal_rating = 0;
17505 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17507 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17509 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17510 uint32 t_rating = at->GetRating();
17511 p_rating = p_rating<t_rating? p_rating : t_rating;
17512 if(max_personal_rating < p_rating)
17513 max_personal_rating = p_rating;
17516 return max_personal_rating;
17519 void Player::UpdateHomebindTime(uint32 time)
17521 // GMs never get homebind timer online
17522 if (m_InstanceValid || isGameMaster())
17524 if(m_HomebindTimer) // instance valid, but timer not reset
17526 // hide reminder
17527 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17528 data << uint32(0);
17529 data << uint32(0);
17530 GetSession()->SendPacket(&data);
17532 // instance is valid, reset homebind timer
17533 m_HomebindTimer = 0;
17535 else if (m_HomebindTimer > 0)
17537 if (time >= m_HomebindTimer)
17539 // teleport to homebind location
17540 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17542 else
17543 m_HomebindTimer -= time;
17545 else
17547 // instance is invalid, start homebind timer
17548 m_HomebindTimer = 60000;
17549 // send message to player
17550 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17551 data << m_HomebindTimer;
17552 data << uint32(1);
17553 GetSession()->SendPacket(&data);
17554 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17558 void Player::UpdatePvP(bool state, bool ovrride)
17560 if(!state || ovrride)
17562 SetPvP(state);
17563 if(Pet* pet = GetPet())
17564 pet->SetPvP(state);
17565 if(Unit* charmed = GetCharm())
17566 charmed->SetPvP(state);
17568 pvpInfo.endTimer = 0;
17570 else
17572 if(pvpInfo.endTimer != 0)
17573 pvpInfo.endTimer = time(NULL);
17574 else
17576 SetPvP(state);
17578 if(Pet* pet = GetPet())
17579 pet->SetPvP(state);
17580 if(Unit* charmed = GetCharm())
17581 charmed->SetPvP(state);
17586 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17588 SpellCooldown sc;
17589 sc.end = end_time;
17590 sc.itemid = itemid;
17591 m_spellCooldowns[spellid] = sc;
17594 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17596 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17597 return;
17599 // Get spell cooldown
17600 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17601 // Apply spellmods
17602 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17603 if (cooldown < 0)
17604 cooldown = 0;
17605 // Add cooldown
17606 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17607 // Send activate
17608 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17609 data << spellInfo->Id;
17610 data << GetGUID();
17611 SendDirectMessage(&data);
17613 //slot to be excluded while counting
17614 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17616 if(!enchantmentcondition)
17617 return true;
17619 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17621 if(!Condition)
17622 return true;
17624 uint8 curcount[4] = {0, 0, 0, 0};
17626 //counting current equipped gem colors
17627 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17629 if(i == slot)
17630 continue;
17631 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17632 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17634 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17636 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17637 if(!enchant_id)
17638 continue;
17640 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17641 if(!enchantEntry)
17642 continue;
17644 uint32 gemid = enchantEntry->GemID;
17645 if(!gemid)
17646 continue;
17648 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17649 if(!gemProto)
17650 continue;
17652 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17653 if(!gemProperty)
17654 continue;
17656 uint8 GemColor = gemProperty->color;
17658 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17660 if(tmpcolormask & GemColor)
17661 ++curcount[b];
17667 bool activate = true;
17669 for(int i = 0; i < 5; i++)
17671 if(!Condition->Color[i])
17672 continue;
17674 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17676 // if have <CompareColor> use them as count, else use <value> from Condition
17677 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17679 switch(Condition->Comparator[i])
17681 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17682 activate &= (_cur_gem < _cmp_gem) ? true : false;
17683 break;
17684 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17685 activate &= (_cur_gem > _cmp_gem) ? true : false;
17686 break;
17687 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17688 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17689 break;
17693 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");
17695 return activate;
17698 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17700 //cycle all equipped items
17701 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17703 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17704 if(slot == exceptslot)
17705 continue;
17707 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17709 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17710 continue;
17712 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17714 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17715 if(!enchant_id)
17716 continue;
17718 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17719 if(!enchantEntry)
17720 continue;
17722 uint32 condition = enchantEntry->EnchantmentCondition;
17723 if(condition)
17725 //was enchant active with/without item?
17726 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17727 //should it now be?
17728 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17730 // ignore item gem conditions
17731 //if state changed, (dis)apply enchant
17732 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17739 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17740 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17742 //cycle all equipped items
17743 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17745 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17746 if(slot == exceptslot)
17747 continue;
17749 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17751 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17752 continue;
17754 //cycle all (gem)enchants
17755 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17757 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17758 if(!enchant_id) //if no enchant go to next enchant(slot)
17759 continue;
17761 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17762 if(!enchantEntry)
17763 continue;
17765 //only metagems to be (de)activated, so only enchants with condition
17766 uint32 condition = enchantEntry->EnchantmentCondition;
17767 if(condition)
17768 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17773 void Player::LeaveBattleground(bool teleportToEntryPoint)
17775 if(BattleGround *bg = GetBattleGround())
17777 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17779 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17781 // call after remove to be sure that player resurrected for correct cast
17782 if(need_debuf)
17783 CastSpell(this, 26013, true); // Deserter
17787 bool Player::CanJoinToBattleground() const
17789 // check Deserter debuff
17790 if(GetDummyAura(26013))
17791 return false;
17793 return true;
17796 bool Player::CanReportAfkDueToLimit()
17798 // a player can complain about 15 people per 5 minutes
17799 if(m_bgAfkReportedCount >= 15)
17800 return false;
17801 ++m_bgAfkReportedCount;
17802 return true;
17805 ///This player has been blamed to be inactive in a battleground
17806 void Player::ReportedAfkBy(Player* reporter)
17808 BattleGround *bg = GetBattleGround();
17809 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17810 return;
17812 // check if player has 'Idle' or 'Inactive' debuff
17813 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17815 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17816 // 3 players have to complain to apply debuff
17817 if(m_bgAfkReporter.size() >= 3)
17819 // cast 'Idle' spell
17820 CastSpell(this, 43680, true);
17821 m_bgAfkReporter.clear();
17826 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17828 // gamemaster in GM mode see all, including ghosts
17829 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17830 return true;
17832 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17833 if (InBattleGround())
17835 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17836 return false;
17837 return true;
17840 // Live player see live player or dead player with not realized corpse
17841 if(pl->isAlive() || pl->m_deathTimer > 0)
17843 return isAlive() || m_deathTimer > 0;
17846 // Ghost see other friendly ghosts, that's for sure
17847 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17848 return true;
17850 // Dead player see live players near own corpse
17851 if(isAlive())
17853 Corpse *corpse = pl->GetCorpse();
17854 if(corpse)
17856 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17857 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17858 return true;
17862 // and not see any other
17863 return false;
17866 bool Player::IsVisibleGloballyFor( Player* u ) const
17868 if(!u)
17869 return false;
17871 // Always can see self
17872 if (u==this)
17873 return true;
17875 // Visible units, always are visible for all players
17876 if (GetVisibility() == VISIBILITY_ON)
17877 return true;
17879 // GMs are visible for higher gms (or players are visible for gms)
17880 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17881 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17883 // non faction visibility non-breakable for non-GMs
17884 if (GetVisibility() == VISIBILITY_OFF)
17885 return false;
17887 // non-gm stealth/invisibility not hide from global player lists
17888 return true;
17891 void Player::UpdateVisibilityOf(WorldObject* target)
17893 if(HaveAtClient(target))
17895 if(!target->isVisibleForInState(this,true))
17897 target->DestroyForPlayer(this);
17898 m_clientGUIDs.erase(target->GetGUID());
17900 #ifdef MANGOS_DEBUG
17901 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17902 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17903 #endif
17906 else
17908 if(target->isVisibleForInState(this,false))
17910 target->SendUpdateToPlayer(this);
17911 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17912 m_clientGUIDs.insert(target->GetGUID());
17914 #ifdef MANGOS_DEBUG
17915 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17916 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
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(target!=this && target->isType(TYPEMASK_UNIT))
17922 SendAurasForTarget((Unit*)target);
17924 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17925 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17930 template<class T>
17931 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17933 s64.insert(target->GetGUID());
17936 template<>
17937 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17939 if(!target->IsTransport())
17940 s64.insert(target->GetGUID());
17943 template<class T>
17944 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17946 if(HaveAtClient(target))
17948 if(!target->isVisibleForInState(this,true))
17950 target->BuildOutOfRangeUpdateBlock(&data);
17951 m_clientGUIDs.erase(target->GetGUID());
17953 #ifdef MANGOS_DEBUG
17954 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17955 sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
17956 #endif
17959 else
17961 if(target->isVisibleForInState(this,false))
17963 visibleNow.insert(target);
17964 target->BuildUpdate(data_updates);
17965 target->BuildCreateUpdateBlockForPlayer(&data, this);
17966 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17968 #ifdef MANGOS_DEBUG
17969 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17970 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));
17971 #endif
17976 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17977 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17978 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17979 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17980 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17982 void Player::InitPrimaryProffesions()
17984 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17987 void Player::SendComboPoints()
17989 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17990 if (combotarget)
17992 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17993 data.append(combotarget->GetPackGUID());
17994 data << uint8(m_comboPoints);
17995 GetSession()->SendPacket(&data);
17999 void Player::AddComboPoints(Unit* target, int8 count)
18001 if(!count)
18002 return;
18004 // without combo points lost (duration checked in aura)
18005 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18007 if(target->GetGUID() == m_comboTarget)
18009 m_comboPoints += count;
18011 else
18013 if(m_comboTarget)
18014 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18015 target->RemoveComboPointHolder(GetGUIDLow());
18017 m_comboTarget = target->GetGUID();
18018 m_comboPoints = count;
18020 target->AddComboPointHolder(GetGUIDLow());
18023 if (m_comboPoints > 5) m_comboPoints = 5;
18024 if (m_comboPoints < 0) m_comboPoints = 0;
18026 SendComboPoints();
18029 void Player::ClearComboPoints()
18031 if(!m_comboTarget)
18032 return;
18034 // without combopoints lost (duration checked in aura)
18035 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18037 m_comboPoints = 0;
18039 SendComboPoints();
18041 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18042 target->RemoveComboPointHolder(GetGUIDLow());
18044 m_comboTarget = 0;
18047 void Player::SetGroup(Group *group, int8 subgroup)
18049 if(group == NULL) m_group.unlink();
18050 else
18052 // never use SetGroup without a subgroup unless you specify NULL for group
18053 assert(subgroup >= 0);
18054 m_group.link(group, this);
18055 m_group.setSubGroup((uint8)subgroup);
18059 void Player::SendInitialPacketsBeforeAddToMap()
18061 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18062 data << uint32(0); // unknown, may be rest state time or experience
18063 GetSession()->SendPacket(&data);
18065 // Homebind
18066 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18067 data << m_homebindX << m_homebindY << m_homebindZ;
18068 data << (uint32) m_homebindMapId;
18069 data << (uint32) m_homebindZoneId;
18070 GetSession()->SendPacket(&data);
18072 // SMSG_SET_PROFICIENCY
18073 // SMSG_UPDATE_AURA_DURATION
18075 // tutorial stuff
18076 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
18077 for (int i = 0; i < 8; ++i)
18078 data << uint32( GetTutorialInt(i) );
18079 GetSession()->SendPacket(&data);
18081 SendInitialSpells();
18083 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18084 data << uint32(0); // count, for(count) uint32;
18085 GetSession()->SendPacket(&data);
18087 SendInitialActionButtons();
18088 SendInitialReputations();
18089 m_achievementMgr.SendAllAchievementData();
18090 UpdateZone(GetZoneId());
18091 SendInitWorldStates();
18093 // SMSG_SET_AURA_SINGLE
18095 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18096 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18097 data << (float)0.01666667f; // game speed
18098 GetSession()->SendPacket( &data );
18100 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18101 data << uint32(0x00000000); // on blizz it increments periodically
18102 GetSession()->SendPacket(&data);
18104 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18105 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18106 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18108 m_mover = this;
18111 void Player::SendInitialPacketsAfterAddToMap()
18113 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18114 data << uint32(0x00000000); // on blizz it increments periodically
18115 GetSession()->SendPacket(&data);
18117 CastSpell(this, 836, true); // LOGINEFFECT
18119 // set some aura effects that send packet to player client after add player to map
18120 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18121 // same auras state lost at far teleport, send it one more time in this case also
18122 static const AuraType auratypes[] =
18124 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18125 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18126 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18128 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18130 Unit::AuraList const& auraList = GetAurasByType(*itr);
18131 if(!auraList.empty())
18132 auraList.front()->ApplyModifier(true,true);
18135 if(HasAuraType(SPELL_AURA_MOD_STUN))
18136 SetMovement(MOVE_ROOT);
18138 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18139 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18141 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
18142 data.append(GetPackGUID());
18143 data << (uint32)2;
18144 SendMessageToSet(&data,true);
18147 SendAurasForTarget(this);
18148 SendEnchantmentDurations(); // must be after add to map
18149 SendItemDurations(); // must be after add to map
18152 void Player::SendUpdateToOutOfRangeGroupMembers()
18154 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18155 return;
18156 if(Group* group = GetGroup())
18157 group->UpdatePlayerOutOfRange(this);
18159 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18160 m_auraUpdateMask = 0;
18161 if(Pet *pet = GetPet())
18162 pet->ResetAuraUpdateMask();
18165 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18167 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18168 data << uint32(mapid);
18169 data << uint8(reason); // transfer abort reason
18170 switch(reason)
18172 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18173 case TRANSFER_ABORT_DIFFICULTY:
18174 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18175 data << uint8(arg);
18176 break;
18178 GetSession()->SendPacket(&data);
18181 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18183 // type of warning, based on the time remaining until reset
18184 uint32 type;
18185 if(time > 3600)
18186 type = RAID_INSTANCE_WELCOME;
18187 else if(time > 900 && time <= 3600)
18188 type = RAID_INSTANCE_WARNING_HOURS;
18189 else if(time > 300 && time <= 900)
18190 type = RAID_INSTANCE_WARNING_MIN;
18191 else
18192 type = RAID_INSTANCE_WARNING_MIN_SOON;
18193 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18194 data << uint32(type);
18195 data << uint32(mapid);
18196 data << uint32(time);
18197 GetSession()->SendPacket(&data);
18200 void Player::ApplyEquipCooldown( Item * pItem )
18202 for(int i = 0; i <5; ++i)
18204 _Spell const& spellData = pItem->GetProto()->Spells[i];
18206 // no spell
18207 if( !spellData.SpellId )
18208 continue;
18210 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18211 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18212 continue;
18214 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18216 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18217 data << pItem->GetGUID();
18218 data << uint32(spellData.SpellId);
18219 GetSession()->SendPacket(&data);
18223 void Player::resetSpells()
18225 // not need after this call
18226 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18228 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18229 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18232 // make full copy of map (spells removed and marked as deleted at another spell remove
18233 // and we can't use original map for safe iterative with visit each spell at loop end
18234 PlayerSpellMap smap = GetSpellMap();
18236 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18237 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18239 learnDefaultSpells();
18240 learnQuestRewardedSpells();
18243 void Player::learnDefaultSpells()
18245 // learn default race/class spells
18246 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18247 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18249 uint32 tspell = *itr;
18250 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18251 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18252 addSpell(tspell,true,true,true,false);
18253 else // but send in normal spell in game learn case
18254 learnSpell(tspell,true);
18258 void Player::learnQuestRewardedSpells(Quest const* quest)
18260 uint32 spell_id = quest->GetRewSpellCast();
18262 // skip quests without rewarded spell
18263 if( !spell_id )
18264 return;
18266 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18267 if(!spellInfo)
18268 return;
18270 // check learned spells state
18271 bool found = false;
18272 for(int i=0; i < 3; ++i)
18274 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18276 found = true;
18277 break;
18281 // skip quests with not teaching spell or already known spell
18282 if(!found)
18283 return;
18285 // prevent learn non first rank unknown profession and second specialization for same profession)
18286 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18287 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18289 // not have first rank learned (unlearned prof?)
18290 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18291 if( !HasSpell(first_spell) )
18292 return;
18294 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18295 if(!learnedInfo)
18296 return;
18298 // specialization
18299 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18301 // search other specialization for same prof
18302 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18304 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18305 continue;
18307 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18308 if(!itrInfo)
18309 return;
18311 // compare only specializations
18312 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18313 continue;
18315 // compare same chain spells
18316 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18317 continue;
18319 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18320 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18321 return;
18326 CastSpell( this, spell_id, true);
18329 void Player::learnQuestRewardedSpells()
18331 // learn spells received from quest completing
18332 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18334 // skip no rewarded quests
18335 if(!itr->second.m_rewarded)
18336 continue;
18338 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18339 if( !quest )
18340 continue;
18342 learnQuestRewardedSpells(quest);
18346 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18348 uint32 raceMask = getRaceMask();
18349 uint32 classMask = getClassMask();
18350 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18352 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18353 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18354 continue;
18355 // Check race if set
18356 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18357 continue;
18358 // Check class if set
18359 if (pAbility->classmask && !(pAbility->classmask & classMask))
18360 continue;
18362 if (sSpellStore.LookupEntry(pAbility->spellId))
18364 // need unlearn spell
18365 if (skill_value < pAbility->req_skill_value)
18366 removeSpell(pAbility->spellId);
18367 // need learn
18368 else if (!IsInWorld())
18369 addSpell(pAbility->spellId,true,true,true,false);
18370 else
18371 learnSpell(pAbility->spellId,true);
18376 void Player::SendAurasForTarget(Unit *target)
18378 if(target->GetVisibleAuras()->empty()) // speedup things
18379 return;
18381 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18382 data.append(target->GetPackGUID());
18384 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18385 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18387 for(uint32 j = 0; j < 3; ++j)
18389 if(Aura *aura = target->GetAura(itr->second, j))
18391 data << uint8(aura->GetAuraSlot());
18392 data << uint32(aura->GetId());
18394 if(aura->GetId())
18396 uint8 auraFlags = aura->GetAuraFlags();
18397 // flags
18398 data << uint8(auraFlags);
18399 // level
18400 data << uint8(aura->GetAuraLevel());
18401 // charges
18402 data << uint8(aura->GetAuraCharges());
18404 if(!(auraFlags & AFLAG_NOT_CASTER))
18406 data << uint8(0); // packed GUID of someone (caster?)
18409 if(auraFlags & AFLAG_DURATION) // include aura duration
18411 data << uint32(aura->GetAuraMaxDuration());
18412 data << uint32(aura->GetAuraDuration());
18415 break;
18420 GetSession()->SendPacket(&data);
18423 void Player::SetDailyQuestStatus( uint32 quest_id )
18425 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18427 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18429 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18430 m_lastDailyQuestTime = time(NULL); // last daily quest time
18431 m_DailyQuestChanged = true;
18432 break;
18437 void Player::ResetDailyQuestStatus()
18439 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18440 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18442 // DB data deleted in caller
18443 m_DailyQuestChanged = false;
18444 m_lastDailyQuestTime = 0;
18447 BattleGround* Player::GetBattleGround() const
18449 if(GetBattleGroundId()==0)
18450 return NULL;
18452 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18455 bool Player::InArena() const
18457 BattleGround *bg = GetBattleGround();
18458 if(!bg || !bg->isArena())
18459 return false;
18461 return true;
18464 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18466 // get a template bg instead of running one
18467 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18468 if(!bg)
18469 return false;
18471 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18472 return false;
18474 return true;
18477 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id, BattleGroundTypeId bgTypeId)
18479 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18480 assert(bg);
18481 return (queue_id*10)+bg->GetMinLevel();
18484 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id, BattleGroundTypeId bgTypeId)
18486 return GetMinLevelForBattleGroundQueueId(queue_id, bgTypeId)+10;
18489 uint32 Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18491 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18492 assert(bg);
18493 if(getLevel()<bg->GetMinLevel())
18495 sLog.outError("getting queue_id for player who doesn't meet the requirements - this shouldn't happen");
18496 return 0;
18498 uint32 queue_id = (getLevel() - bg->GetMinLevel()) / 10;
18499 if(queue_id>MAX_BATTLEGROUND_QUEUES)
18501 sLog.outError("to high queue_id %u this shouldn't happen",queue_id);
18502 return 0;
18504 return queue_id;
18507 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18509 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18510 if(!vendor_faction)
18511 return 1.0f;
18513 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18514 if(rank <= REP_NEUTRAL)
18515 return 1.0f;
18517 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18520 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18522 uint32 racemask = getRaceMask();
18523 uint32 classmask = getClassMask();
18525 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18526 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18527 if(lower==upper)
18528 return true;
18530 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18532 // skip wrong race skills
18533 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18534 continue;
18536 // skip wrong class skills
18537 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18538 continue;
18540 return true;
18543 return false;
18546 bool Player::HasQuestForGO(int32 GOId) const
18548 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18550 uint32 questid = GetQuestSlotQuestId(i);
18551 if ( questid == 0 )
18552 continue;
18554 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18555 if(qs_itr == mQuestStatus.end())
18556 continue;
18558 QuestStatusData const& qs = qs_itr->second;
18560 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18562 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18563 if(!qinfo)
18564 continue;
18566 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18567 continue;
18569 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18571 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18572 continue;
18574 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18575 return true;
18579 return false;
18582 void Player::UpdateForQuestsGO()
18584 if(m_clientGUIDs.empty())
18585 return;
18587 UpdateData udata;
18588 WorldPacket packet;
18589 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18591 if(IS_GAMEOBJECT_GUID(*itr))
18593 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18594 if(obj)
18595 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18598 udata.BuildPacket(&packet);
18599 GetSession()->SendPacket(&packet);
18602 void Player::SummonIfPossible(bool agree)
18604 if(!agree)
18606 m_summon_expire = 0;
18607 return;
18610 // expire and auto declined
18611 if(m_summon_expire < time(NULL))
18612 return;
18614 // stop taxi flight at summon
18615 if(isInFlight())
18617 GetMotionMaster()->MovementExpired();
18618 m_taxi.ClearTaxiDestinations();
18621 // drop flag at summon
18622 if(BattleGround *bg = GetBattleGround())
18623 bg->EventPlayerDroppedFlag(this);
18625 m_summon_expire = 0;
18627 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18630 void Player::RemoveItemDurations( Item *item )
18632 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18634 if(*itr==item)
18636 m_itemDuration.erase(itr);
18637 break;
18642 void Player::AddItemDurations( Item *item )
18644 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18646 m_itemDuration.push_back(item);
18647 item->SendTimeUpdate(this);
18651 void Player::AutoUnequipOffhandIfNeed()
18653 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18654 if(!offItem)
18655 return;
18657 // need unequip for 2h-weapon without TitanGrip
18658 if (!IsTwoHandUsed())
18659 return;
18661 ItemPosCountVec off_dest;
18662 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18663 if( off_msg == EQUIP_ERR_OK )
18665 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18666 StoreItem( off_dest, offItem, true );
18668 else
18670 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18674 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18676 if(spellInfo->EquippedItemClass < 0)
18677 return true;
18679 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18680 // for optimize check 2 used cases only
18681 switch(spellInfo->EquippedItemClass)
18683 case ITEM_CLASS_WEAPON:
18685 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18686 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18687 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18688 return true;
18689 break;
18691 case ITEM_CLASS_ARMOR:
18693 // tabard not have dependent spells
18694 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18695 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18696 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18697 return true;
18699 // shields can be equipped to offhand slot
18700 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18701 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18702 return true;
18704 // ranged slot can have some armor subclasses
18705 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18706 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18707 return true;
18709 break;
18711 default:
18712 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18713 break;
18716 return false;
18719 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18721 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18722 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18723 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18724 return true;
18726 // Check no reagent use mask
18727 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18728 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18729 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18730 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18731 return true;
18733 return false;
18736 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18738 AuraMap& auras = GetAuras();
18739 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18741 Aura* aura = itr->second;
18743 // skip passive (passive item dependent spells work in another way) and not self applied auras
18744 SpellEntry const* spellInfo = aura->GetSpellProto();
18745 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18747 ++itr;
18748 continue;
18751 // skip if not item dependent or have alternative item
18752 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18754 ++itr;
18755 continue;
18758 // no alt item, remove aura, restart check
18759 RemoveAurasDueToSpell(aura->GetId());
18760 itr = auras.begin();
18763 // currently casted spells can be dependent from item
18764 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18766 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18767 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18768 InterruptSpell(i);
18772 uint32 Player::GetResurrectionSpellId()
18774 // search priceless resurrection possibilities
18775 uint32 prio = 0;
18776 uint32 spell_id = 0;
18777 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18778 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18780 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18781 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18783 switch((*itr)->GetId())
18785 case 20707: spell_id = 3026; break; // rank 1
18786 case 20762: spell_id = 20758; break; // rank 2
18787 case 20763: spell_id = 20759; break; // rank 3
18788 case 20764: spell_id = 20760; break; // rank 4
18789 case 20765: spell_id = 20761; break; // rank 5
18790 case 27239: spell_id = 27240; break; // rank 6
18791 case 47883: spell_id = 47882; break; // rank 7
18792 default:
18793 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18794 continue;
18797 prio = 3;
18799 // Twisting Nether // prio: 2 (max)
18800 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18802 prio = 2;
18803 spell_id = 23700;
18807 // Reincarnation (passive spell) // prio: 1
18808 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18809 spell_id = 21169;
18811 return spell_id;
18814 // Used in triggers for check "Only to targets that grant experience or honor" req
18815 bool Player::isHonorOrXPTarget(Unit* pVictim)
18817 uint32 v_level = pVictim->getLevel();
18818 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18820 // Victim level less gray level
18821 if(v_level<=k_grey)
18822 return false;
18824 if(pVictim->GetTypeId() == TYPEID_UNIT)
18826 if (((Creature*)pVictim)->isTotem() ||
18827 ((Creature*)pVictim)->isPet() ||
18828 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18829 return false;
18831 return true;
18834 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18836 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18838 // prepare data for near group iteration (PvP and !PvP cases)
18839 uint32 xp = 0;
18840 bool honored_kill = false;
18842 if(Group *pGroup = GetGroup())
18844 uint32 count = 0;
18845 uint32 sum_level = 0;
18846 Player* member_with_max_level = NULL;
18847 Player* not_gray_member_with_max_level = NULL;
18849 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18851 if(member_with_max_level)
18853 /// not get Xp in PvP or no not gray players in group
18854 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18856 /// skip in check PvP case (for speed, not used)
18857 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18858 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18859 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18861 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18863 Player* pGroupGuy = itr->getSource();
18864 if(!pGroupGuy)
18865 continue;
18867 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18868 continue; // member (alive or dead) or his corpse at req. distance
18870 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18871 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18872 honored_kill = true;
18874 // xp and reputation only in !PvP case
18875 if(!PvP)
18877 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18879 // if is in dungeon then all receive full reputation at kill
18880 // rewarded any alive/dead/near_corpse group member
18881 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18883 // XP updated only for alive group member
18884 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18885 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18887 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18889 pGroupGuy->GiveXP(itr_xp, pVictim);
18890 if(Pet* pet = pGroupGuy->GetPet())
18891 pet->GivePetXP(itr_xp/2);
18894 // quest objectives updated only for alive group member or dead but with not released body
18895 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18897 // normal creature (not pet/etc) can be only in !PvP case
18898 if(pVictim->GetTypeId()==TYPEID_UNIT)
18899 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18905 else // if (!pGroup)
18907 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18909 // honor can be in PvP and !PvP (racial leader) cases
18910 if(RewardHonor(pVictim,1))
18911 honored_kill = true;
18913 // xp and reputation only in !PvP case
18914 if(!PvP)
18916 RewardReputation(pVictim,1);
18917 GiveXP(xp, pVictim);
18919 if(Pet* pet = GetPet())
18920 pet->GivePetXP(xp);
18922 // normal creature (not pet/etc) can be only in !PvP case
18923 if(pVictim->GetTypeId()==TYPEID_UNIT)
18924 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18927 return xp || honored_kill;
18930 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18932 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18933 return true;
18935 if(isAlive())
18936 return false;
18938 Corpse* corpse = GetCorpse();
18939 if(!corpse)
18940 return false;
18942 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18945 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18947 Item* item = GetWeaponForAttack(attType,true);
18949 // unarmed only with base attack
18950 if(attType != BASE_ATTACK && !item)
18951 return 0;
18953 // weapon skill or (unarmed for base attack)
18954 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18955 return GetBaseSkillValue(skill);
18958 void Player::ResurectUsingRequestData()
18960 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18961 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18963 ResurrectPlayer(0.0f,false);
18965 if(GetMaxHealth() > m_resurrectHealth)
18966 SetHealth( m_resurrectHealth );
18967 else
18968 SetHealth( GetMaxHealth() );
18970 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18971 SetPower(POWER_MANA, m_resurrectMana );
18972 else
18973 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18975 SetPower(POWER_RAGE, 0 );
18977 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18979 SpawnCorpseBones();
18982 void Player::SetClientControl(Unit* target, uint8 allowMove)
18984 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18985 data.append(target->GetPackGUID());
18986 data << uint8(allowMove);
18987 GetSession()->SendPacket(&data);
18990 void Player::UpdateZoneDependentAuras( uint32 newZone )
18992 // remove new continent flight forms
18993 if( !IsAllowUseFlyMountsHere() )
18995 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18996 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18999 // Some spells applied at enter into zone (with subzones)
19000 switch(newZone)
19002 case 2367: // Old Hillsbrad Foothills
19004 // Human Illusion
19005 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
19006 uint32 spellid = 0;
19007 // all horde races
19008 if( GetTeam() == HORDE )
19009 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
19010 // and some alliance races
19011 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
19012 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
19014 if(spellid && !HasAura(spellid,0) )
19015 CastSpell(this,spellid,true);
19016 break;
19021 void Player::UpdateAreaDependentAuras( uint32 newArea )
19023 // remove auras from spells with area limitations
19024 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19026 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19027 if(GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,GetBattleGroundId())!=0)
19028 RemoveAura(iter);
19029 else
19030 ++iter;
19033 // some auras applied at subzone enter
19034 switch(newArea)
19036 // Dragonmaw Illusion
19037 case 3759: // Netherwing Ledge
19038 case 3939: // Dragonmaw Fortress
19039 case 3966: // Dragonmaw Base Camp
19040 if( GetDummyAura(40214) )
19042 if( !HasAura(40216,0) )
19043 CastSpell(this,40216,true);
19044 if( !HasAura(42016,0) )
19045 CastSpell(this,42016,true);
19047 break;
19048 // Dominion Over Acherus
19049 case 4281: // Acherus: The Ebon Hold
19050 case 4342: // Acherus: The Ebon Hold
19051 if( HasSpell(51721) )
19052 if( !HasAura(51721,0) )
19053 CastSpell(this,51721,true);
19054 break;
19055 // Mist of the Kvaldir
19056 case 4028: //Riplash Strand
19057 case 4029: //Riplash Ruins
19058 case 4106: //Garrosh's Landing
19059 case 4031: //Pal'ea
19060 CastSpell(this,54119,true);
19061 break;
19065 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19067 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19068 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19070 return copseReclaimDelay[0];
19073 time_t now = time(NULL);
19074 // 0..2 full period
19075 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19076 return copseReclaimDelay[count];
19079 void Player::UpdateCorpseReclaimDelay()
19081 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19083 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19084 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19085 return;
19087 time_t now = time(NULL);
19088 if(now < m_deathExpireTime)
19090 // full and partly periods 1..3
19091 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19092 if(count < MAX_DEATH_COUNT)
19093 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19094 else
19095 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19097 else
19098 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19101 void Player::SendCorpseReclaimDelay(bool load)
19103 Corpse* corpse = GetCorpse();
19104 if(!corpse)
19105 return;
19107 uint32 delay;
19108 if(load)
19110 if(corpse->GetGhostTime() > m_deathExpireTime)
19111 return;
19113 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19115 uint32 count;
19116 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19117 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19119 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19120 if(count>=MAX_DEATH_COUNT)
19121 count = MAX_DEATH_COUNT-1;
19123 else
19124 count=0;
19126 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19128 time_t now = time(NULL);
19129 if(now >= expected_time)
19130 return;
19132 delay = expected_time-now;
19134 else
19135 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19137 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19138 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19139 data << uint32(delay*1000);
19140 GetSession()->SendPacket( &data );
19143 Player* Player::GetNextRandomRaidMember(float radius)
19145 Group *pGroup = GetGroup();
19146 if(!pGroup)
19147 return NULL;
19149 std::vector<Player*> nearMembers;
19150 nearMembers.reserve(pGroup->GetMembersCount());
19152 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19154 Player* Target = itr->getSource();
19156 // IsHostileTo check duel and controlled by enemy
19157 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19158 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19159 nearMembers.push_back(Target);
19162 if (nearMembers.empty())
19163 return NULL;
19165 uint32 randTarget = urand(0,nearMembers.size()-1);
19166 return nearMembers[randTarget];
19169 PartyResult Player::CanUninviteFromGroup() const
19171 const Group* grp = GetGroup();
19172 if(!grp)
19173 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19175 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19176 return PARTY_RESULT_YOU_NOT_LEADER;
19178 if(InBattleGround())
19179 return PARTY_RESULT_INVITE_RESTRICTED;
19181 return PARTY_RESULT_OK;
19184 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19186 float water_z = m->GetWaterLevel(x,y);
19187 float terrain_z = m->GetHeight(x,y,z, false); // use .map base surface height
19188 uint8 flag1 = m->GetTerrainType(x,y);
19190 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19191 if (terrain_z <= INVALID_HEIGHT || z < (terrain_z-2) || z > (water_z - 2) )
19192 m_isunderwater &= ~UNDERWATER_INWATER;
19193 else if ((z < (water_z - 2)) && (flag1 & 0x01))
19194 m_isunderwater |= UNDERWATER_INWATER;
19196 //!in lava check, anywhere under lava level
19197 if ((terrain_z <= INVALID_HEIGHT || z < (terrain_z - 0)) && (flag1 == 0x00) && IsInWater())
19198 m_isunderwater |= UNDERWATER_INLAVA;
19199 else
19200 m_isunderwater &= ~UNDERWATER_INLAVA;
19203 void Player::SetCanParry( bool value )
19205 if(m_canParry==value)
19206 return;
19208 m_canParry = value;
19209 UpdateParryPercentage();
19212 void Player::SetCanBlock( bool value )
19214 if(m_canBlock==value)
19215 return;
19217 m_canBlock = value;
19218 UpdateBlockPercentage();
19221 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19223 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19224 if(itr->pos == pos)
19225 return true;
19227 return false;
19230 bool Player::isAllowUseBattleGroundObject()
19232 return ( //InBattleGround() && // in battleground - not need, check in other cases
19233 !IsMounted() && // not mounted
19234 !HasStealthAura() && // not stealthed
19235 !HasInvisibilityAura() && // not invisible
19236 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19237 isAlive() // live player
19241 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19243 uint32 level = getLevel();
19245 if(level > GT_MAX_LEVEL)
19246 level = GT_MAX_LEVEL; // max level in this dbc
19248 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19249 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19250 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19252 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19253 return 0;
19255 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19257 if(!bsc) // shouldn't happen
19258 return 0xFFFFFFFF;
19260 float cost = 0;
19262 if(hairstyle != newhairstyle)
19263 cost += bsc->cost; // full price
19265 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19266 cost += bsc->cost * 0.5f; // +1/2 of price
19268 if(facialhair != newfacialhair)
19269 cost += bsc->cost * 0.75f; // +3/4 of price
19271 return uint32(cost);
19274 void Player::InitGlyphsForLevel()
19276 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19277 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19278 if(gs->Order)
19279 SetGlyphSlot(gs->Order - 1, gs->Id);
19281 uint32 level = getLevel();
19282 uint32 value = 0;
19284 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19285 if(level >= 15)
19286 value |= (0x01 | 0x02);
19287 if(level >= 30)
19288 value |= 0x08;
19289 if(level >= 50)
19290 value |= 0x04;
19291 if(level >= 70)
19292 value |= 0x10;
19293 if(level >= 80)
19294 value |= 0x20;
19296 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19299 void Player::EnterVehicle(Vehicle *vehicle)
19301 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19302 if(!ve)
19303 return;
19305 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19306 if(!veSeat)
19307 return;
19309 vehicle->SetCharmerGUID(GetGUID());
19310 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19311 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19312 vehicle->setFaction(getFaction());
19314 SetCharm(vehicle); // charm
19315 SetFarSightGUID(vehicle->GetGUID()); // set view
19317 SetClientControl(vehicle, 1); // redirect controls to vehicle
19319 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19320 GetSession()->SendPacket(&data);
19322 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19323 data.append(GetPackGUID());
19324 data << uint32(0); // counter?
19325 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19326 data << uint16(0); // special flags
19327 data << uint32(getMSTime()); // time
19328 data << vehicle->GetPositionX(); // x
19329 data << vehicle->GetPositionY(); // y
19330 data << vehicle->GetPositionZ(); // z
19331 data << vehicle->GetOrientation(); // o
19332 // transport part, TODO: load/calculate seat offsets
19333 data << uint64(vehicle->GetGUID()); // transport guid
19334 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19335 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19336 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19337 data << float(0); // transport orientation
19338 data << uint32(getMSTime()); // transport time
19339 data << uint8(0); // seat
19340 // end of transport part
19341 data << uint32(0); // fall time
19342 GetSession()->SendPacket(&data);
19344 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19345 data << uint64(vehicle->GetGUID());
19346 data << uint32(0x00000000);
19347 data << uint32(0x00000000);
19348 data << uint32(0x00000101);
19350 for(uint32 i = 0; i < 10; ++i)
19351 data << uint16(0) << uint8(0) << uint8(i+8);
19353 data << uint8(0);
19354 data << uint8(0);
19355 GetSession()->SendPacket(&data);
19358 void Player::ExitVehicle(Vehicle *vehicle)
19360 vehicle->SetCharmerGUID(0);
19361 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19362 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19363 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19365 SetCharm(NULL);
19366 SetFarSightGUID(0);
19368 SetClientControl(vehicle, 0);
19370 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19371 data.append(GetPackGUID());
19372 data << uint32(0); // counter?
19373 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19374 data << uint16(0x40); // special flags
19375 data << uint32(getMSTime()); // time
19376 data << vehicle->GetPositionX(); // x
19377 data << vehicle->GetPositionY(); // y
19378 data << vehicle->GetPositionZ(); // z
19379 data << vehicle->GetOrientation(); // o
19380 data << uint32(0); // fall time
19381 GetSession()->SendPacket(&data);
19383 data.Initialize(SMSG_PET_SPELLS, 8+4);
19384 data << uint64(0);
19385 data << uint32(0);
19386 GetSession()->SendPacket(&data);
19388 // only for flyable vehicles?
19389 CastSpell(this, 45472, true); // Parachute
19392 bool Player::HasTitle(uint32 bitIndex)
19394 if (bitIndex > 128)
19395 return false;
19397 uint32 fieldIndexOffset = bitIndex/32;
19398 uint32 flag = 1 << (bitIndex%32);
19399 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19402 void Player::SetTitle(CharTitlesEntry const* title)
19404 uint32 fieldIndexOffset = title->bit_index/32;
19405 uint32 flag = 1 << (title->bit_index%32);
19406 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19409 void Player::ConvertRune(uint8 index, uint8 newType)
19411 SetCurrentRune(index, newType);
19413 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19414 data << uint8(index);
19415 data << uint8(newType);
19416 GetSession()->SendPacket(&data);
19419 void Player::ResyncRunes(uint8 count)
19421 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19422 for(uint32 i = 0; i < count; ++i)
19424 data << uint8(GetCurrentRune(i)); // rune type
19425 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19427 GetSession()->SendPacket(&data);
19430 void Player::AddRunePower(uint8 index)
19432 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19433 data << uint32(1 << index); // mask (0x00-0x3F probably)
19434 GetSession()->SendPacket(&data);
19437 void Player::InitRunes()
19439 if(getClass() != CLASS_DEATH_KNIGHT)
19440 return;
19442 m_runes = new Runes;
19444 m_runes->runeState = 0;
19446 for(uint32 i = 0; i < MAX_RUNES; ++i)
19448 SetBaseRune(i, i / 2); // init base types
19449 SetCurrentRune(i, i / 2); // init current types
19450 SetRuneCooldown(i, 0); // reset cooldowns
19451 m_runes->SetRuneState(i);
19454 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19455 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19458 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19460 Loot loot;
19461 loot.FillLoot (loot_id,store,this,true);
19463 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19464 for(uint32 i = 0; i < max_slot; ++i)
19466 LootItem* lootItem = loot.LootItemInSlot(i,this);
19468 ItemPosCountVec dest;
19469 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19470 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19471 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19472 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19473 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19474 if(msg != EQUIP_ERR_OK)
19476 SendEquipError( msg, NULL, NULL );
19477 continue;
19480 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19481 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19485 uint32 Player::CalculateTalentsPoints() const
19487 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19489 if(getClass() != CLASS_DEATH_KNIGHT)
19490 return base_talent;
19492 uint32 talentPointsForLevel =
19493 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19494 + m_questRewardTalentCount;
19496 if(talentPointsForLevel > base_talent)
19497 talentPointsForLevel = base_talent;
19499 return talentPointsForLevel;
19502 bool Player::IsAllowUseFlyMountsHere() const
19504 if (isGameMaster())
19505 return true;
19507 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19508 return v_map == 530 || v_map == 571 && HasSpell(54197);
19511 void Player::learnSpellHighRank(uint32 spellid)
19513 learnSpell(spellid,false);
19515 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19516 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19517 learnSpellHighRank(itr->second);
19520 void Player::_LoadSkills()
19522 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19524 // reset skill modifiers and set correct unlearn flags
19525 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
19527 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19529 // set correct unlearn bit
19530 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19531 if(!id) continue;
19533 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19534 if(!pSkill) continue;
19536 // enable unlearn button for primary professions only
19537 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19538 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19539 else
19540 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19542 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19544 learnSkillRewardedSpells(id, vskill);
19547 // special settings
19548 if(getClass()==CLASS_DEATH_KNIGHT)
19550 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19551 if(base_level < 1)
19552 base_level = 1;
19553 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19554 if(base_skill < 1)
19555 base_skill = 1; // skill mast be known and then > 0 in any case
19557 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19558 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19559 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19560 SetSkill(SKILL_AXES, base_skill,base_skill);
19561 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19562 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19563 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19564 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19565 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19566 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19567 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19568 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19569 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19570 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19571 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19572 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19576 uint32 Player::GetPhaseMaskForSpawn() const
19578 uint32 phase = PHASEMASK_NORMAL;
19579 if(!isGameMaster())
19580 phase = GetPhaseMask();
19581 else
19583 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19584 if(!phases.empty())
19585 phase = phases.front()->GetMiscValue();
19588 // some aura phases include 1 normal map in addition to phase itself
19589 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19590 return n_phase;
19592 return PHASEMASK_NORMAL;
19595 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19597 ItemPrototype const* pProto = pItem->GetProto();
19599 // proto based limitations
19600 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19601 return res;
19603 // check unique-equipped on gems
19604 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19606 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19607 if(!enchant_id)
19608 continue;
19609 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19610 if(!enchantEntry)
19611 continue;
19613 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19614 if(!pGem)
19615 continue;
19617 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19618 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19619 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19621 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19622 return res;
19625 return EQUIP_ERR_OK;
19628 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19630 // check unique-equipped on item
19631 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19633 // there is an equip limit on this item
19634 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19635 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19638 // check unique-equipped limit
19639 if (itemProto->ItemLimitCategory)
19641 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19642 if(!limitEntry)
19643 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19645 if(limit_count > limitEntry->maxCount)
19646 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19648 // there is an equip limit on this item
19649 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19650 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19653 return EQUIP_ERR_OK;