[7261] Better check DB corrdinates for bg entry at player loading.
[getmangos.git] / src / game / Player.cpp
blob131377b8d8b3fbf1113151f6cb78e0e09a790e49
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].bgQueueType = 0;
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 will 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 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2312 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2313 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2314 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2315 SetUInt32Value(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 break;
6732 case ITEM_MOD_RANGED_ATTACK_POWER:
6733 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6734 break;
6735 case ITEM_MOD_FERAL_ATTACK_POWER:
6736 ApplyFeralAPBonus(int32(val), apply);
6737 break;
6738 case ITEM_MOD_SPELL_HEALING_DONE:
6739 ApplySpellHealingBonus(int32(val), apply);
6740 break;
6741 case ITEM_MOD_SPELL_DAMAGE_DONE:
6742 ApplySpellDamageBonus(int32(val), apply);
6743 break;
6744 case ITEM_MOD_MANA_REGENERATION:
6745 ApplyManaRegenBonus(int32(val), apply);
6746 break;
6747 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6748 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6749 break;
6750 case ITEM_MOD_SPELL_POWER:
6751 ApplySpellHealingBonus(int32(val), apply);
6752 ApplySpellDamageBonus(int32(val), apply);
6753 break;
6757 if (proto->Armor)
6758 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6760 if (proto->Block)
6761 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6763 if (proto->HolyRes)
6764 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6766 if (proto->FireRes)
6767 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6769 if (proto->NatureRes)
6770 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6772 if (proto->FrostRes)
6773 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6775 if (proto->ShadowRes)
6776 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6778 if (proto->ArcaneRes)
6779 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6781 WeaponAttackType attType = BASE_ATTACK;
6782 float damage = 0.0f;
6784 if( slot == EQUIPMENT_SLOT_RANGED && (
6785 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6786 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6788 attType = RANGED_ATTACK;
6790 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6792 attType = OFF_ATTACK;
6795 if (proto->Damage[0].DamageMin > 0 )
6797 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6798 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6799 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6802 if (proto->Damage[0].DamageMax > 0 )
6804 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6805 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6808 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6809 return;
6811 if (proto->Delay)
6813 if(slot == EQUIPMENT_SLOT_RANGED)
6814 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6815 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6816 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6817 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6818 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6821 if(CanModifyStats() && (damage || proto->Delay))
6822 UpdateDamagePhysical(attType);
6825 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6827 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6828 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6829 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6831 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6832 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6833 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6835 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6836 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6837 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6840 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6842 // generic not weapon specific case processes in aura code
6843 if(aura->GetSpellProto()->EquippedItemClass == -1)
6844 return;
6846 BaseModGroup mod = BASEMOD_END;
6847 switch(attackType)
6849 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6850 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6851 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6852 default: return;
6855 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6857 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6861 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6863 // ignore spell mods for not wands
6864 Modifier const* modifier = aura->GetModifier();
6865 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6866 return;
6868 // generic not weapon specific case processes in aura code
6869 if(aura->GetSpellProto()->EquippedItemClass == -1)
6870 return;
6872 UnitMods unitMod = UNIT_MOD_END;
6873 switch(attackType)
6875 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6876 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6877 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6878 default: return;
6881 UnitModifierType unitModType = TOTAL_VALUE;
6882 switch(modifier->m_auraname)
6884 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6885 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6886 default: return;
6889 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6891 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6895 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6897 if(!item)
6898 return;
6900 ItemPrototype const *proto = item->GetProto();
6901 if(!proto)
6902 return;
6904 for (int i = 0; i < 5; i++)
6906 _Spell const& spellData = proto->Spells[i];
6908 // no spell
6909 if(!spellData.SpellId )
6910 continue;
6912 // wrong triggering type
6913 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6914 continue;
6916 // check if it is valid spell
6917 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6918 if(!spellproto)
6919 continue;
6921 ApplyEquipSpell(spellproto,item,apply,form_change);
6925 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6927 if(apply)
6929 // Cannot be used in this stance/form
6930 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6931 return;
6933 if(form_change) // check aura active state from other form
6935 bool found = false;
6936 for (int k=0; k < 3; ++k)
6938 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6939 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6941 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6943 found = true;
6944 break;
6947 if(found)
6948 break;
6951 if(found) // and skip re-cast already active aura at form change
6952 return;
6955 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6957 CastSpell(this,spellInfo,true,item);
6959 else
6961 if(form_change) // check aura compatibility
6963 // Cannot be used in this stance/form
6964 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6965 return; // and remove only not compatible at form change
6968 if(item)
6969 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6970 else
6971 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6975 void Player::UpdateEquipSpellsAtFormChange()
6977 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6979 if(m_items[i] && !m_items[i]->IsBroken())
6981 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6982 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6986 // item set bonuses not dependent from item broken state
6987 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6989 ItemSetEffect* eff = ItemSetEff[setindex];
6990 if(!eff)
6991 continue;
6993 for(uint32 y=0;y<8; ++y)
6995 SpellEntry const* spellInfo = eff->spells[y];
6996 if(!spellInfo)
6997 continue;
6999 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7000 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7005 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
7007 if(!item || item->IsBroken())
7008 return;
7010 ItemPrototype const *proto = item->GetProto();
7011 if(!proto)
7012 return;
7014 if (!Target || Target == this )
7015 return;
7017 for (int i = 0; i < 5; i++)
7019 _Spell const& spellData = proto->Spells[i];
7021 // no spell
7022 if(!spellData.SpellId )
7023 continue;
7025 // wrong triggering type
7026 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7027 continue;
7029 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7030 if(!spellInfo)
7032 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7033 continue;
7036 // not allow proc extra attack spell at extra attack
7037 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7038 return;
7040 float chance = spellInfo->procChance;
7042 if(spellData.SpellPPMRate)
7044 uint32 WeaponSpeed = GetAttackTime(attType);
7045 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7047 else if(chance > 100.0f)
7049 chance = GetWeaponProcChance();
7052 if (roll_chance_f(chance))
7053 CastSpell(Target, spellInfo->Id, true, item);
7056 // item combat enchantments
7057 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7059 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7060 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7061 if(!pEnchant) continue;
7062 for (int s=0;s<3;s++)
7064 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7065 continue;
7067 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7068 if (!spellInfo)
7070 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7071 continue;
7074 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7075 if (roll_chance_f(chance))
7077 if(IsPositiveSpell(pEnchant->spellid[s]))
7078 CastSpell(this, pEnchant->spellid[s], true, item);
7079 else
7080 CastSpell(Target, pEnchant->spellid[s], true, item);
7086 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7088 ItemPrototype const* proto = item->GetProto();
7089 // special learning case
7090 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7092 uint32 learn_spell_id = proto->Spells[0].SpellId;
7093 uint32 learning_spell_id = proto->Spells[1].SpellId;
7095 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7096 if(!spellInfo)
7098 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7099 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7100 return;
7103 Spell *spell = new Spell(this, spellInfo, false);
7104 spell->m_CastItem = item;
7105 spell->m_cast_count = cast_count; //set count of casts
7106 spell->m_currentBasePoints[0] = learning_spell_id;
7107 spell->prepare(&targets);
7108 return;
7111 // use triggered flag only for items with many spell casts and for not first cast
7112 int count = 0;
7114 // item spells casted at use
7115 for(int i = 0; i < 5; ++i)
7117 _Spell const& spellData = proto->Spells[i];
7119 // no spell
7120 if(!spellData.SpellId)
7121 continue;
7123 // wrong triggering type
7124 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7125 continue;
7127 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7128 if(!spellInfo)
7130 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7131 continue;
7134 Spell *spell = new Spell(this, spellInfo, (count > 0));
7135 spell->m_CastItem = item;
7136 spell->m_cast_count = cast_count; // set count of casts
7137 spell->m_glyphIndex = glyphIndex; // glyph index
7138 spell->prepare(&targets);
7140 ++count;
7143 // Item enchantments spells casted at use
7144 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7146 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7147 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7148 if(!pEnchant) continue;
7149 for (int s=0;s<3;s++)
7151 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7152 continue;
7154 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7155 if (!spellInfo)
7157 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7158 continue;
7161 Spell *spell = new Spell(this, spellInfo, (count > 0));
7162 spell->m_CastItem = item;
7163 spell->m_cast_count = cast_count; // set count of casts
7164 spell->m_glyphIndex = glyphIndex; // glyph index
7165 spell->prepare(&targets);
7167 ++count;
7172 void Player::_RemoveAllItemMods()
7174 sLog.outDebug("_RemoveAllItemMods start.");
7176 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7178 if(m_items[i])
7180 ItemPrototype const *proto = m_items[i]->GetProto();
7181 if(!proto)
7182 continue;
7184 // item set bonuses not dependent from item broken state
7185 if(proto->ItemSet)
7186 RemoveItemsSetItem(this,proto);
7188 if(m_items[i]->IsBroken())
7189 continue;
7191 ApplyItemEquipSpell(m_items[i],false);
7192 ApplyEnchantment(m_items[i], false);
7196 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7198 if(m_items[i])
7200 if(m_items[i]->IsBroken())
7201 continue;
7202 ItemPrototype const *proto = m_items[i]->GetProto();
7203 if(!proto)
7204 continue;
7206 uint32 attacktype = Player::GetAttackBySlot(i);
7207 if(attacktype < MAX_ATTACK)
7208 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7210 _ApplyItemBonuses(proto,i, false);
7212 if( i == EQUIPMENT_SLOT_RANGED )
7213 _ApplyAmmoBonuses();
7217 sLog.outDebug("_RemoveAllItemMods complete.");
7220 void Player::_ApplyAllItemMods()
7222 sLog.outDebug("_ApplyAllItemMods start.");
7224 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7226 if(m_items[i])
7228 if(m_items[i]->IsBroken())
7229 continue;
7231 ItemPrototype const *proto = m_items[i]->GetProto();
7232 if(!proto)
7233 continue;
7235 uint32 attacktype = Player::GetAttackBySlot(i);
7236 if(attacktype < MAX_ATTACK)
7237 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7239 _ApplyItemBonuses(proto,i, true);
7241 if( i == EQUIPMENT_SLOT_RANGED )
7242 _ApplyAmmoBonuses();
7246 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7248 if(m_items[i])
7250 ItemPrototype const *proto = m_items[i]->GetProto();
7251 if(!proto)
7252 continue;
7254 // item set bonuses not dependent from item broken state
7255 if(proto->ItemSet)
7256 AddItemsSetItem(this,m_items[i]);
7258 if(m_items[i]->IsBroken())
7259 continue;
7261 ApplyItemEquipSpell(m_items[i],true);
7262 ApplyEnchantment(m_items[i], true);
7266 sLog.outDebug("_ApplyAllItemMods complete.");
7269 void Player::_ApplyAmmoBonuses()
7271 // check ammo
7272 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7273 if(!ammo_id)
7274 return;
7276 float currentAmmoDPS;
7278 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7279 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7280 currentAmmoDPS = 0.0f;
7281 else
7282 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7284 if(currentAmmoDPS == GetAmmoDPS())
7285 return;
7287 m_ammoDPS = currentAmmoDPS;
7289 if(CanModifyStats())
7290 UpdateDamagePhysical(RANGED_ATTACK);
7293 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7295 if(!ammo_proto)
7296 return false;
7298 // check ranged weapon
7299 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7300 if(!weapon || weapon->IsBroken() )
7301 return false;
7303 ItemPrototype const* weapon_proto = weapon->GetProto();
7304 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7305 return false;
7307 // check ammo ws. weapon compatibility
7308 switch(weapon_proto->SubClass)
7310 case ITEM_SUBCLASS_WEAPON_BOW:
7311 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7312 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7313 return false;
7314 break;
7315 case ITEM_SUBCLASS_WEAPON_GUN:
7316 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7317 return false;
7318 break;
7319 default:
7320 return false;
7323 return true;
7326 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7327 Called by remove insignia spell effect */
7328 void Player::RemovedInsignia(Player* looterPlr)
7330 if (!GetBattleGroundId())
7331 return;
7333 // If not released spirit, do it !
7334 if(m_deathTimer > 0)
7336 m_deathTimer = 0;
7337 BuildPlayerRepop();
7338 RepopAtGraveyard();
7341 Corpse *corpse = GetCorpse();
7342 if (!corpse)
7343 return;
7345 // We have to convert player corpse to bones, not to be able to resurrect there
7346 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7347 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7348 if (!bones)
7349 return;
7351 // Now we must make bones lootable, and send player loot
7352 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7354 // We store the level of our player in the gold field
7355 // We retrieve this information at Player::SendLoot()
7356 bones->loot.gold = getLevel();
7357 bones->lootRecipient = looterPlr;
7358 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7361 /*Loot type MUST be
7362 1-corpse, go
7363 2-skinning
7364 3-Fishing
7367 void Player::SendLootRelease( uint64 guid )
7369 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7370 data << uint64(guid) << uint8(1);
7371 SendDirectMessage( &data );
7374 void Player::SendLoot(uint64 guid, LootType loot_type)
7376 Loot *loot = 0;
7377 PermissionTypes permission = ALL_PERMISSION;
7379 sLog.outDebug("Player::SendLoot");
7380 if (IS_GAMEOBJECT_GUID(guid))
7382 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7383 GameObject *go =
7384 ObjectAccessor::GetGameObject(*this, guid);
7386 // not check distance for GO in case owned GO (fishing bobber case, for example)
7387 // And permit out of range GO with no owner in case fishing hole
7388 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7390 SendLootRelease(guid);
7391 return;
7394 loot = &go->loot;
7396 if(go->getLootState() == GO_READY)
7398 uint32 lootid = go->GetLootId();
7400 if(lootid)
7402 sLog.outDebug(" if(lootid)");
7403 loot->clear();
7404 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7407 if(loot_type == LOOT_FISHING)
7408 go->getFishLoot(loot,this);
7410 go->SetLootState(GO_ACTIVATED);
7413 else if (IS_ITEM_GUID(guid))
7415 Item *item = GetItemByGuid( guid );
7417 if (!item)
7419 SendLootRelease(guid);
7420 return;
7423 if(loot_type == LOOT_DISENCHANTING)
7425 loot = &item->loot;
7427 if(!item->m_lootGenerated)
7429 item->m_lootGenerated = true;
7430 loot->clear();
7431 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7434 else if(loot_type == LOOT_PROSPECTING)
7436 loot = &item->loot;
7438 if(!item->m_lootGenerated)
7440 item->m_lootGenerated = true;
7441 loot->clear();
7442 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7445 else if(loot_type == LOOT_MILLING)
7447 loot = &item->loot;
7449 if(!item->m_lootGenerated)
7451 item->m_lootGenerated = true;
7452 loot->clear();
7453 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7456 else
7458 loot = &item->loot;
7460 if(!item->m_lootGenerated)
7462 item->m_lootGenerated = true;
7463 loot->clear();
7464 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7466 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7470 else if (IS_CORPSE_GUID(guid)) // remove insignia
7472 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7474 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7476 SendLootRelease(guid);
7477 return;
7480 loot = &bones->loot;
7482 if (!bones->lootForBody)
7484 bones->lootForBody = true;
7485 uint32 pLevel = bones->loot.gold;
7486 bones->loot.clear();
7487 // It may need a better formula
7488 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7489 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7492 if (bones->lootRecipient != this)
7493 permission = NONE_PERMISSION;
7495 else
7497 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7499 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7500 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7502 SendLootRelease(guid);
7503 return;
7506 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7508 SendLootRelease(guid);
7509 return;
7512 loot = &creature->loot;
7514 if(loot_type == LOOT_PICKPOCKETING)
7516 if ( !creature->lootForPickPocketed )
7518 creature->lootForPickPocketed = true;
7519 loot->clear();
7521 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7522 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7524 // Generate extra money for pick pocket loot
7525 const uint32 a = urand(0, creature->getLevel()/2);
7526 const uint32 b = urand(0, getLevel()/2);
7527 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7530 else
7532 // the player whose group may loot the corpse
7533 Player *recipient = creature->GetLootRecipient();
7534 if (!recipient)
7536 creature->SetLootRecipient(this);
7537 recipient = this;
7540 if (creature->lootForPickPocketed)
7542 creature->lootForPickPocketed = false;
7543 loot->clear();
7546 if(!creature->lootForBody)
7548 creature->lootForBody = true;
7549 loot->clear();
7551 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7552 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7554 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7556 if(Group* group = recipient->GetGroup())
7558 group->UpdateLooterGuid(creature,true);
7560 switch (group->GetLootMethod())
7562 case GROUP_LOOT:
7563 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7564 group->GroupLoot(recipient->GetGUID(), loot, creature);
7565 break;
7566 case NEED_BEFORE_GREED:
7567 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7568 break;
7569 case MASTER_LOOT:
7570 group->MasterLoot(recipient->GetGUID(), loot, creature);
7571 break;
7572 default:
7573 break;
7578 // possible only if creature->lootForBody && loot->empty() at spell cast check
7579 if (loot_type == LOOT_SKINNING)
7581 loot->clear();
7582 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7584 // set group rights only for loot_type != LOOT_SKINNING
7585 else
7587 if(Group* group = GetGroup())
7589 if( group == recipient->GetGroup() )
7591 if(group->GetLootMethod() == FREE_FOR_ALL)
7592 permission = ALL_PERMISSION;
7593 else if(group->GetLooterGuid() == GetGUID())
7595 if(group->GetLootMethod() == MASTER_LOOT)
7596 permission = MASTER_PERMISSION;
7597 else
7598 permission = ALL_PERMISSION;
7600 else
7601 permission = GROUP_PERMISSION;
7603 else
7604 permission = NONE_PERMISSION;
7606 else if(recipient == this)
7607 permission = ALL_PERMISSION;
7608 else
7609 permission = NONE_PERMISSION;
7614 SetLootGUID(guid);
7616 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7617 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7618 loot_type = LOOT_SKINNING;
7620 if(loot_type == LOOT_FISHINGHOLE)
7621 loot_type = LOOT_FISHING;
7623 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7625 data << uint64(guid);
7626 data << uint8(loot_type);
7627 data << LootView(*loot, this, permission);
7629 SendDirectMessage(&data);
7631 // add 'this' player as one of the players that are looting 'loot'
7632 if (permission != NONE_PERMISSION)
7633 loot->AddLooter(GetGUID());
7635 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7636 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7639 void Player::SendNotifyLootMoneyRemoved()
7641 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7642 GetSession()->SendPacket( &data );
7645 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7647 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7648 data << uint8(lootSlot);
7649 GetSession()->SendPacket( &data );
7652 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7654 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7655 data << Field;
7656 data << Value;
7657 GetSession()->SendPacket(&data);
7660 void Player::SendInitWorldStates()
7662 // data depends on zoneid/mapid...
7663 BattleGround* bg = GetBattleGround();
7664 uint16 NumberOfFields = 0;
7665 uint32 mapid = GetMapId();
7666 uint32 zoneid = GetZoneId();
7667 uint32 areaid = GetAreaId();
7668 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7669 // may be exist better way to do this...
7670 switch(zoneid)
7672 case 0:
7673 case 1:
7674 case 4:
7675 case 8:
7676 case 10:
7677 case 11:
7678 case 12:
7679 case 36:
7680 case 38:
7681 case 40:
7682 case 41:
7683 case 51:
7684 case 267:
7685 case 1519:
7686 case 1537:
7687 case 2257:
7688 case 2918:
7689 NumberOfFields = 8;
7690 break;
7691 case 139:
7692 NumberOfFields = 41;
7693 break;
7694 case 1377:
7695 NumberOfFields = 15;
7696 break;
7697 case 2597:
7698 NumberOfFields = 83;
7699 break;
7700 case 3277:
7701 NumberOfFields = 16;
7702 break;
7703 case 3358:
7704 case 3820:
7705 NumberOfFields = 40;
7706 break;
7707 case 3483:
7708 NumberOfFields = 27;
7709 break;
7710 case 3518:
7711 NumberOfFields = 39;
7712 break;
7713 case 3519:
7714 NumberOfFields = 38;
7715 break;
7716 case 3521:
7717 NumberOfFields = 37;
7718 break;
7719 case 3698:
7720 case 3702:
7721 case 3968:
7722 NumberOfFields = 11;
7723 break;
7724 case 3703:
7725 NumberOfFields = 11;
7726 break;
7727 default:
7728 NumberOfFields = 12;
7729 break;
7732 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7733 data << uint32(mapid); // mapid
7734 data << uint32(zoneid); // zone id
7735 data << uint32(areaid); // area id, new 2.1.0
7736 data << uint16(NumberOfFields); // count of uint64 blocks
7737 data << uint32(0x8d8) << uint32(0x0); // 1
7738 data << uint32(0x8d7) << uint32(0x0); // 2
7739 data << uint32(0x8d6) << uint32(0x0); // 3
7740 data << uint32(0x8d5) << uint32(0x0); // 4
7741 data << uint32(0x8d4) << uint32(0x0); // 5
7742 data << uint32(0x8d3) << uint32(0x0); // 6
7743 // 7 1 - Arena season in progress, 0 - end of season
7744 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7745 // 8 Arena season id
7746 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7747 if(mapid == 530) // Outland
7749 data << uint32(0x9bf) << uint32(0x0); // 7
7750 data << uint32(0x9bd) << uint32(0xF); // 8
7751 data << uint32(0x9bb) << uint32(0xF); // 9
7753 switch(zoneid)
7755 case 1:
7756 case 11:
7757 case 12:
7758 case 38:
7759 case 40:
7760 case 51:
7761 case 1519:
7762 case 1537:
7763 case 2257:
7764 break;
7765 case 2597: // AV
7766 data << uint32(0x7ae) << uint32(0x1); // 7
7767 data << uint32(0x532) << uint32(0x1); // 8
7768 data << uint32(0x531) << uint32(0x0); // 9
7769 data << uint32(0x52e) << uint32(0x0); // 10
7770 data << uint32(0x571) << uint32(0x0); // 11
7771 data << uint32(0x570) << uint32(0x0); // 12
7772 data << uint32(0x567) << uint32(0x1); // 13
7773 data << uint32(0x566) << uint32(0x1); // 14
7774 data << uint32(0x550) << uint32(0x1); // 15
7775 data << uint32(0x544) << uint32(0x0); // 16
7776 data << uint32(0x536) << uint32(0x0); // 17
7777 data << uint32(0x535) << uint32(0x1); // 18
7778 data << uint32(0x518) << uint32(0x0); // 19
7779 data << uint32(0x517) << uint32(0x0); // 20
7780 data << uint32(0x574) << uint32(0x0); // 21
7781 data << uint32(0x573) << uint32(0x0); // 22
7782 data << uint32(0x572) << uint32(0x0); // 23
7783 data << uint32(0x56f) << uint32(0x0); // 24
7784 data << uint32(0x56e) << uint32(0x0); // 25
7785 data << uint32(0x56d) << uint32(0x0); // 26
7786 data << uint32(0x56c) << uint32(0x0); // 27
7787 data << uint32(0x56b) << uint32(0x0); // 28
7788 data << uint32(0x56a) << uint32(0x1); // 29
7789 data << uint32(0x569) << uint32(0x1); // 30
7790 data << uint32(0x568) << uint32(0x1); // 13
7791 data << uint32(0x565) << uint32(0x0); // 32
7792 data << uint32(0x564) << uint32(0x0); // 33
7793 data << uint32(0x563) << uint32(0x0); // 34
7794 data << uint32(0x562) << uint32(0x0); // 35
7795 data << uint32(0x561) << uint32(0x0); // 36
7796 data << uint32(0x560) << uint32(0x0); // 37
7797 data << uint32(0x55f) << uint32(0x0); // 38
7798 data << uint32(0x55e) << uint32(0x0); // 39
7799 data << uint32(0x55d) << uint32(0x0); // 40
7800 data << uint32(0x3c6) << uint32(0x4); // 41
7801 data << uint32(0x3c4) << uint32(0x6); // 42
7802 data << uint32(0x3c2) << uint32(0x4); // 43
7803 data << uint32(0x516) << uint32(0x1); // 44
7804 data << uint32(0x515) << uint32(0x0); // 45
7805 data << uint32(0x3b6) << uint32(0x6); // 46
7806 data << uint32(0x55c) << uint32(0x0); // 47
7807 data << uint32(0x55b) << uint32(0x0); // 48
7808 data << uint32(0x55a) << uint32(0x0); // 49
7809 data << uint32(0x559) << uint32(0x0); // 50
7810 data << uint32(0x558) << uint32(0x0); // 51
7811 data << uint32(0x557) << uint32(0x0); // 52
7812 data << uint32(0x556) << uint32(0x0); // 53
7813 data << uint32(0x555) << uint32(0x0); // 54
7814 data << uint32(0x554) << uint32(0x1); // 55
7815 data << uint32(0x553) << uint32(0x1); // 56
7816 data << uint32(0x552) << uint32(0x1); // 57
7817 data << uint32(0x551) << uint32(0x1); // 58
7818 data << uint32(0x54f) << uint32(0x0); // 59
7819 data << uint32(0x54e) << uint32(0x0); // 60
7820 data << uint32(0x54d) << uint32(0x1); // 61
7821 data << uint32(0x54c) << uint32(0x0); // 62
7822 data << uint32(0x54b) << uint32(0x0); // 63
7823 data << uint32(0x545) << uint32(0x0); // 64
7824 data << uint32(0x543) << uint32(0x1); // 65
7825 data << uint32(0x542) << uint32(0x0); // 66
7826 data << uint32(0x540) << uint32(0x0); // 67
7827 data << uint32(0x53f) << uint32(0x0); // 68
7828 data << uint32(0x53e) << uint32(0x0); // 69
7829 data << uint32(0x53d) << uint32(0x0); // 70
7830 data << uint32(0x53c) << uint32(0x0); // 71
7831 data << uint32(0x53b) << uint32(0x0); // 72
7832 data << uint32(0x53a) << uint32(0x1); // 73
7833 data << uint32(0x539) << uint32(0x0); // 74
7834 data << uint32(0x538) << uint32(0x0); // 75
7835 data << uint32(0x537) << uint32(0x0); // 76
7836 data << uint32(0x534) << uint32(0x0); // 77
7837 data << uint32(0x533) << uint32(0x0); // 78
7838 data << uint32(0x530) << uint32(0x0); // 79
7839 data << uint32(0x52f) << uint32(0x0); // 80
7840 data << uint32(0x52d) << uint32(0x1); // 81
7841 break;
7842 case 3277: // WS
7843 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7844 bg->FillInitialWorldStates(data);
7845 else
7847 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7848 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7849 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7850 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7851 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7852 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7853 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7854 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7856 break;
7857 case 3358: // AB
7858 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7859 bg->FillInitialWorldStates(data);
7860 else
7862 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7863 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7864 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7865 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7866 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7867 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7868 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7869 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7870 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7871 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7872 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7873 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7874 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7875 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7876 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7877 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7878 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7879 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7880 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7881 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7882 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7883 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7884 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7885 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7886 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7887 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7888 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7889 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7890 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7891 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7892 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7893 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7895 break;
7896 case 3820: // EY
7897 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7898 bg->FillInitialWorldStates(data);
7899 else
7901 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7902 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7903 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7904 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7905 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7906 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7907 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7908 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7909 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7910 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7911 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7912 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7913 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7914 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7915 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7916 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7917 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7918 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7919 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7920 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7921 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7922 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7923 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7924 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7925 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7926 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7927 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7928 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7929 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7930 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7931 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7932 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7933 // and some more ... unknown
7935 break;
7936 case 3483: // Hellfire Peninsula
7937 data << uint32(0x9ba) << uint32(0x1); // 10
7938 data << uint32(0x9b9) << uint32(0x1); // 11
7939 data << uint32(0x9b5) << uint32(0x0); // 12
7940 data << uint32(0x9b4) << uint32(0x1); // 13
7941 data << uint32(0x9b3) << uint32(0x0); // 14
7942 data << uint32(0x9b2) << uint32(0x0); // 15
7943 data << uint32(0x9b1) << uint32(0x1); // 16
7944 data << uint32(0x9b0) << uint32(0x0); // 17
7945 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7946 data << uint32(0x9ac) << uint32(0x0); // 19
7947 data << uint32(0x9a8) << uint32(0x0); // 20
7948 data << uint32(0x9a7) << uint32(0x0); // 21
7949 data << uint32(0x9a6) << uint32(0x1); // 22
7950 break;
7951 case 3519: // Terokkar Forest
7952 data << uint32(0xa41) << uint32(0x0); // 10
7953 data << uint32(0xa40) << uint32(0x14); // 11
7954 data << uint32(0xa3f) << uint32(0x0); // 12
7955 data << uint32(0xa3e) << uint32(0x0); // 13
7956 data << uint32(0xa3d) << uint32(0x5); // 14
7957 data << uint32(0xa3c) << uint32(0x0); // 15
7958 data << uint32(0xa87) << uint32(0x0); // 16
7959 data << uint32(0xa86) << uint32(0x0); // 17
7960 data << uint32(0xa85) << uint32(0x0); // 18
7961 data << uint32(0xa84) << uint32(0x0); // 19
7962 data << uint32(0xa83) << uint32(0x0); // 20
7963 data << uint32(0xa82) << uint32(0x0); // 21
7964 data << uint32(0xa81) << uint32(0x0); // 22
7965 data << uint32(0xa80) << uint32(0x0); // 23
7966 data << uint32(0xa7e) << uint32(0x0); // 24
7967 data << uint32(0xa7d) << uint32(0x0); // 25
7968 data << uint32(0xa7c) << uint32(0x0); // 26
7969 data << uint32(0xa7b) << uint32(0x0); // 27
7970 data << uint32(0xa7a) << uint32(0x0); // 28
7971 data << uint32(0xa79) << uint32(0x0); // 29
7972 data << uint32(0x9d0) << uint32(0x5); // 30
7973 data << uint32(0x9ce) << uint32(0x0); // 31
7974 data << uint32(0x9cd) << uint32(0x0); // 32
7975 data << uint32(0x9cc) << uint32(0x0); // 33
7976 data << uint32(0xa88) << uint32(0x0); // 34
7977 data << uint32(0xad0) << uint32(0x0); // 35
7978 data << uint32(0xacf) << uint32(0x1); // 36
7979 break;
7980 case 3521: // Zangarmarsh
7981 data << uint32(0x9e1) << uint32(0x0); // 10
7982 data << uint32(0x9e0) << uint32(0x0); // 11
7983 data << uint32(0x9df) << uint32(0x0); // 12
7984 data << uint32(0xa5d) << uint32(0x1); // 13
7985 data << uint32(0xa5c) << uint32(0x0); // 14
7986 data << uint32(0xa5b) << uint32(0x1); // 15
7987 data << uint32(0xa5a) << uint32(0x0); // 16
7988 data << uint32(0xa59) << uint32(0x1); // 17
7989 data << uint32(0xa58) << uint32(0x0); // 18
7990 data << uint32(0xa57) << uint32(0x0); // 19
7991 data << uint32(0xa56) << uint32(0x0); // 20
7992 data << uint32(0xa55) << uint32(0x1); // 21
7993 data << uint32(0xa54) << uint32(0x0); // 22
7994 data << uint32(0x9e7) << uint32(0x0); // 23
7995 data << uint32(0x9e6) << uint32(0x0); // 24
7996 data << uint32(0x9e5) << uint32(0x0); // 25
7997 data << uint32(0xa00) << uint32(0x0); // 26
7998 data << uint32(0x9ff) << uint32(0x1); // 27
7999 data << uint32(0x9fe) << uint32(0x0); // 28
8000 data << uint32(0x9fd) << uint32(0x0); // 29
8001 data << uint32(0x9fc) << uint32(0x1); // 30
8002 data << uint32(0x9fb) << uint32(0x0); // 31
8003 data << uint32(0xa62) << uint32(0x0); // 32
8004 data << uint32(0xa61) << uint32(0x1); // 33
8005 data << uint32(0xa60) << uint32(0x1); // 34
8006 data << uint32(0xa5f) << uint32(0x0); // 35
8007 break;
8008 case 3698: // Nagrand Arena
8009 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8010 bg->FillInitialWorldStates(data);
8011 else
8013 data << uint32(0xa0f) << uint32(0x0); // 7
8014 data << uint32(0xa10) << uint32(0x0); // 8
8015 data << uint32(0xa11) << uint32(0x0); // 9 show
8017 break;
8018 case 3702: // Blade's Edge Arena
8019 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8020 bg->FillInitialWorldStates(data);
8021 else
8023 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8024 data << uint32(0x9f1) << uint32(0x0); // 8 green
8025 data << uint32(0x9f3) << uint32(0x0); // 9 show
8027 break;
8028 case 3968: // Ruins of Lordaeron
8029 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8030 bg->FillInitialWorldStates(data);
8031 else
8033 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8034 data << uint32(0xbb9) << uint32(0x0); // 8 green
8035 data << uint32(0xbba) << uint32(0x0); // 9 show
8037 break;
8038 case 3703: // Shattrath City
8039 break;
8040 default:
8041 data << uint32(0x914) << uint32(0x0); // 7
8042 data << uint32(0x913) << uint32(0x0); // 8
8043 data << uint32(0x912) << uint32(0x0); // 9
8044 data << uint32(0x915) << uint32(0x0); // 10
8045 break;
8047 GetSession()->SendPacket(&data);
8050 uint32 Player::GetXPRestBonus(uint32 xp)
8052 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8054 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8055 rested_bonus = xp;
8057 SetRestBonus( GetRestBonus() - rested_bonus);
8059 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8060 return rested_bonus;
8063 void Player::SetBindPoint(uint64 guid)
8065 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8066 data << uint64(guid);
8067 GetSession()->SendPacket( &data );
8070 void Player::SendTalentWipeConfirm(uint64 guid)
8072 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8073 data << uint64(guid);
8074 data << uint32(resetTalentsCost());
8075 GetSession()->SendPacket( &data );
8078 void Player::SendPetSkillWipeConfirm()
8080 Pet* pet = GetPet();
8081 if(!pet)
8082 return;
8083 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8084 data << pet->GetGUID();
8085 data << uint32(pet->resetTalentsCost());
8086 GetSession()->SendPacket( &data );
8089 /*********************************************************/
8090 /*** STORAGE SYSTEM ***/
8091 /*********************************************************/
8093 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8095 assert(i < 3);
8096 if(i < 2 && item)
8098 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8099 return;
8100 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8101 if(charges == 0)
8102 return;
8103 if(charges > 1)
8104 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8105 else if(charges <= 1)
8107 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8108 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8113 void Player::SetSheath( uint32 sheathed )
8115 switch (sheathed)
8117 case SHEATH_STATE_UNARMED: // no prepared weapon
8118 SetVirtualItemSlot(0,NULL);
8119 SetVirtualItemSlot(1,NULL);
8120 SetVirtualItemSlot(2,NULL);
8121 break;
8122 case SHEATH_STATE_MELEE: // prepared melee weapon
8124 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8125 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8126 SetVirtualItemSlot(2,NULL);
8127 }; break;
8128 case SHEATH_STATE_RANGED: // prepared ranged weapon
8129 SetVirtualItemSlot(0,NULL);
8130 SetVirtualItemSlot(1,NULL);
8131 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8132 break;
8133 default:
8134 SetVirtualItemSlot(0,NULL);
8135 SetVirtualItemSlot(1,NULL);
8136 SetVirtualItemSlot(2,NULL);
8137 break;
8139 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
8142 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8144 uint8 pClass = getClass();
8146 uint8 slots[4];
8147 slots[0] = NULL_SLOT;
8148 slots[1] = NULL_SLOT;
8149 slots[2] = NULL_SLOT;
8150 slots[3] = NULL_SLOT;
8151 switch( proto->InventoryType )
8153 case INVTYPE_HEAD:
8154 slots[0] = EQUIPMENT_SLOT_HEAD;
8155 break;
8156 case INVTYPE_NECK:
8157 slots[0] = EQUIPMENT_SLOT_NECK;
8158 break;
8159 case INVTYPE_SHOULDERS:
8160 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8161 break;
8162 case INVTYPE_BODY:
8163 slots[0] = EQUIPMENT_SLOT_BODY;
8164 break;
8165 case INVTYPE_CHEST:
8166 slots[0] = EQUIPMENT_SLOT_CHEST;
8167 break;
8168 case INVTYPE_ROBE:
8169 slots[0] = EQUIPMENT_SLOT_CHEST;
8170 break;
8171 case INVTYPE_WAIST:
8172 slots[0] = EQUIPMENT_SLOT_WAIST;
8173 break;
8174 case INVTYPE_LEGS:
8175 slots[0] = EQUIPMENT_SLOT_LEGS;
8176 break;
8177 case INVTYPE_FEET:
8178 slots[0] = EQUIPMENT_SLOT_FEET;
8179 break;
8180 case INVTYPE_WRISTS:
8181 slots[0] = EQUIPMENT_SLOT_WRISTS;
8182 break;
8183 case INVTYPE_HANDS:
8184 slots[0] = EQUIPMENT_SLOT_HANDS;
8185 break;
8186 case INVTYPE_FINGER:
8187 slots[0] = EQUIPMENT_SLOT_FINGER1;
8188 slots[1] = EQUIPMENT_SLOT_FINGER2;
8189 break;
8190 case INVTYPE_TRINKET:
8191 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8192 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8193 break;
8194 case INVTYPE_CLOAK:
8195 slots[0] = EQUIPMENT_SLOT_BACK;
8196 break;
8197 case INVTYPE_WEAPON:
8199 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8201 // suggest offhand slot only if know dual wielding
8202 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8203 if(CanDualWield())
8204 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8205 break;
8207 case INVTYPE_SHIELD:
8208 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8209 break;
8210 case INVTYPE_RANGED:
8211 slots[0] = EQUIPMENT_SLOT_RANGED;
8212 break;
8213 case INVTYPE_2HWEAPON:
8214 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8215 if (CanDualWield() && CanTitanGrip())
8216 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8217 break;
8218 case INVTYPE_TABARD:
8219 slots[0] = EQUIPMENT_SLOT_TABARD;
8220 break;
8221 case INVTYPE_WEAPONMAINHAND:
8222 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8223 break;
8224 case INVTYPE_WEAPONOFFHAND:
8225 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8226 break;
8227 case INVTYPE_HOLDABLE:
8228 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8229 break;
8230 case INVTYPE_THROWN:
8231 slots[0] = EQUIPMENT_SLOT_RANGED;
8232 break;
8233 case INVTYPE_RANGEDRIGHT:
8234 slots[0] = EQUIPMENT_SLOT_RANGED;
8235 break;
8236 case INVTYPE_BAG:
8237 slots[0] = INVENTORY_SLOT_BAG_1;
8238 slots[1] = INVENTORY_SLOT_BAG_2;
8239 slots[2] = INVENTORY_SLOT_BAG_3;
8240 slots[3] = INVENTORY_SLOT_BAG_4;
8241 break;
8242 case INVTYPE_RELIC:
8244 switch(proto->SubClass)
8246 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8247 if (pClass == CLASS_PALADIN)
8248 slots[0] = EQUIPMENT_SLOT_RANGED;
8249 break;
8250 case ITEM_SUBCLASS_ARMOR_IDOL:
8251 if (pClass == CLASS_DRUID)
8252 slots[0] = EQUIPMENT_SLOT_RANGED;
8253 break;
8254 case ITEM_SUBCLASS_ARMOR_TOTEM:
8255 if (pClass == CLASS_SHAMAN)
8256 slots[0] = EQUIPMENT_SLOT_RANGED;
8257 break;
8258 case ITEM_SUBCLASS_ARMOR_MISC:
8259 if (pClass == CLASS_WARLOCK)
8260 slots[0] = EQUIPMENT_SLOT_RANGED;
8261 break;
8262 case ITEM_SUBCLASS_ARMOR_SIGIL:
8263 if (pClass == CLASS_DEATH_KNIGHT)
8264 slots[0] = EQUIPMENT_SLOT_RANGED;
8265 break;
8267 break;
8269 default :
8270 return NULL_SLOT;
8273 if( slot != NULL_SLOT )
8275 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8277 for (int i = 0; i < 4; i++)
8279 if ( slots[i] == slot )
8280 return slot;
8284 else
8286 // search free slot at first
8287 for (int i = 0; i < 4; i++)
8289 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8291 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8292 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8293 return slots[i];
8297 // if not found free and can swap return first appropriate from used
8298 for (int i = 0; i < 4; i++)
8300 if ( slots[i] != NULL_SLOT && swap )
8301 return slots[i];
8305 // no free position
8306 return NULL_SLOT;
8309 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8311 Item *pItem;
8312 uint32 tempcount = 0;
8314 uint8 res = EQUIP_ERR_OK;
8316 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8318 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8319 if( pItem && pItem->GetEntry() == item )
8321 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8322 if(ires==EQUIP_ERR_OK)
8324 tempcount += pItem->GetCount();
8325 if( tempcount >= count )
8326 return EQUIP_ERR_OK;
8328 else
8329 res = ires;
8332 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8334 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8335 if( pItem && pItem->GetEntry() == item )
8337 tempcount += pItem->GetCount();
8338 if( tempcount >= count )
8339 return EQUIP_ERR_OK;
8342 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8344 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8345 if( pItem && pItem->GetEntry() == item )
8347 tempcount += pItem->GetCount();
8348 if( tempcount >= count )
8349 return EQUIP_ERR_OK;
8352 Bag *pBag;
8353 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8355 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8356 if( pBag )
8358 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8360 pItem = GetItemByPos( i, j );
8361 if( pItem && pItem->GetEntry() == item )
8363 tempcount += pItem->GetCount();
8364 if( tempcount >= count )
8365 return EQUIP_ERR_OK;
8371 // not found req. item count and have unequippable items
8372 return res;
8375 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8377 uint32 count = 0;
8378 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8380 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8381 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8382 count += pItem->GetCount();
8384 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8386 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8387 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8388 count += pItem->GetCount();
8390 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8392 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8393 if( pBag )
8394 count += pBag->GetItemCount(item,skipItem);
8397 if(skipItem && skipItem->GetProto()->GemProperties)
8399 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8401 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8402 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8403 count += pItem->GetGemCountWithID(item);
8407 if(inBankAlso)
8409 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8411 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8412 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8413 count += pItem->GetCount();
8415 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8417 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8418 if( pBag )
8419 count += pBag->GetItemCount(item,skipItem);
8422 if(skipItem && skipItem->GetProto()->GemProperties)
8424 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8426 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8427 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8428 count += pItem->GetGemCountWithID(item);
8433 return count;
8436 Item* Player::GetItemByGuid( uint64 guid ) const
8438 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8440 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8441 if( pItem && pItem->GetGUID() == guid )
8442 return pItem;
8444 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8446 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8447 if( pItem && pItem->GetGUID() == guid )
8448 return pItem;
8451 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8453 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8454 if( pBag )
8456 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8458 Item* pItem = pBag->GetItemByPos( j );
8459 if( pItem && pItem->GetGUID() == guid )
8460 return pItem;
8464 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8466 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8467 if( pBag )
8469 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8471 Item* pItem = pBag->GetItemByPos( j );
8472 if( pItem && pItem->GetGUID() == guid )
8473 return pItem;
8478 return NULL;
8481 Item* Player::GetItemByPos( uint16 pos ) const
8483 uint8 bag = pos >> 8;
8484 uint8 slot = pos & 255;
8485 return GetItemByPos( bag, slot );
8488 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8490 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8491 return m_items[slot];
8492 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8493 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8495 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8496 if ( pBag )
8497 return pBag->GetItemByPos(slot);
8499 return NULL;
8502 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8504 uint16 slot;
8505 switch (attackType)
8507 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8508 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8509 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8510 default: return NULL;
8513 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8514 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8515 return NULL;
8517 if(!useable)
8518 return item;
8520 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8521 return NULL;
8523 return item;
8526 Item* Player::GetShield(bool useable) const
8528 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8529 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8530 return NULL;
8532 if(!useable)
8533 return item;
8535 if( item->IsBroken())
8536 return NULL;
8538 return item;
8541 uint32 Player::GetAttackBySlot( uint8 slot )
8543 switch(slot)
8545 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8546 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8547 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8548 default: return MAX_ATTACK;
8552 bool Player::HasBankBagSlot( uint8 slot ) const
8554 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8555 if( slot < maxslot )
8556 return true;
8557 return false;
8560 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8562 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8563 return true;
8564 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8565 return true;
8566 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8567 return true;
8568 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8569 return true;
8570 return false;
8573 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8575 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8576 return true;
8577 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8578 return true;
8579 return false;
8582 bool Player::IsBankPos( uint8 bag, uint8 slot )
8584 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8585 return true;
8586 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8587 return true;
8588 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8589 return true;
8590 return false;
8593 bool Player::IsBagPos( uint16 pos )
8595 uint8 bag = pos >> 8;
8596 uint8 slot = pos & 255;
8597 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8598 return true;
8599 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8600 return true;
8601 return false;
8604 bool Player::IsValidPos( uint8 bag, uint8 slot )
8606 // post selected
8607 if(bag == NULL_BAG)
8608 return true;
8610 if (bag == INVENTORY_SLOT_BAG_0)
8612 // any post selected
8613 if (slot == NULL_SLOT)
8614 return true;
8616 // equipment
8617 if (slot < EQUIPMENT_SLOT_END)
8618 return true;
8620 // bag equip slots
8621 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8622 return true;
8624 // backpack slots
8625 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8626 return true;
8628 // keyring slots
8629 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8630 return true;
8632 // bank main slots
8633 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8634 return true;
8636 // bank bag slots
8637 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8638 return true;
8640 return false;
8643 // bag content slots
8644 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8646 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8647 if(!pBag)
8648 return false;
8650 // any post selected
8651 if (slot == NULL_SLOT)
8652 return true;
8654 return slot < pBag->GetBagSize();
8657 // bank bag content slots
8658 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8660 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8661 if(!pBag)
8662 return false;
8664 // any post selected
8665 if (slot == NULL_SLOT)
8666 return true;
8668 return slot < pBag->GetBagSize();
8671 // where this?
8672 return false;
8676 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8678 uint32 tempcount = 0;
8679 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8681 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8682 if( pItem && pItem->GetEntry() == item )
8684 tempcount += pItem->GetCount();
8685 if( tempcount >= count )
8686 return true;
8689 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8691 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8692 if( pItem && pItem->GetEntry() == item )
8694 tempcount += pItem->GetCount();
8695 if( tempcount >= count )
8696 return true;
8699 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8701 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8703 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8705 Item* pItem = GetItemByPos( i, j );
8706 if( pItem && pItem->GetEntry() == item )
8708 tempcount += pItem->GetCount();
8709 if( tempcount >= count )
8710 return true;
8716 if(inBankAlso)
8718 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8720 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8721 if( pItem && pItem->GetEntry() == item )
8723 tempcount += pItem->GetCount();
8724 if( tempcount >= count )
8725 return true;
8728 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8730 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8732 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8734 Item* pItem = GetItemByPos( i, j );
8735 if( pItem && pItem->GetEntry() == item )
8737 tempcount += pItem->GetCount();
8738 if( tempcount >= count )
8739 return true;
8746 return false;
8749 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8751 Item *pItem;
8752 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8754 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8755 if( pItem && pItem->GetEntry() == item )
8756 return pItem;
8759 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8760 if (pProto && pProto->GemProperties)
8762 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8764 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8765 if( pItem && pItem->GetProto()->Socket[0].Color )
8767 if (pItem->GetGemCountWithID(item) > 0 )
8768 return pItem;
8773 return NULL;
8776 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8778 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8779 if( !pProto )
8781 if(no_space_count)
8782 *no_space_count = count;
8783 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8786 // no maximum
8787 if(pProto->MaxCount <= 0)
8788 return EQUIP_ERR_OK;
8790 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8792 if (curcount + count > uint32(pProto->MaxCount))
8794 if(no_space_count)
8795 *no_space_count = count +curcount - pProto->MaxCount;
8796 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8799 return EQUIP_ERR_OK;
8802 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8804 Item *pItem;
8805 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8807 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8808 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8809 return true;
8811 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8813 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8814 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8815 return true;
8817 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8819 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8821 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8823 pItem = GetItemByPos( i, j );
8824 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8825 return true;
8829 return false;
8832 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8834 Item* pItem2 = GetItemByPos( bag, slot );
8836 // ignore move item (this slot will be empty at move)
8837 if(pItem2==pSrcItem)
8838 pItem2 = NULL;
8840 uint32 need_space;
8842 // empty specific slot - check item fit to slot
8843 if( !pItem2 || swap )
8845 if( bag == INVENTORY_SLOT_BAG_0 )
8847 // keyring case
8848 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8849 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8851 // vanitypet case (not use, vanity pets stored as spells)
8852 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8853 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8855 // currencytoken case (disabled until proper implement)
8856 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8857 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8859 // guestbag case (disabled until proper implement)
8860 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8861 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8863 // prevent cheating
8864 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8865 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8867 else
8869 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8870 if( !pBag )
8871 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8873 ItemPrototype const* pBagProto = pBag->GetProto();
8874 if( !pBagProto )
8875 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8877 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8878 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8881 // non empty stack with space
8882 need_space = pProto->GetMaxStackSize();
8884 // non empty slot, check item type
8885 else
8887 // check item type
8888 if(pItem2->GetEntry() != pProto->ItemId)
8889 return EQUIP_ERR_ITEM_CANT_STACK;
8891 // check free space
8892 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8893 return EQUIP_ERR_ITEM_CANT_STACK;
8895 // free stack space or infinity
8896 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8899 if(need_space > count)
8900 need_space = count;
8902 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8903 if(!newPosition.isContainedIn(dest))
8905 dest.push_back(newPosition);
8906 count -= need_space;
8908 return EQUIP_ERR_OK;
8911 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
8913 // skip specific bag already processed in first called _CanStoreItem_InBag
8914 if(bag==skip_bag)
8915 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8917 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8918 if( !pBag )
8919 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8921 ItemPrototype const* pBagProto = pBag->GetProto();
8922 if( !pBagProto )
8923 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8925 // specialized bag mode or non-specilized
8926 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8927 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8929 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8930 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8932 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8934 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8935 if(j==skip_slot)
8936 continue;
8938 Item* pItem2 = GetItemByPos( bag, j );
8940 // ignore move item (this slot will be empty at move)
8941 if(pItem2==pSrcItem)
8942 pItem2 = NULL;
8944 // if merge skip empty, if !merge skip non-empty
8945 if((pItem2!=NULL)!=merge)
8946 continue;
8948 if( pItem2 )
8950 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8952 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8953 if(need_space > count)
8954 need_space = count;
8956 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8957 if(!newPosition.isContainedIn(dest))
8959 dest.push_back(newPosition);
8960 count -= need_space;
8962 if(count==0)
8963 return EQUIP_ERR_OK;
8967 else
8969 uint32 need_space = pProto->GetMaxStackSize();
8970 if(need_space > count)
8971 need_space = count;
8973 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8974 if(!newPosition.isContainedIn(dest))
8976 dest.push_back(newPosition);
8977 count -= need_space;
8979 if(count==0)
8980 return EQUIP_ERR_OK;
8984 return EQUIP_ERR_OK;
8987 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
8989 for(uint32 j = slot_begin; j < slot_end; j++)
8991 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8992 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8993 continue;
8995 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8997 // ignore move item (this slot will be empty at move)
8998 if(pItem2==pSrcItem)
8999 pItem2 = NULL;
9001 // if merge skip empty, if !merge skip non-empty
9002 if((pItem2!=NULL)!=merge)
9003 continue;
9005 if( pItem2 )
9007 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9009 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9010 if(need_space > count)
9011 need_space = count;
9012 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9013 if(!newPosition.isContainedIn(dest))
9015 dest.push_back(newPosition);
9016 count -= need_space;
9018 if(count==0)
9019 return EQUIP_ERR_OK;
9023 else
9025 uint32 need_space = pProto->GetMaxStackSize();
9026 if(need_space > count)
9027 need_space = count;
9029 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9030 if(!newPosition.isContainedIn(dest))
9032 dest.push_back(newPosition);
9033 count -= need_space;
9035 if(count==0)
9036 return EQUIP_ERR_OK;
9040 return EQUIP_ERR_OK;
9043 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9045 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9047 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9048 if( !pProto )
9050 if(no_space_count)
9051 *no_space_count = count;
9052 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9055 if(pItem && pItem->IsBindedNotWith(GetGUID()))
9057 if(no_space_count)
9058 *no_space_count = count;
9059 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9062 // check count of items (skip for auto move for same player from bank)
9063 uint32 no_similar_count = 0; // can't store this amount similar items
9064 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9065 if(res!=EQUIP_ERR_OK)
9067 if(count==no_similar_count)
9069 if(no_space_count)
9070 *no_space_count = no_similar_count;
9071 return res;
9073 count -= no_similar_count;
9076 // in specific slot
9077 if( bag != NULL_BAG && slot != NULL_SLOT )
9079 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9080 if(res!=EQUIP_ERR_OK)
9082 if(no_space_count)
9083 *no_space_count = count + no_similar_count;
9084 return res;
9087 if(count==0)
9089 if(no_similar_count==0)
9090 return EQUIP_ERR_OK;
9092 if(no_space_count)
9093 *no_space_count = count + no_similar_count;
9094 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9098 // not specific slot or have space for partly store only in specific slot
9100 // in specific bag
9101 if( bag != NULL_BAG )
9103 // search stack in bag for merge to
9104 if( pProto->Stackable != 1 )
9106 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9108 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9109 if(res!=EQUIP_ERR_OK)
9111 if(no_space_count)
9112 *no_space_count = count + no_similar_count;
9113 return res;
9116 if(count==0)
9118 if(no_similar_count==0)
9119 return EQUIP_ERR_OK;
9121 if(no_space_count)
9122 *no_space_count = count + no_similar_count;
9123 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9126 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9127 if(res!=EQUIP_ERR_OK)
9129 if(no_space_count)
9130 *no_space_count = count + no_similar_count;
9131 return res;
9134 if(count==0)
9136 if(no_similar_count==0)
9137 return EQUIP_ERR_OK;
9139 if(no_space_count)
9140 *no_space_count = count + no_similar_count;
9141 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9144 else // equipped bag
9146 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9147 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9148 if(res!=EQUIP_ERR_OK)
9149 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9151 if(res!=EQUIP_ERR_OK)
9153 if(no_space_count)
9154 *no_space_count = count + no_similar_count;
9155 return res;
9158 if(count==0)
9160 if(no_similar_count==0)
9161 return EQUIP_ERR_OK;
9163 if(no_space_count)
9164 *no_space_count = count + no_similar_count;
9165 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9170 // search free slot in bag for place to
9171 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9173 // search free slot - keyring case
9174 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9176 uint32 keyringSize = GetMaxKeyringSize();
9177 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9178 if(res!=EQUIP_ERR_OK)
9180 if(no_space_count)
9181 *no_space_count = count + no_similar_count;
9182 return res;
9185 if(count==0)
9187 if(no_similar_count==0)
9188 return EQUIP_ERR_OK;
9190 if(no_space_count)
9191 *no_space_count = count + no_similar_count;
9192 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9196 // Vanity pet case skipped as not used
9198 /* until proper implementation
9199 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9201 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9202 if(res!=EQUIP_ERR_OK)
9204 if(no_space_count)
9205 *no_space_count = count + no_similar_count;
9206 return res;
9209 if(count==0)
9211 if(no_similar_count==0)
9212 return EQUIP_ERR_OK;
9214 if(no_space_count)
9215 *no_space_count = count + no_similar_count;
9216 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9220 /* until proper implementation
9221 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9223 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9224 if(res!=EQUIP_ERR_OK)
9226 if(no_space_count)
9227 *no_space_count = count + no_similar_count;
9228 return res;
9231 if(count==0)
9233 if(no_similar_count==0)
9234 return EQUIP_ERR_OK;
9236 if(no_space_count)
9237 *no_space_count = count + no_similar_count;
9238 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9243 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9244 if(res!=EQUIP_ERR_OK)
9246 if(no_space_count)
9247 *no_space_count = count + no_similar_count;
9248 return res;
9251 if(count==0)
9253 if(no_similar_count==0)
9254 return EQUIP_ERR_OK;
9256 if(no_space_count)
9257 *no_space_count = count + no_similar_count;
9258 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9261 else // equipped bag
9263 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9264 if(res!=EQUIP_ERR_OK)
9265 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9267 if(res!=EQUIP_ERR_OK)
9269 if(no_space_count)
9270 *no_space_count = count + no_similar_count;
9271 return res;
9274 if(count==0)
9276 if(no_similar_count==0)
9277 return EQUIP_ERR_OK;
9279 if(no_space_count)
9280 *no_space_count = count + no_similar_count;
9281 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9286 // not specific bag or have space for partly store only in specific bag
9288 // search stack for merge to
9289 if( pProto->Stackable != 1 )
9291 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9292 if(res!=EQUIP_ERR_OK)
9294 if(no_space_count)
9295 *no_space_count = count + no_similar_count;
9296 return res;
9299 if(count==0)
9301 if(no_similar_count==0)
9302 return EQUIP_ERR_OK;
9304 if(no_space_count)
9305 *no_space_count = count + no_similar_count;
9306 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9309 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9310 if(res!=EQUIP_ERR_OK)
9312 if(no_space_count)
9313 *no_space_count = count + no_similar_count;
9314 return res;
9317 if(count==0)
9319 if(no_similar_count==0)
9320 return EQUIP_ERR_OK;
9322 if(no_space_count)
9323 *no_space_count = count + no_similar_count;
9324 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9327 if( pProto->BagFamily )
9329 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9331 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9332 if(res!=EQUIP_ERR_OK)
9333 continue;
9335 if(count==0)
9337 if(no_similar_count==0)
9338 return EQUIP_ERR_OK;
9340 if(no_space_count)
9341 *no_space_count = count + no_similar_count;
9342 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9347 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9349 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9350 if(res!=EQUIP_ERR_OK)
9351 continue;
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;
9365 // search free slot - special bag case
9366 if( pProto->BagFamily )
9368 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9370 uint32 keyringSize = GetMaxKeyringSize();
9371 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9372 if(res!=EQUIP_ERR_OK)
9374 if(no_space_count)
9375 *no_space_count = count + no_similar_count;
9376 return res;
9379 if(count==0)
9381 if(no_similar_count==0)
9382 return EQUIP_ERR_OK;
9384 if(no_space_count)
9385 *no_space_count = count + no_similar_count;
9386 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9390 // Vanity pet case skipped as not used
9392 /* until proper implementation
9393 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9395 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9396 if(res!=EQUIP_ERR_OK)
9398 if(no_space_count)
9399 *no_space_count = count + no_similar_count;
9400 return res;
9403 if(count==0)
9405 if(no_similar_count==0)
9406 return EQUIP_ERR_OK;
9408 if(no_space_count)
9409 *no_space_count = count + no_similar_count;
9410 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9414 /* until proper implementation
9415 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9417 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9418 if(res!=EQUIP_ERR_OK)
9420 if(no_space_count)
9421 *no_space_count = count + no_similar_count;
9422 return res;
9425 if(count==0)
9427 if(no_similar_count==0)
9428 return EQUIP_ERR_OK;
9430 if(no_space_count)
9431 *no_space_count = count + no_similar_count;
9432 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9437 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9439 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9440 if(res!=EQUIP_ERR_OK)
9441 continue;
9443 if(count==0)
9445 if(no_similar_count==0)
9446 return EQUIP_ERR_OK;
9448 if(no_space_count)
9449 *no_space_count = count + no_similar_count;
9450 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9455 // search free slot
9456 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9457 if(res!=EQUIP_ERR_OK)
9459 if(no_space_count)
9460 *no_space_count = count + no_similar_count;
9461 return res;
9464 if(count==0)
9466 if(no_similar_count==0)
9467 return EQUIP_ERR_OK;
9469 if(no_space_count)
9470 *no_space_count = count + no_similar_count;
9471 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9474 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9476 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9477 if(res!=EQUIP_ERR_OK)
9478 continue;
9480 if(count==0)
9482 if(no_similar_count==0)
9483 return EQUIP_ERR_OK;
9485 if(no_space_count)
9486 *no_space_count = count + no_similar_count;
9487 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9491 if(no_space_count)
9492 *no_space_count = count + no_similar_count;
9494 return EQUIP_ERR_INVENTORY_FULL;
9497 //////////////////////////////////////////////////////////////////////////
9498 uint8 Player::CanStoreItems( Item **pItems,int count) const
9500 Item *pItem2;
9502 // fill space table
9503 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9504 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9505 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9506 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9507 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9509 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9510 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9511 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9512 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9513 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9515 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9517 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9519 if (pItem2 && !pItem2->IsInTrade())
9521 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9525 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9527 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9529 if (pItem2 && !pItem2->IsInTrade())
9531 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9535 // Vanity pet case skipped as not used
9537 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9539 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9541 if (pItem2 && !pItem2->IsInTrade())
9543 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9547 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9549 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9551 if (pItem2 && !pItem2->IsInTrade())
9553 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9557 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9559 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9561 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9563 pItem2 = GetItemByPos( i, j );
9564 if (pItem2 && !pItem2->IsInTrade())
9566 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9572 // check free space for all items
9573 for (int k=0;k<count;k++)
9575 Item *pItem = pItems[k];
9577 // no item
9578 if (!pItem) continue;
9580 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9581 ItemPrototype const *pProto = pItem->GetProto();
9583 // strange item
9584 if( !pProto )
9585 return EQUIP_ERR_ITEM_NOT_FOUND;
9587 // item it 'bind'
9588 if(pItem->IsBindedNotWith(GetGUID()))
9589 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9591 Bag *pBag;
9592 ItemPrototype const *pBagProto;
9594 // item is 'one item only'
9595 uint8 res = CanTakeMoreSimilarItems(pItem);
9596 if(res != EQUIP_ERR_OK)
9597 return res;
9599 // search stack for merge to
9600 if( pProto->Stackable != 1 )
9602 bool b_found = false;
9604 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9606 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9607 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9609 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9610 b_found = true;
9611 break;
9614 if (b_found) continue;
9616 // Vanity pet case skipped as not used
9618 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9620 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9621 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9623 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9624 b_found = true;
9625 break;
9628 if (b_found) continue;
9630 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9632 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9633 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9635 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9636 b_found = true;
9637 break;
9640 if (b_found) continue;
9642 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9644 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9645 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9647 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9648 b_found = true;
9649 break;
9652 if (b_found) continue;
9654 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9656 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9657 if( pBag )
9659 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9661 pItem2 = GetItemByPos( t, j );
9662 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9664 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9665 b_found = true;
9666 break;
9671 if (b_found) continue;
9674 // special bag case
9675 if( pProto->BagFamily )
9677 bool b_found = false;
9678 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9680 uint32 keyringSize = GetMaxKeyringSize();
9681 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9683 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9685 inv_keys[t-KEYRING_SLOT_START] = 1;
9686 b_found = true;
9687 break;
9692 if (b_found) continue;
9694 // Vanity pet case skipped as not used
9696 /* until proper implementation
9697 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9699 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9701 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9703 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9704 b_found = true;
9705 break;
9710 if (b_found) continue;
9712 /* until proper implementation
9713 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9715 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9717 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9719 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9720 b_found = true;
9721 break;
9726 if (b_found) continue;
9729 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9731 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9732 if( pBag )
9734 pBagProto = pBag->GetProto();
9736 // not plain container check
9737 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9738 ItemCanGoIntoBag(pProto,pBagProto) )
9740 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9742 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9744 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9745 b_found = true;
9746 break;
9752 if (b_found) continue;
9755 // search free slot
9756 bool b_found = false;
9757 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9759 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9761 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9762 b_found = true;
9763 break;
9766 if (b_found) continue;
9768 // search free slot in bags
9769 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9771 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9772 if( pBag )
9774 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9776 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9778 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9779 b_found = true;
9780 break;
9786 // no free slot found?
9787 if (!b_found)
9788 return EQUIP_ERR_INVENTORY_FULL;
9791 return EQUIP_ERR_OK;
9794 //////////////////////////////////////////////////////////////////////////
9795 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9797 dest = 0;
9798 Item *pItem = Item::CreateItem( item, 1, this );
9799 if( pItem )
9801 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9802 delete pItem;
9803 return result;
9806 return EQUIP_ERR_ITEM_NOT_FOUND;
9809 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9811 dest = 0;
9812 if( pItem )
9814 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9815 ItemPrototype const *pProto = pItem->GetProto();
9816 if( pProto )
9818 // May be here should be more stronger checks; STUNNED checked
9819 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9820 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9821 return EQUIP_ERR_YOU_ARE_STUNNED;
9823 if(pItem->IsBindedNotWith(GetGUID()))
9824 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9826 // check count of items (skip for auto move for same player from bank)
9827 uint8 res = CanTakeMoreSimilarItems(pItem);
9828 if(res != EQUIP_ERR_OK)
9829 return res;
9831 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9832 // - combat
9833 // - in-progress arenas
9834 if( !pProto->CanChangeEquipStateInCombat() )
9836 if( isInCombat() )
9837 return EQUIP_ERR_NOT_IN_COMBAT;
9839 if(BattleGround* bg = GetBattleGround())
9840 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9841 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9844 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9845 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9847 if(IsNonMeleeSpellCasted(false))
9848 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9850 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9851 if( eslot == NULL_SLOT )
9852 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9854 uint8 msg = CanUseItem( pItem , not_loading );
9855 if( msg != EQUIP_ERR_OK )
9856 return msg;
9857 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9858 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9860 // check unique-equipped on item
9861 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9863 // there is an equip limit on this item
9864 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9865 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9866 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9869 // check unique-equipped on gems
9870 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9872 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9873 if(!enchant_id)
9874 continue;
9875 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9876 if(!enchantEntry)
9877 continue;
9879 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9880 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9882 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9883 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9884 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9888 // check unique-equipped special item classes
9889 if (pProto->Class == ITEM_CLASS_QUIVER)
9891 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9893 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9895 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9897 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9898 (!swap || pBag->GetSlot() != eslot ) )
9900 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9901 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9902 else
9903 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9910 uint32 type = pProto->InventoryType;
9912 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9914 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9916 if(!CanDualWield())
9917 return EQUIP_ERR_CANT_DUAL_WIELD;
9919 else if (type == INVTYPE_2HWEAPON)
9921 if(!CanDualWield() || !CanTitanGrip())
9922 return EQUIP_ERR_CANT_DUAL_WIELD;
9925 if(IsTwoHandUsed())
9926 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9929 // equip two-hand weapon case (with possible unequip 2 items)
9930 if( type == INVTYPE_2HWEAPON )
9932 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9934 if (!CanTitanGrip())
9935 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9937 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9938 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9940 if (!CanTitanGrip())
9942 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9943 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9944 ItemPosCountVec off_dest;
9945 if( offItem && (!not_loading ||
9946 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9947 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9948 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9951 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9952 return EQUIP_ERR_OK;
9955 if( !swap )
9956 return EQUIP_ERR_ITEM_NOT_FOUND;
9957 else
9958 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9961 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9963 // Applied only to equipped items and bank bags
9964 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9965 return EQUIP_ERR_OK;
9967 Item* pItem = GetItemByPos(pos);
9969 // Applied only to existed equipped item
9970 if( !pItem )
9971 return EQUIP_ERR_OK;
9973 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9975 ItemPrototype const *pProto = pItem->GetProto();
9976 if( !pProto )
9977 return EQUIP_ERR_ITEM_NOT_FOUND;
9979 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9980 // - combat
9981 // - in-progress arenas
9982 if( !pProto->CanChangeEquipStateInCombat() )
9984 if( isInCombat() )
9985 return EQUIP_ERR_NOT_IN_COMBAT;
9987 if(BattleGround* bg = GetBattleGround())
9988 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9989 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9992 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9993 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9995 return EQUIP_ERR_OK;
9998 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10000 if( !pItem )
10001 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10003 uint32 count = pItem->GetCount();
10005 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10006 ItemPrototype const *pProto = pItem->GetProto();
10007 if( !pProto )
10008 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10010 if( pItem->IsBindedNotWith(GetGUID()) )
10011 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10013 // check count of items (skip for auto move for same player from bank)
10014 uint8 res = CanTakeMoreSimilarItems(pItem);
10015 if(res != EQUIP_ERR_OK)
10016 return res;
10018 // in specific slot
10019 if( bag != NULL_BAG && slot != NULL_SLOT )
10021 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10023 if (!pItem->IsBag())
10024 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10026 Bag *pBag = (Bag*)pItem;
10027 if( !HasBankBagSlot( slot ) )
10028 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10030 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
10031 return cantuse;
10034 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10035 if(res!=EQUIP_ERR_OK)
10036 return res;
10038 if(count==0)
10039 return EQUIP_ERR_OK;
10042 // not specific slot or have space for partly store only in specific slot
10044 // in specific bag
10045 if( bag != NULL_BAG )
10047 if( pProto->InventoryType == INVTYPE_BAG )
10049 Bag *pBag = (Bag*)pItem;
10050 if( pBag && !pBag->IsEmpty() )
10051 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10054 // search stack in bag for merge to
10055 if( pProto->Stackable != 1 )
10057 if( bag == INVENTORY_SLOT_BAG_0 )
10059 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10060 if(res!=EQUIP_ERR_OK)
10061 return res;
10063 if(count==0)
10064 return EQUIP_ERR_OK;
10066 else
10068 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10069 if(res!=EQUIP_ERR_OK)
10070 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10072 if(res!=EQUIP_ERR_OK)
10073 return res;
10075 if(count==0)
10076 return EQUIP_ERR_OK;
10080 // search free slot in bag
10081 if( bag == INVENTORY_SLOT_BAG_0 )
10083 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10084 if(res!=EQUIP_ERR_OK)
10085 return res;
10087 if(count==0)
10088 return EQUIP_ERR_OK;
10090 else
10092 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10093 if(res!=EQUIP_ERR_OK)
10094 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10096 if(res!=EQUIP_ERR_OK)
10097 return res;
10099 if(count==0)
10100 return EQUIP_ERR_OK;
10104 // not specific bag or have space for partly store only in specific bag
10106 // search stack for merge to
10107 if( pProto->Stackable != 1 )
10109 // in slots
10110 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10111 if(res!=EQUIP_ERR_OK)
10112 return res;
10114 if(count==0)
10115 return EQUIP_ERR_OK;
10117 // in special bags
10118 if( pProto->BagFamily )
10120 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10122 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10123 if(res!=EQUIP_ERR_OK)
10124 continue;
10126 if(count==0)
10127 return EQUIP_ERR_OK;
10131 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10133 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10134 if(res!=EQUIP_ERR_OK)
10135 continue;
10137 if(count==0)
10138 return EQUIP_ERR_OK;
10142 // search free place in special bag
10143 if( pProto->BagFamily )
10145 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10147 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10148 if(res!=EQUIP_ERR_OK)
10149 continue;
10151 if(count==0)
10152 return EQUIP_ERR_OK;
10156 // search free space
10157 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10158 if(res!=EQUIP_ERR_OK)
10159 return res;
10161 if(count==0)
10162 return EQUIP_ERR_OK;
10164 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10166 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10167 if(res!=EQUIP_ERR_OK)
10168 continue;
10170 if(count==0)
10171 return EQUIP_ERR_OK;
10173 return EQUIP_ERR_BANK_FULL;
10176 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10178 if( pItem )
10180 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10181 if( !isAlive() && not_loading )
10182 return EQUIP_ERR_YOU_ARE_DEAD;
10183 //if( isStunned() )
10184 // return EQUIP_ERR_YOU_ARE_STUNNED;
10185 ItemPrototype const *pProto = pItem->GetProto();
10186 if( pProto )
10188 if( pItem->IsBindedNotWith(GetGUID()) )
10189 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10190 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10191 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10192 if( pItem->GetSkill() != 0 )
10194 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10195 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10197 if( pProto->RequiredSkill != 0 )
10199 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10200 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10201 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10202 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10204 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10205 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10206 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10207 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10208 if( getLevel() < pProto->RequiredLevel )
10209 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10210 return EQUIP_ERR_OK;
10213 return EQUIP_ERR_ITEM_NOT_FOUND;
10216 bool Player::CanUseItem( ItemPrototype const *pProto )
10218 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10220 if( pProto )
10222 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10223 return false;
10224 if( pProto->RequiredSkill != 0 )
10226 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10227 return false;
10228 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10229 return false;
10231 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10232 return false;
10233 if( getLevel() < pProto->RequiredLevel )
10234 return false;
10235 return true;
10237 return false;
10240 uint8 Player::CanUseAmmo( uint32 item ) const
10242 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10243 if( !isAlive() )
10244 return EQUIP_ERR_YOU_ARE_DEAD;
10245 //if( isStunned() )
10246 // return EQUIP_ERR_YOU_ARE_STUNNED;
10247 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10248 if( pProto )
10250 if( pProto->InventoryType!= INVTYPE_AMMO )
10251 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10252 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10253 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10254 if( pProto->RequiredSkill != 0 )
10256 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10257 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10258 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10259 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10261 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10262 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10263 /*if( GetReputation() < pProto->RequiredReputation )
10264 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10266 if( getLevel() < pProto->RequiredLevel )
10267 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10269 // Requires No Ammo
10270 if(GetDummyAura(46699))
10271 return EQUIP_ERR_BAG_FULL6;
10273 return EQUIP_ERR_OK;
10275 return EQUIP_ERR_ITEM_NOT_FOUND;
10278 void Player::SetAmmo( uint32 item )
10280 if(!item)
10281 return;
10283 // already set
10284 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10285 return;
10287 // check ammo
10288 if(item)
10290 uint8 msg = CanUseAmmo( item );
10291 if( msg != EQUIP_ERR_OK )
10293 SendEquipError( msg, NULL, NULL );
10294 return;
10298 SetUInt32Value(PLAYER_AMMO_ID, item);
10300 _ApplyAmmoBonuses();
10303 void Player::RemoveAmmo()
10305 SetUInt32Value(PLAYER_AMMO_ID, 0);
10307 m_ammoDPS = 0.0f;
10309 if(CanModifyStats())
10310 UpdateDamagePhysical(RANGED_ATTACK);
10313 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10314 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10316 uint32 count = 0;
10317 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10318 count += itr->count;
10320 Item *pItem = Item::CreateItem( item, count, this );
10321 if( pItem )
10323 ItemAddedQuestCheck( item, count );
10324 if(randomPropertyId)
10325 pItem->SetItemRandomProperties(randomPropertyId);
10326 pItem = StoreItem( dest, pItem, update );
10328 return pItem;
10331 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10333 if( !pItem )
10334 return NULL;
10336 Item* lastItem = pItem;
10338 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10340 uint16 pos = itr->pos;
10341 uint32 count = itr->count;
10343 ++itr;
10345 if(itr == dest.end())
10347 lastItem = _StoreItem(pos,pItem,count,false,update);
10348 break;
10351 lastItem = _StoreItem(pos,pItem,count,true,update);
10354 return lastItem;
10357 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10358 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10360 if( !pItem )
10361 return NULL;
10363 uint8 bag = pos >> 8;
10364 uint8 slot = pos & 255;
10366 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10368 Item *pItem2 = GetItemByPos( bag, slot );
10370 if( !pItem2 )
10372 if(clone)
10373 pItem = pItem->CloneItem(count,this);
10374 else
10375 pItem->SetCount(count);
10377 if(!pItem)
10378 return NULL;
10380 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10381 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10382 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10383 pItem->SetBinding( true );
10385 if( bag == INVENTORY_SLOT_BAG_0 )
10387 m_items[slot] = pItem;
10388 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10389 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10390 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10392 pItem->SetSlot( slot );
10393 pItem->SetContainer( NULL );
10395 if( IsInWorld() && update )
10397 pItem->AddToWorld();
10398 pItem->SendUpdateToPlayer( this );
10401 pItem->SetState(ITEM_CHANGED, this);
10403 else
10405 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10406 if( pBag )
10408 pBag->StoreItem( slot, pItem, update );
10409 if( IsInWorld() && update )
10411 pItem->AddToWorld();
10412 pItem->SendUpdateToPlayer( this );
10414 pItem->SetState(ITEM_CHANGED, this);
10415 pBag->SetState(ITEM_CHANGED, this);
10419 AddEnchantmentDurations(pItem);
10420 AddItemDurations(pItem);
10422 return pItem;
10424 else
10426 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10427 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10428 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10429 pItem2->SetBinding( true );
10431 pItem2->SetCount( pItem2->GetCount() + count );
10432 if( IsInWorld() && update )
10433 pItem2->SendUpdateToPlayer( this );
10435 if(!clone)
10437 // delete item (it not in any slot currently)
10438 if( IsInWorld() && update )
10440 pItem->RemoveFromWorld();
10441 pItem->DestroyForPlayer( this );
10444 RemoveEnchantmentDurations(pItem);
10445 RemoveItemDurations(pItem);
10447 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10448 pItem->SetState(ITEM_REMOVED, this);
10450 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10451 AddEnchantmentDurations(pItem2);
10453 pItem2->SetState(ITEM_CHANGED, this);
10455 return pItem2;
10459 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10461 Item *pItem = Item::CreateItem( item, 1, this );
10462 if( pItem )
10464 ItemAddedQuestCheck( item, 1 );
10465 Item * retItem = EquipItem( pos, pItem, update );
10467 return retItem;
10469 return NULL;
10472 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10474 if( pItem )
10476 AddEnchantmentDurations(pItem);
10477 AddItemDurations(pItem);
10479 uint8 bag = pos >> 8;
10480 uint8 slot = pos & 255;
10482 Item *pItem2 = GetItemByPos( bag, slot );
10484 if( !pItem2 )
10486 VisualizeItem( slot, pItem);
10488 if(isAlive())
10490 ItemPrototype const *pProto = pItem->GetProto();
10492 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10493 if(pProto && pProto->ItemSet)
10494 AddItemsSetItem(this,pItem);
10496 _ApplyItemMods(pItem, slot, true);
10498 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10500 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10502 if (getClass() == CLASS_ROGUE)
10503 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10505 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10507 if (!spellProto)
10508 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10509 else
10511 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10513 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10514 data << uint64(GetGUID());
10515 data << uint8(1);
10516 data << uint32(cooldownSpell);
10517 data << uint32(0);
10518 GetSession()->SendPacket(&data);
10523 if( IsInWorld() && update )
10525 pItem->AddToWorld();
10526 pItem->SendUpdateToPlayer( this );
10529 ApplyEquipCooldown(pItem);
10531 if( slot == EQUIPMENT_SLOT_MAINHAND )
10532 UpdateExpertise(BASE_ATTACK);
10533 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10534 UpdateExpertise(OFF_ATTACK);
10536 else
10538 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10539 if( IsInWorld() && update )
10540 pItem2->SendUpdateToPlayer( this );
10542 // delete item (it not in any slot currently)
10543 //pItem->DeleteFromDB();
10544 if( IsInWorld() && update )
10546 pItem->RemoveFromWorld();
10547 pItem->DestroyForPlayer( this );
10550 RemoveEnchantmentDurations(pItem);
10551 RemoveItemDurations(pItem);
10553 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10554 pItem->SetState(ITEM_REMOVED, this);
10555 pItem2->SetState(ITEM_CHANGED, this);
10557 ApplyEquipCooldown(pItem2);
10559 return pItem2;
10563 return pItem;
10566 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10568 if( pItem )
10570 AddEnchantmentDurations(pItem);
10571 AddItemDurations(pItem);
10573 uint8 slot = pos & 255;
10574 VisualizeItem( slot, pItem);
10576 if( IsInWorld() )
10578 pItem->AddToWorld();
10579 pItem->SendUpdateToPlayer( this );
10584 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10586 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10587 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10588 // entry // Size: 1
10589 // inspected enchantments // Size: 6
10590 // ? // Size: 5
10591 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10592 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10593 // // = 16
10595 if(pItem)
10597 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10599 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10600 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10602 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10603 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10605 // Use SetInt16Value to prevent set high part to FFFF for negative value
10606 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10607 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10609 else
10611 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10613 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10614 SetUInt32Value(VisibleBase + 0, 0);
10616 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10617 SetUInt32Value(VisibleBase + 1 + i, 0);
10619 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10620 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10624 void Player::VisualizeItem( uint8 slot, Item *pItem)
10626 if(!pItem)
10627 return;
10629 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10630 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10631 pItem->SetBinding( true );
10633 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10635 m_items[slot] = pItem;
10636 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10637 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10638 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10639 pItem->SetSlot( slot );
10640 pItem->SetContainer( NULL );
10642 if( slot < EQUIPMENT_SLOT_END )
10643 SetVisibleItemSlot(slot,pItem);
10645 pItem->SetState(ITEM_CHANGED, this);
10648 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10650 // note: removeitem does not actually change the item
10651 // it only takes the item out of storage temporarily
10652 // note2: if removeitem is to be used for delinking
10653 // the item must be removed from the player's updatequeue
10655 Item *pItem = GetItemByPos( bag, slot );
10656 if( pItem )
10658 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10660 RemoveEnchantmentDurations(pItem);
10661 RemoveItemDurations(pItem);
10663 if( bag == INVENTORY_SLOT_BAG_0 )
10665 if ( slot < INVENTORY_SLOT_BAG_END )
10667 ItemPrototype const *pProto = pItem->GetProto();
10668 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10670 if(pProto && pProto->ItemSet)
10671 RemoveItemsSetItem(this,pProto);
10673 _ApplyItemMods(pItem, slot, false);
10675 // remove item dependent auras and casts (only weapon and armor slots)
10676 if(slot < EQUIPMENT_SLOT_END)
10677 RemoveItemDependentAurasAndCasts(pItem);
10679 // remove held enchantments
10680 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10682 if (pItem->GetItemSuffixFactor())
10684 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10685 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10687 else
10689 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10690 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10695 m_items[slot] = NULL;
10696 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10698 if ( slot < EQUIPMENT_SLOT_END )
10699 SetVisibleItemSlot(slot,NULL);
10701 else
10703 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10704 if( pBag )
10705 pBag->RemoveItem(slot, update);
10707 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10708 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10709 pItem->SetSlot( NULL_SLOT );
10710 if( IsInWorld() && update )
10711 pItem->SendUpdateToPlayer( this );
10713 if( slot == EQUIPMENT_SLOT_MAINHAND )
10714 UpdateExpertise(BASE_ATTACK);
10715 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10716 UpdateExpertise(OFF_ATTACK);
10720 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10721 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10723 if(Item* it = GetItemByPos(bag,slot))
10725 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10726 RemoveItem( bag,slot,update);
10727 it->RemoveFromUpdateQueueOf(this);
10728 if(it->IsInWorld())
10730 it->RemoveFromWorld();
10731 it->DestroyForPlayer( this );
10736 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10737 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10739 // update quest counters
10740 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10742 // store item
10743 Item* pLastItem = StoreItem( dest, pItem, update);
10745 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10746 if(pLastItem==pItem)
10748 // update owner for last item (this can be original item with wrong owner
10749 if(pLastItem->GetOwnerGUID() != GetGUID())
10750 pLastItem->SetOwnerGUID(GetGUID());
10752 // if this original item then it need create record in inventory
10753 // in case trade we already have item in other player inventory
10754 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10758 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10760 Item *pItem = GetItemByPos( bag, slot );
10761 if( pItem )
10763 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10765 // start from destroy contained items (only equipped bag can have its)
10766 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10768 for (int i = 0; i < MAX_BAG_SIZE; i++)
10769 DestroyItem(slot,i,update);
10772 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10773 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10775 RemoveEnchantmentDurations(pItem);
10776 RemoveItemDurations(pItem);
10778 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10780 if( bag == INVENTORY_SLOT_BAG_0 )
10782 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10784 // equipment and equipped bags can have applied bonuses
10785 if ( slot < INVENTORY_SLOT_BAG_END )
10787 ItemPrototype const *pProto = pItem->GetProto();
10789 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10790 if(pProto && pProto->ItemSet)
10791 RemoveItemsSetItem(this,pProto);
10793 _ApplyItemMods(pItem, slot, false);
10796 if ( slot < EQUIPMENT_SLOT_END )
10798 // remove item dependent auras and casts (only weapon and armor slots)
10799 RemoveItemDependentAurasAndCasts(pItem);
10801 // equipment visual show
10802 SetVisibleItemSlot(slot,NULL);
10805 m_items[slot] = NULL;
10807 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10808 pBag->RemoveItem(slot, update);
10810 if( IsInWorld() && update )
10812 pItem->RemoveFromWorld();
10813 pItem->DestroyForPlayer(this);
10816 //pItem->SetOwnerGUID(0);
10817 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10818 pItem->SetSlot( NULL_SLOT );
10819 pItem->SetState(ITEM_REMOVED, this);
10823 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10825 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10826 Item *pItem;
10827 ItemPrototype const *pProto;
10828 uint32 remcount = 0;
10830 // in inventory
10831 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10833 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10834 if( pItem && pItem->GetEntry() == item )
10836 if( pItem->GetCount() + remcount <= count )
10838 // all items in inventory can unequipped
10839 remcount += pItem->GetCount();
10840 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10842 if(remcount >=count)
10843 return;
10845 else
10847 pProto = pItem->GetProto();
10848 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10849 pItem->SetCount( pItem->GetCount() - count + remcount );
10850 if( IsInWorld() & update )
10851 pItem->SendUpdateToPlayer( this );
10852 pItem->SetState(ITEM_CHANGED, this);
10853 return;
10857 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10859 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10860 if( pItem && pItem->GetEntry() == item )
10862 if( pItem->GetCount() + remcount <= count )
10864 // all keys can be unequipped
10865 remcount += pItem->GetCount();
10866 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10868 if(remcount >=count)
10869 return;
10871 else
10873 pProto = pItem->GetProto();
10874 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10875 pItem->SetCount( pItem->GetCount() - count + remcount );
10876 if( IsInWorld() & update )
10877 pItem->SendUpdateToPlayer( this );
10878 pItem->SetState(ITEM_CHANGED, this);
10879 return;
10884 // in inventory bags
10885 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10887 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10889 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10891 pItem = pBag->GetItemByPos(j);
10892 if( pItem && pItem->GetEntry() == item )
10894 // all items in bags can be unequipped
10895 if( pItem->GetCount() + remcount <= count )
10897 remcount += pItem->GetCount();
10898 DestroyItem( i, j, update );
10900 if(remcount >=count)
10901 return;
10903 else
10905 pProto = pItem->GetProto();
10906 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10907 pItem->SetCount( pItem->GetCount() - count + remcount );
10908 if( IsInWorld() && update )
10909 pItem->SendUpdateToPlayer( this );
10910 pItem->SetState(ITEM_CHANGED, this);
10911 return;
10918 // in equipment and bag list
10919 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10921 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10922 if( pItem && pItem->GetEntry() == item )
10924 if( pItem->GetCount() + remcount <= count )
10926 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10928 remcount += pItem->GetCount();
10929 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10931 if(remcount >=count)
10932 return;
10935 else
10937 pProto = pItem->GetProto();
10938 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10939 pItem->SetCount( pItem->GetCount() - count + remcount );
10940 if( IsInWorld() & update )
10941 pItem->SendUpdateToPlayer( this );
10942 pItem->SetState(ITEM_CHANGED, this);
10943 return;
10949 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10951 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10953 // in inventory
10954 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10956 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10957 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10958 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10960 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10962 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10963 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10964 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10967 // in inventory bags
10968 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10970 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10971 if( pBag )
10973 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10975 Item* pItem = pBag->GetItemByPos(j);
10976 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10977 DestroyItem( i, j, update);
10982 // in equipment and bag list
10983 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10985 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10986 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10987 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10991 void Player::DestroyConjuredItems( bool update )
10993 // used when entering arena
10994 // destroys all conjured items
10995 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10997 // in inventory
10998 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11000 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11001 if( pItem && pItem->GetProto() &&
11002 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11003 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11004 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11007 // in inventory bags
11008 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11010 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11011 if( pBag )
11013 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11015 Item* pItem = pBag->GetItemByPos(j);
11016 if( pItem && pItem->GetProto() &&
11017 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11018 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11019 DestroyItem( i, j, update);
11024 // in equipment and bag list
11025 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11027 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11028 if( pItem && pItem->GetProto() &&
11029 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11030 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11031 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11035 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11037 if(!pItem)
11038 return;
11040 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11042 if( pItem->GetCount() <= count )
11044 count-= pItem->GetCount();
11046 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11048 else
11050 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11051 pItem->SetCount( pItem->GetCount() - count );
11052 count = 0;
11053 if( IsInWorld() & update )
11054 pItem->SendUpdateToPlayer( this );
11055 pItem->SetState(ITEM_CHANGED, this);
11059 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11061 uint8 srcbag = src >> 8;
11062 uint8 srcslot = src & 255;
11064 uint8 dstbag = dst >> 8;
11065 uint8 dstslot = dst & 255;
11067 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11068 if( !pSrcItem )
11070 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11071 return;
11074 // not let split all items (can be only at cheating)
11075 if(pSrcItem->GetCount() == count)
11077 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11078 return;
11081 // not let split more existed items (can be only at cheating)
11082 if(pSrcItem->GetCount() < count)
11084 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11085 return;
11088 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11090 //best error message found for attempting to split while looting
11091 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11092 return;
11095 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11096 Item *pNewItem = pSrcItem->CloneItem( count, this );
11097 if( !pNewItem )
11099 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11100 return;
11103 if( IsInventoryPos( dst ) )
11105 // change item amount before check (for unique max count check)
11106 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11108 ItemPosCountVec dest;
11109 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11110 if( msg != EQUIP_ERR_OK )
11112 delete pNewItem;
11113 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11114 SendEquipError( msg, pSrcItem, NULL );
11115 return;
11118 if( IsInWorld() )
11119 pSrcItem->SendUpdateToPlayer( this );
11120 pSrcItem->SetState(ITEM_CHANGED, this);
11121 StoreItem( dest, pNewItem, true);
11123 else if( IsBankPos ( dst ) )
11125 // change item amount before check (for unique max count check)
11126 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11128 ItemPosCountVec dest;
11129 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11130 if( msg != EQUIP_ERR_OK )
11132 delete pNewItem;
11133 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11134 SendEquipError( msg, pSrcItem, NULL );
11135 return;
11138 if( IsInWorld() )
11139 pSrcItem->SendUpdateToPlayer( this );
11140 pSrcItem->SetState(ITEM_CHANGED, this);
11141 BankItem( dest, pNewItem, true);
11143 else if( IsEquipmentPos ( dst ) )
11145 // change item amount before check (for unique max count check), provide space for splitted items
11146 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11148 uint16 dest;
11149 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11150 if( msg != EQUIP_ERR_OK )
11152 delete pNewItem;
11153 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11154 SendEquipError( msg, pSrcItem, NULL );
11155 return;
11158 if( IsInWorld() )
11159 pSrcItem->SendUpdateToPlayer( this );
11160 pSrcItem->SetState(ITEM_CHANGED, this);
11161 EquipItem( dest, pNewItem, true);
11162 AutoUnequipOffhandIfNeed();
11166 void Player::SwapItem( uint16 src, uint16 dst )
11168 uint8 srcbag = src >> 8;
11169 uint8 srcslot = src & 255;
11171 uint8 dstbag = dst >> 8;
11172 uint8 dstslot = dst & 255;
11174 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11175 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11177 if( !pSrcItem )
11178 return;
11180 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11182 if(!isAlive() )
11184 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11185 return;
11188 // SRC checks
11190 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11192 //best error message found for attempting to swap while looting
11193 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11194 return;
11197 // check unequip potability for equipped items and bank bags
11198 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11200 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11201 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11202 if(msg != EQUIP_ERR_OK)
11204 SendEquipError( msg, pSrcItem, pDstItem );
11205 return;
11209 // prevent put equipped/bank bag in self
11210 if( IsBagPos ( src ) && srcslot == dstbag)
11212 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11213 return;
11216 // DST checks
11218 if (pDstItem)
11220 if(pDstItem->m_lootGenerated) // prevent swap looting item
11222 //best error message found for attempting to swap while looting
11223 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11224 return;
11227 // check unequip potability for equipped items and bank bags
11228 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11230 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11231 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11232 if(msg != EQUIP_ERR_OK)
11234 SendEquipError( msg, pSrcItem, pDstItem );
11235 return;
11240 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11241 // or swap empty bag with another empty or not empty bag (with items exchange)
11243 // Move case
11244 if( !pDstItem )
11246 if( IsInventoryPos( dst ) )
11248 ItemPosCountVec dest;
11249 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11250 if( msg != EQUIP_ERR_OK )
11252 SendEquipError( msg, pSrcItem, NULL );
11253 return;
11256 RemoveItem(srcbag, srcslot, true);
11257 StoreItem( dest, pSrcItem, true);
11259 else if( IsBankPos ( dst ) )
11261 ItemPosCountVec dest;
11262 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11263 if( msg != EQUIP_ERR_OK )
11265 SendEquipError( msg, pSrcItem, NULL );
11266 return;
11269 RemoveItem(srcbag, srcslot, true);
11270 BankItem( dest, pSrcItem, true);
11272 else if( IsEquipmentPos ( dst ) )
11274 uint16 dest;
11275 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11276 if( msg != EQUIP_ERR_OK )
11278 SendEquipError( msg, pSrcItem, NULL );
11279 return;
11282 RemoveItem(srcbag, srcslot, true);
11283 EquipItem( dest, pSrcItem, true);
11284 AutoUnequipOffhandIfNeed();
11287 return;
11290 // attempt merge to / fill target item
11291 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11293 uint8 msg;
11294 ItemPosCountVec sDest;
11295 uint16 eDest;
11296 if( IsInventoryPos( dst ) )
11297 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11298 else if( IsBankPos ( dst ) )
11299 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11300 else if( IsEquipmentPos ( dst ) )
11301 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11302 else
11303 return;
11305 // can be merge/fill
11306 if(msg == EQUIP_ERR_OK)
11308 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11310 RemoveItem(srcbag, srcslot, true);
11312 if( IsInventoryPos( dst ) )
11313 StoreItem( sDest, pSrcItem, true);
11314 else if( IsBankPos ( dst ) )
11315 BankItem( sDest, pSrcItem, true);
11316 else if( IsEquipmentPos ( dst ) )
11318 EquipItem( eDest, pSrcItem, true);
11319 AutoUnequipOffhandIfNeed();
11322 else
11324 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11325 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11326 pSrcItem->SetState(ITEM_CHANGED, this);
11327 pDstItem->SetState(ITEM_CHANGED, this);
11328 if( IsInWorld() )
11330 pSrcItem->SendUpdateToPlayer( this );
11331 pDstItem->SendUpdateToPlayer( this );
11334 return;
11338 // impossible merge/fill, do real swap
11339 uint8 msg;
11341 // check src->dest move possibility
11342 ItemPosCountVec sDest;
11343 uint16 eDest;
11344 if( IsInventoryPos( dst ) )
11345 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11346 else if( IsBankPos( dst ) )
11347 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11348 else if( IsEquipmentPos( dst ) )
11350 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11351 if( msg == EQUIP_ERR_OK )
11352 msg = CanUnequipItem( eDest, true );
11355 if( msg != EQUIP_ERR_OK )
11357 SendEquipError( msg, pSrcItem, pDstItem );
11358 return;
11361 // check dest->src move possibility
11362 ItemPosCountVec sDest2;
11363 uint16 eDest2;
11364 if( IsInventoryPos( src ) )
11365 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11366 else if( IsBankPos( src ) )
11367 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11368 else if( IsEquipmentPos( src ) )
11370 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11371 if( msg == EQUIP_ERR_OK )
11372 msg = CanUnequipItem( eDest2, true);
11375 if( msg != EQUIP_ERR_OK )
11377 SendEquipError( msg, pDstItem, pSrcItem );
11378 return;
11381 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11382 if(pSrcItem->IsBag() && pDstItem->IsBag())
11384 Bag* emptyBag = NULL;
11385 Bag* fullBag = NULL;
11386 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11388 emptyBag = (Bag*)pSrcItem;
11389 fullBag = (Bag*)pDstItem;
11391 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11393 emptyBag = (Bag*)pDstItem;
11394 fullBag = (Bag*)pSrcItem;
11397 // bag swap (with items exchange) case
11398 if(emptyBag && fullBag)
11400 ItemPrototype const* emotyProto = emptyBag->GetProto();
11402 uint32 count = 0;
11404 for(int i=0; i < fullBag->GetBagSize(); ++i)
11406 Item *bagItem = fullBag->GetItemByPos(i);
11407 if (!bagItem)
11408 continue;
11410 ItemPrototype const* bagItemProto = bagItem->GetProto();
11411 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11413 // one from items not go to empry target bag
11414 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11415 return;
11418 ++count;
11422 if (count > emptyBag->GetBagSize())
11424 // too small targeted bag
11425 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11426 return;
11429 // Items swap
11430 count = 0; // will pos in new bag
11431 for(int i=0; i< fullBag->GetBagSize(); ++i)
11433 Item *bagItem = fullBag->GetItemByPos(i);
11434 if (!bagItem)
11435 continue;
11437 fullBag->RemoveItem(i, true);
11438 emptyBag->StoreItem(count, bagItem, true);
11439 bagItem->SetState(ITEM_CHANGED, this);
11441 ++count;
11446 // now do moves, remove...
11447 RemoveItem(dstbag, dstslot, false);
11448 RemoveItem(srcbag, srcslot, false);
11450 // add to dest
11451 if( IsInventoryPos( dst ) )
11452 StoreItem(sDest, pSrcItem, true);
11453 else if( IsBankPos( dst ) )
11454 BankItem(sDest, pSrcItem, true);
11455 else if( IsEquipmentPos( dst ) )
11456 EquipItem(eDest, pSrcItem, true);
11458 // add to src
11459 if( IsInventoryPos( src ) )
11460 StoreItem(sDest2, pDstItem, true);
11461 else if( IsBankPos( src ) )
11462 BankItem(sDest2, pDstItem, true);
11463 else if( IsEquipmentPos( src ) )
11464 EquipItem(eDest2, pDstItem, true);
11466 AutoUnequipOffhandIfNeed();
11469 void Player::AddItemToBuyBackSlot( Item *pItem )
11471 if( pItem )
11473 uint32 slot = m_currentBuybackSlot;
11474 // if current back slot non-empty search oldest or free
11475 if(m_items[slot])
11477 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11478 uint32 oldest_slot = BUYBACK_SLOT_START;
11480 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11482 // found empty
11483 if(!m_items[i])
11485 slot = i;
11486 break;
11489 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11491 if(oldest_time > i_time)
11493 oldest_time = i_time;
11494 oldest_slot = i;
11498 // find oldest
11499 slot = oldest_slot;
11502 RemoveItemFromBuyBackSlot( slot, true );
11503 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11505 m_items[slot] = pItem;
11506 time_t base = time(NULL);
11507 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11508 uint32 eslot = slot - BUYBACK_SLOT_START;
11510 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11511 ItemPrototype const *pProto = pItem->GetProto();
11512 if( pProto )
11513 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11514 else
11515 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11516 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11518 // move to next (for non filled list is move most optimized choice)
11519 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11520 ++m_currentBuybackSlot;
11524 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11526 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11527 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11528 return m_items[slot];
11529 return NULL;
11532 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11534 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11535 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11537 Item *pItem = m_items[slot];
11538 if( pItem )
11540 pItem->RemoveFromWorld();
11541 if(del) pItem->SetState(ITEM_REMOVED, this);
11544 m_items[slot] = NULL;
11546 uint32 eslot = slot - BUYBACK_SLOT_START;
11547 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11548 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11549 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11551 // if current backslot is filled set to now free slot
11552 if(m_items[m_currentBuybackSlot])
11553 m_currentBuybackSlot = slot;
11557 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11559 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11560 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11561 data << uint8(msg);
11563 if(msg)
11565 data << uint64(pItem ? pItem->GetGUID() : 0);
11566 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11567 data << uint8(0); // not 0 there...
11569 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11571 uint32 level = 0;
11573 if(pItem)
11574 if(ItemPrototype const* proto = pItem->GetProto())
11575 level = proto->RequiredLevel;
11577 data << uint32(level); // new 2.4.0
11580 GetSession()->SendPacket(&data);
11583 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11585 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11586 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11587 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11588 data << uint32(item);
11589 if( param > 0 )
11590 data << uint32(param);
11591 data << uint8(msg);
11592 GetSession()->SendPacket(&data);
11595 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11597 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11598 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11599 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11600 data << uint64(guid);
11601 if( param > 0 )
11602 data << uint32(param);
11603 data << uint8(msg);
11604 GetSession()->SendPacket(&data);
11607 void Player::ClearTrade()
11609 tradeGold = 0;
11610 acceptTrade = false;
11611 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11612 tradeItems[i] = NULL_SLOT;
11615 void Player::TradeCancel(bool sendback)
11617 if(pTrader)
11619 // send yellow "Trade canceled" message to both traders
11620 WorldSession* ws;
11621 ws = GetSession();
11622 if(sendback)
11623 ws->SendCancelTrade();
11624 ws = pTrader->GetSession();
11625 if(!ws->PlayerLogout())
11626 ws->SendCancelTrade();
11628 // cleanup
11629 ClearTrade();
11630 pTrader->ClearTrade();
11631 // prevent loss of reference
11632 pTrader->pTrader = NULL;
11633 pTrader = NULL;
11637 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11639 if(m_itemDuration.empty())
11640 return;
11642 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11644 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11646 Item* item = *itr;
11647 ++itr; // current element can be erased in UpdateDuration
11649 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11650 item->UpdateDuration(this,time);
11654 void Player::UpdateEnchantTime(uint32 time)
11656 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11658 assert(itr->item);
11659 next=itr;
11660 if(!itr->item->GetEnchantmentId(itr->slot))
11662 next = m_enchantDuration.erase(itr);
11664 else if(itr->leftduration <= time)
11666 ApplyEnchantment(itr->item,itr->slot,false,false);
11667 itr->item->ClearEnchantment(itr->slot);
11668 next = m_enchantDuration.erase(itr);
11670 else if(itr->leftduration > time)
11672 itr->leftduration -= time;
11673 ++next;
11678 void Player::AddEnchantmentDurations(Item *item)
11680 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11682 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11683 continue;
11685 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11686 if( duration > 0 )
11687 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11691 void Player::RemoveEnchantmentDurations(Item *item)
11693 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11695 if(itr->item == item)
11697 // save duration in item
11698 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11699 itr = m_enchantDuration.erase(itr);
11701 else
11702 ++itr;
11706 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11708 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11709 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11711 next = itr;
11712 if(itr->slot==slot)
11714 if(itr->item && itr->item->GetEnchantmentId(slot))
11716 // remove from stats
11717 ApplyEnchantment(itr->item,slot,false,false);
11718 // remove visual
11719 itr->item->ClearEnchantment(slot);
11721 // remove from update list
11722 next = m_enchantDuration.erase(itr);
11724 else
11725 ++next;
11728 // remove enchants from inventory items
11729 // NOTE: no need to remove these from stats, since these aren't equipped
11730 // in inventory
11731 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11733 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11734 if( pItem && pItem->GetEnchantmentId(slot) )
11735 pItem->ClearEnchantment(slot);
11738 // in inventory bags
11739 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11741 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11742 if( pBag )
11744 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11746 Item* pItem = pBag->GetItemByPos(j);
11747 if( pItem && pItem->GetEnchantmentId(slot) )
11748 pItem->ClearEnchantment(slot);
11754 // duration == 0 will remove item enchant
11755 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11757 if(!item)
11758 return;
11760 if(slot >= MAX_ENCHANTMENT_SLOT)
11761 return;
11763 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11765 if(itr->item == item && itr->slot == slot)
11767 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11768 m_enchantDuration.erase(itr);
11769 break;
11772 if(item && duration > 0 )
11774 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11775 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11779 void Player::ApplyEnchantment(Item *item,bool apply)
11781 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11782 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11785 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11787 if(!item)
11788 return;
11790 if(!item->IsEquipped())
11791 return;
11793 if(slot >= MAX_ENCHANTMENT_SLOT)
11794 return;
11796 uint32 enchant_id = item->GetEnchantmentId(slot);
11797 if(!enchant_id)
11798 return;
11800 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11801 if(!pEnchant)
11802 return;
11804 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11805 return;
11807 for (int s=0; s<3; s++)
11809 uint32 enchant_display_type = pEnchant->type[s];
11810 uint32 enchant_amount = pEnchant->amount[s];
11811 uint32 enchant_spell_id = pEnchant->spellid[s];
11813 switch(enchant_display_type)
11815 case ITEM_ENCHANTMENT_TYPE_NONE:
11816 break;
11817 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11818 // processed in Player::CastItemCombatSpell
11819 break;
11820 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11821 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11822 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11823 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11824 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11825 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11826 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11827 break;
11828 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11829 if(enchant_spell_id)
11831 if(apply)
11833 int32 basepoints = 0;
11834 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11835 if (item->GetItemRandomPropertyId())
11837 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11838 if (item_rand)
11840 // Search enchant_amount
11841 for (int k=0; k<3; k++)
11843 if(item_rand->enchant_id[k] == enchant_id)
11845 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11846 break;
11851 // Cast custom spell vs all equal basepoints getted from enchant_amount
11852 if (basepoints)
11853 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11854 else
11855 CastSpell(this,enchant_spell_id,true,item);
11857 else
11858 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11860 break;
11861 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11862 if (!enchant_amount)
11864 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11865 if(item_rand)
11867 for (int k=0; k<3; k++)
11869 if(item_rand->enchant_id[k] == enchant_id)
11871 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11872 break;
11878 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11879 break;
11880 case ITEM_ENCHANTMENT_TYPE_STAT:
11882 if (!enchant_amount)
11884 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11885 if(item_rand_suffix)
11887 for (int k=0; k<3; k++)
11889 if(item_rand_suffix->enchant_id[k] == enchant_id)
11891 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11892 break;
11898 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11899 switch (enchant_spell_id)
11901 case ITEM_MOD_AGILITY:
11902 sLog.outDebug("+ %u AGILITY",enchant_amount);
11903 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11904 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11905 break;
11906 case ITEM_MOD_STRENGTH:
11907 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11908 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11909 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11910 break;
11911 case ITEM_MOD_INTELLECT:
11912 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11913 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11914 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11915 break;
11916 case ITEM_MOD_SPIRIT:
11917 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11918 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11919 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11920 break;
11921 case ITEM_MOD_STAMINA:
11922 sLog.outDebug("+ %u STAMINA",enchant_amount);
11923 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11924 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11925 break;
11926 case ITEM_MOD_DEFENSE_SKILL_RATING:
11927 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11928 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11929 break;
11930 case ITEM_MOD_DODGE_RATING:
11931 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11932 sLog.outDebug("+ %u DODGE", enchant_amount);
11933 break;
11934 case ITEM_MOD_PARRY_RATING:
11935 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11936 sLog.outDebug("+ %u PARRY", enchant_amount);
11937 break;
11938 case ITEM_MOD_BLOCK_RATING:
11939 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11940 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11941 break;
11942 case ITEM_MOD_HIT_MELEE_RATING:
11943 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11944 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11945 break;
11946 case ITEM_MOD_HIT_RANGED_RATING:
11947 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11948 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11949 break;
11950 case ITEM_MOD_HIT_SPELL_RATING:
11951 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11952 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11953 break;
11954 case ITEM_MOD_CRIT_MELEE_RATING:
11955 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11956 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11957 break;
11958 case ITEM_MOD_CRIT_RANGED_RATING:
11959 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11960 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11961 break;
11962 case ITEM_MOD_CRIT_SPELL_RATING:
11963 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11964 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11965 break;
11966 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11967 // in Enchantments
11968 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11969 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11970 // break;
11971 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11972 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11973 // break;
11974 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11975 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11976 // break;
11977 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11978 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11979 // break;
11980 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11981 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11982 // break;
11983 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11984 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11985 // break;
11986 // case ITEM_MOD_HASTE_MELEE_RATING:
11987 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11988 // break;
11989 // case ITEM_MOD_HASTE_RANGED_RATING:
11990 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11991 // break;
11992 case ITEM_MOD_HASTE_SPELL_RATING:
11993 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11994 break;
11995 case ITEM_MOD_HIT_RATING:
11996 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11997 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11998 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11999 sLog.outDebug("+ %u HIT", enchant_amount);
12000 break;
12001 case ITEM_MOD_CRIT_RATING:
12002 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12003 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12004 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12005 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12006 break;
12007 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12008 // case ITEM_MOD_HIT_TAKEN_RATING:
12009 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12010 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12011 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12012 // break;
12013 // case ITEM_MOD_CRIT_TAKEN_RATING:
12014 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12015 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12016 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12017 // break;
12018 case ITEM_MOD_RESILIENCE_RATING:
12019 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12020 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12021 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12022 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12023 break;
12024 case ITEM_MOD_HASTE_RATING:
12025 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12026 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12027 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12028 sLog.outDebug("+ %u HASTE", enchant_amount);
12029 break;
12030 case ITEM_MOD_EXPERTISE_RATING:
12031 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12032 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12033 break;
12034 case ITEM_MOD_ATTACK_POWER:
12035 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12036 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12037 break;
12038 case ITEM_MOD_RANGED_ATTACK_POWER:
12039 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12040 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12041 break;
12042 case ITEM_MOD_FERAL_ATTACK_POWER:
12043 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12044 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12045 break;
12046 case ITEM_MOD_SPELL_HEALING_DONE:
12047 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12048 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
12049 break;
12050 case ITEM_MOD_SPELL_DAMAGE_DONE:
12051 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12052 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
12053 break;
12054 case ITEM_MOD_MANA_REGENERATION:
12055 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12056 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12057 break;
12058 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12059 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12060 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12061 break;
12062 case ITEM_MOD_SPELL_POWER:
12063 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12064 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12065 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12066 break;
12067 default:
12068 break;
12070 break;
12072 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12074 if(getClass() == CLASS_SHAMAN)
12076 float addValue = 0.0f;
12077 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12079 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12080 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12082 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12084 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12085 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12088 break;
12090 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12091 // processed in Player::CastItemUseSpell
12092 break;
12093 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12094 // nothing do..
12095 break;
12096 default:
12097 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12098 break;
12099 } /*switch(enchant_display_type)*/
12100 } /*for*/
12102 // visualize enchantment at player and equipped items
12103 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
12105 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
12106 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
12109 if(apply_dur)
12111 if(apply)
12113 // set duration
12114 uint32 duration = item->GetEnchantmentDuration(slot);
12115 if(duration > 0)
12116 AddEnchantmentDuration(item,slot,duration);
12118 else
12120 // duration == 0 will remove EnchantDuration
12121 AddEnchantmentDuration(item,slot,0);
12126 void Player::SendEnchantmentDurations()
12128 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
12130 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
12134 void Player::SendItemDurations()
12136 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
12138 (*itr)->SendTimeUpdate(this);
12142 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12144 if(!item) // prevent crash
12145 return;
12147 // last check 2.0.10
12148 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12149 data << GetGUID(); // player GUID
12150 data << uint32(received); // 0=looted, 1=from npc
12151 data << uint32(created); // 0=received, 1=created
12152 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12153 data << (uint8)item->GetBagSlot(); // bagslot
12154 // item slot, but when added to stack: 0xFFFFFFFF
12155 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
12156 data << uint32(item->GetEntry()); // item id
12157 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12158 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12159 data << uint32(count); // count of items
12160 data << GetItemCount(item->GetEntry()); // count of items in inventory
12162 if (broadcast && GetGroup())
12163 GetGroup()->BroadcastPacket(&data);
12164 else
12165 GetSession()->SendPacket(&data);
12168 /*********************************************************/
12169 /*** QUEST SYSTEM ***/
12170 /*********************************************************/
12172 void Player::PrepareQuestMenu( uint64 guid )
12174 Object *pObject;
12175 QuestRelations* pObjectQR;
12176 QuestRelations* pObjectQIR;
12177 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12178 if( pCreature )
12180 pObject = (Object*)pCreature;
12181 pObjectQR = &objmgr.mCreatureQuestRelations;
12182 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12184 else
12186 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12187 if( pGameObject )
12189 pObject = (Object*)pGameObject;
12190 pObjectQR = &objmgr.mGOQuestRelations;
12191 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12193 else
12194 return;
12197 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12198 qm.ClearMenu();
12200 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12202 uint32 quest_id = i->second;
12203 QuestStatus status = GetQuestStatus( quest_id );
12204 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12205 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12206 else if ( status == QUEST_STATUS_INCOMPLETE )
12207 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12208 else if (status == QUEST_STATUS_AVAILABLE )
12209 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12212 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12214 uint32 quest_id = i->second;
12215 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12216 if(!pQuest) continue;
12218 QuestStatus status = GetQuestStatus( quest_id );
12220 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12221 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12222 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12223 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12227 void Player::SendPreparedQuest( uint64 guid )
12229 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12230 if( questMenu.Empty() )
12231 return;
12233 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12235 uint32 status = qmi0.m_qIcon;
12237 // single element case
12238 if ( questMenu.MenuItemCount() == 1 )
12240 // Auto open -- maybe also should verify there is no greeting
12241 uint32 quest_id = qmi0.m_qId;
12242 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12243 if ( pQuest )
12245 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12246 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12247 else if( status == DIALOG_STATUS_INCOMPLETE )
12248 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12249 // Send completable on repeatable quest if player don't have quest
12250 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12251 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12252 else
12253 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12256 // multiply entries
12257 else
12259 QEmote qe;
12260 qe._Delay = 0;
12261 qe._Emote = 0;
12262 std::string title = "";
12263 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12264 if( pCreature )
12266 uint32 textid = pCreature->GetNpcTextId();
12267 GossipText * gossiptext = objmgr.GetGossipText(textid);
12268 if( !gossiptext )
12270 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12271 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12272 title = "";
12274 else
12276 qe = gossiptext->Options[0].Emotes[0];
12278 if(!gossiptext->Options[0].Text_0.empty())
12280 title = gossiptext->Options[0].Text_0;
12282 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12283 if (loc_idx >= 0)
12285 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12286 if (nl)
12288 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12289 title = nl->Text_0[0][loc_idx];
12293 else
12295 title = gossiptext->Options[0].Text_1;
12297 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12298 if (loc_idx >= 0)
12300 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12301 if (nl)
12303 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12304 title = nl->Text_1[0][loc_idx];
12310 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12314 bool Player::IsActiveQuest( uint32 quest_id ) const
12316 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12318 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12321 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12323 Object *pObject;
12324 QuestRelations* pObjectQR;
12325 QuestRelations* pObjectQIR;
12327 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12328 if( pCreature )
12330 pObject = (Object*)pCreature;
12331 pObjectQR = &objmgr.mCreatureQuestRelations;
12332 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12334 else
12336 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12337 if( pGameObject )
12339 pObject = (Object*)pGameObject;
12340 pObjectQR = &objmgr.mGOQuestRelations;
12341 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12343 else
12344 return NULL;
12347 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12348 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12350 if (itr->second == nextQuestID)
12351 return objmgr.GetQuestTemplate(nextQuestID);
12354 return NULL;
12357 bool Player::CanSeeStartQuest( Quest const *pQuest )
12359 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12360 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12361 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12362 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12364 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12367 return false;
12370 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12372 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12373 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12374 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12375 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12376 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12377 && SatisfyQuestDay( pQuest, msg );
12380 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12382 if( !SatisfyQuestLog( msg ) )
12383 return false;
12385 uint32 srcitem = pQuest->GetSrcItemId();
12386 if( srcitem > 0 )
12388 uint32 count = pQuest->GetSrcItemCount();
12389 ItemPosCountVec dest;
12390 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12392 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12393 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12394 return true;
12395 else if( msg != EQUIP_ERR_OK )
12397 SendEquipError( msg, NULL, NULL );
12398 return false;
12401 return true;
12404 bool Player::CanCompleteQuest( uint32 quest_id )
12406 if( quest_id )
12408 QuestStatusData& q_status = mQuestStatus[quest_id];
12409 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12410 return false; // not allow re-complete quest
12412 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12414 if(!qInfo)
12415 return false;
12417 // auto complete quest
12418 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12419 return true;
12421 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12424 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12426 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12428 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12429 return false;
12433 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12435 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12437 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12438 continue;
12440 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12441 return false;
12445 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12446 return false;
12448 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12449 return false;
12451 if ( qInfo->GetRewOrReqMoney() < 0 )
12453 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12454 return false;
12457 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12458 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12459 return false;
12461 return true;
12464 return false;
12467 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12469 // Solve problem that player don't have the quest and try complete it.
12470 // if repeatable she must be able to complete event if player don't have it.
12471 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12472 if( !CanTakeQuest(pQuest, false) )
12473 return false;
12475 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12476 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12477 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12478 return false;
12480 if( !CanRewardQuest(pQuest, false) )
12481 return false;
12483 return true;
12486 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12488 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12489 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12490 return false;
12492 // daily quest can't be rewarded (25 daily quest already completed)
12493 if(!SatisfyQuestDay(pQuest,true))
12494 return false;
12496 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12497 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12498 return false;
12500 // prevent receive reward with quest items in bank
12501 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12503 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12505 if( pQuest->ReqItemCount[i]!= 0 &&
12506 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12508 if(msg)
12509 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12510 return false;
12515 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12516 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12517 return false;
12519 return true;
12522 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12524 // prevent receive reward with quest items in bank or for not completed quest
12525 if(!CanRewardQuest(pQuest,msg))
12526 return false;
12528 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12530 if( pQuest->RewChoiceItemId[reward] )
12532 ItemPosCountVec dest;
12533 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12534 if( res != EQUIP_ERR_OK )
12536 SendEquipError( res, NULL, NULL );
12537 return false;
12542 if ( pQuest->GetRewItemsCount() > 0 )
12544 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12546 if( pQuest->RewItemId[i] )
12548 ItemPosCountVec dest;
12549 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12550 if( res != EQUIP_ERR_OK )
12552 SendEquipError( res, NULL, NULL );
12553 return false;
12559 return true;
12562 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12564 uint16 log_slot = FindQuestSlot( 0 );
12565 assert(log_slot < MAX_QUEST_LOG_SIZE);
12567 uint32 quest_id = pQuest->GetQuestId();
12569 // if not exist then created with set uState==NEW and rewarded=false
12570 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12572 // check for repeatable quests status reset
12573 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12574 questStatusData.m_explored = false;
12576 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12578 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12579 questStatusData.m_itemcount[i] = 0;
12582 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12584 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12585 questStatusData.m_creatureOrGOcount[i] = 0;
12588 GiveQuestSourceItem( pQuest );
12589 AdjustQuestReqItemCount( pQuest, questStatusData );
12591 if( pQuest->GetRepObjectiveFaction() )
12592 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12594 uint32 qtime = 0;
12595 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12597 uint32 limittime = pQuest->GetLimitTime();
12599 // shared timed quest
12600 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12601 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12603 AddTimedQuest( quest_id );
12604 questStatusData.m_timer = limittime * 1000;
12605 qtime = static_cast<uint32>(time(NULL)) + limittime;
12607 else
12608 questStatusData.m_timer = 0;
12610 SetQuestSlot(log_slot, quest_id, qtime);
12612 if (questStatusData.uState != QUEST_NEW)
12613 questStatusData.uState = QUEST_CHANGED;
12615 //starting initial quest script
12616 if(questGiver && pQuest->GetQuestStartScript()!=0)
12617 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12619 UpdateForQuestsGO();
12622 void Player::CompleteQuest( uint32 quest_id )
12624 if( quest_id )
12626 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12628 uint16 log_slot = FindQuestSlot( quest_id );
12629 if( log_slot < MAX_QUEST_LOG_SIZE)
12630 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12632 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12634 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12635 RewardQuest(qInfo,0,this,false);
12636 else
12637 SendQuestComplete( quest_id );
12642 void Player::IncompleteQuest( uint32 quest_id )
12644 if( quest_id )
12646 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12648 uint16 log_slot = FindQuestSlot( quest_id );
12649 if( log_slot < MAX_QUEST_LOG_SIZE)
12650 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12654 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12656 uint32 quest_id = pQuest->GetQuestId();
12658 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12660 if ( pQuest->ReqItemId[i] )
12661 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12664 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12665 // SetTimedQuest( 0 );
12666 m_timedquests.erase(pQuest->GetQuestId());
12668 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12670 if( pQuest->RewChoiceItemId[reward] )
12672 ItemPosCountVec dest;
12673 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12675 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12676 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12681 if ( pQuest->GetRewItemsCount() > 0 )
12683 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12685 if( pQuest->RewItemId[i] )
12687 ItemPosCountVec dest;
12688 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12690 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12691 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12697 RewardReputation( pQuest );
12699 if( pQuest->GetRewSpellCast() > 0 )
12700 CastSpell( this, pQuest->GetRewSpellCast(), true);
12701 else if( pQuest->GetRewSpell() > 0)
12702 CastSpell( this, pQuest->GetRewSpell(), true);
12704 uint16 log_slot = FindQuestSlot( quest_id );
12705 if( log_slot < MAX_QUEST_LOG_SIZE)
12706 SetQuestSlot(log_slot,0);
12708 QuestStatusData& q_status = mQuestStatus[quest_id];
12710 // Not give XP in case already completed once repeatable quest
12711 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12713 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12714 GiveXP( XP , NULL );
12715 else
12716 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12718 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12719 ModifyMoney( pQuest->GetRewOrReqMoney() );
12721 // honor reward
12722 if(pQuest->GetRewHonorableKills())
12723 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12725 // title reward
12726 if(pQuest->GetCharTitleId())
12728 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12729 SetTitle(titleEntry);
12732 if(pQuest->GetBonusTalents())
12734 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12735 InitTalentForLevel();
12738 // Send reward mail
12739 if(pQuest->GetRewMailTemplateId())
12741 MailMessageType mailType;
12742 uint32 senderGuidOrEntry;
12743 switch(questGiver->GetTypeId())
12745 case TYPEID_UNIT:
12746 mailType = MAIL_CREATURE;
12747 senderGuidOrEntry = questGiver->GetEntry();
12748 break;
12749 case TYPEID_GAMEOBJECT:
12750 mailType = MAIL_GAMEOBJECT;
12751 senderGuidOrEntry = questGiver->GetEntry();
12752 break;
12753 case TYPEID_ITEM:
12754 mailType = MAIL_ITEM;
12755 senderGuidOrEntry = questGiver->GetEntry();
12756 break;
12757 case TYPEID_PLAYER:
12758 mailType = MAIL_NORMAL;
12759 senderGuidOrEntry = questGiver->GetGUIDLow();
12760 break;
12761 default:
12762 mailType = MAIL_NORMAL;
12763 senderGuidOrEntry = GetGUIDLow();
12764 break;
12767 Loot questMailLoot;
12769 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12771 // fill mail
12772 MailItemsInfo mi; // item list preparing
12774 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12775 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12777 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12779 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12781 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12782 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12787 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12790 if(pQuest->IsDaily())
12792 SetDailyQuestStatus(quest_id);
12793 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12796 if ( !pQuest->IsRepeatable() )
12797 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12798 else
12799 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12801 q_status.m_rewarded = true;
12803 if(announce)
12804 SendQuestReward( pQuest, XP, questGiver );
12806 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12807 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12808 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12811 void Player::FailQuest( uint32 quest_id )
12813 if( quest_id )
12815 IncompleteQuest( quest_id );
12817 uint16 log_slot = FindQuestSlot( quest_id );
12818 if( log_slot < MAX_QUEST_LOG_SIZE)
12820 SetQuestSlotTimer(log_slot, 1 );
12821 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12823 SendQuestFailed( quest_id );
12827 void Player::FailTimedQuest( uint32 quest_id )
12829 if( quest_id )
12831 QuestStatusData& q_status = mQuestStatus[quest_id];
12833 q_status.m_timer = 0;
12834 if (q_status.uState != QUEST_NEW)
12835 q_status.uState = QUEST_CHANGED;
12837 IncompleteQuest( quest_id );
12839 uint16 log_slot = FindQuestSlot( quest_id );
12840 if( log_slot < MAX_QUEST_LOG_SIZE)
12842 SetQuestSlotTimer(log_slot, 1 );
12843 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12845 SendQuestTimerFailed( quest_id );
12849 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12851 int32 zoneOrSort = qInfo->GetZoneOrSort();
12852 int32 skillOrClass = qInfo->GetSkillOrClass();
12854 // skip zone zoneOrSort and 0 case skillOrClass
12855 if( zoneOrSort >= 0 && skillOrClass == 0 )
12856 return true;
12858 int32 questSort = -zoneOrSort;
12859 uint8 reqSortClass = ClassByQuestSort(questSort);
12861 // check class sort cases in zoneOrSort
12862 if( reqSortClass != 0 && getClass() != reqSortClass)
12864 if( msg )
12865 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12866 return false;
12869 // check class
12870 if( skillOrClass < 0 )
12872 uint8 reqClass = -int32(skillOrClass);
12873 if(getClass() != reqClass)
12875 if( msg )
12876 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12877 return false;
12880 // check skill
12881 else if( skillOrClass > 0 )
12883 uint32 reqSkill = skillOrClass;
12884 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12886 if( msg )
12887 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12888 return false;
12892 return true;
12895 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12897 if( getLevel() < qInfo->GetMinLevel() )
12899 if( msg )
12900 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12901 return false;
12903 return true;
12906 bool Player::SatisfyQuestLog( bool msg )
12908 // exist free slot
12909 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12910 return true;
12912 if( msg )
12914 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12915 GetSession()->SendPacket( &data );
12916 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12918 return false;
12921 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12923 // No previous quest (might be first quest in a series)
12924 if( qInfo->prevQuests.empty())
12925 return true;
12927 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12929 uint32 prevId = abs(*iter);
12931 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12932 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12934 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12936 // If any of the positive previous quests completed, return true
12937 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12939 // skip one-from-all exclusive group
12940 if(qPrevInfo->GetExclusiveGroup() >= 0)
12941 return true;
12943 // each-from-all exclusive group ( < 0)
12944 // can be start if only all quests in prev quest exclusive group completed and rewarded
12945 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12946 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12948 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12950 for(; iter != end; ++iter)
12952 uint32 exclude_Id = iter->second;
12954 // skip checked quest id, only state of other quests in group is interesting
12955 if(exclude_Id == prevId)
12956 continue;
12958 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12960 // alternative quest from group also must be completed and rewarded(reported)
12961 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12963 if( msg )
12964 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12965 return false;
12968 return true;
12970 // If any of the negative previous quests active, return true
12971 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12972 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
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 active
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 active
12996 if( i_exstatus == mQuestStatus.end() ||
12997 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12998 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13000 if( msg )
13001 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13002 return false;
13005 return true;
13010 // Has only positive prev. quests in non-rewarded state
13011 // and negative prev. quests in non-active state
13012 if( msg )
13013 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13015 return false;
13018 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13020 uint32 reqraces = qInfo->GetRequiredRaces();
13021 if ( reqraces == 0 )
13022 return true;
13023 if( (reqraces & getRaceMask()) == 0 )
13025 if( msg )
13026 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13027 return false;
13029 return true;
13032 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13034 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13035 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13037 if( msg )
13038 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13039 return false;
13042 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13043 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13045 if( msg )
13046 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13047 return false;
13050 return true;
13053 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13055 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13056 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13058 if( msg )
13059 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13060 return false;
13062 return true;
13065 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13067 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13069 if( msg )
13070 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13071 return false;
13073 return true;
13076 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13078 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13079 if(qInfo->GetExclusiveGroup() <= 0)
13080 return true;
13082 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13083 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13085 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13087 for(; iter != end; ++iter)
13089 uint32 exclude_Id = iter->second;
13091 // skip checked quest id, only state of other quests in group is interesting
13092 if(exclude_Id == qInfo->GetQuestId())
13093 continue;
13095 // not allow have daily quest if daily quest from exclusive group already recently completed
13096 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13097 if( !SatisfyQuestDay(Nquest, false) )
13099 if( msg )
13100 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13101 return false;
13104 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13106 // alternative quest already started or completed
13107 if( i_exstatus != mQuestStatus.end()
13108 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13110 if( msg )
13111 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13112 return false;
13115 return true;
13118 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13120 if(!qInfo->GetNextQuestInChain())
13121 return true;
13123 // next quest in chain already started or completed
13124 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13125 if( itr != mQuestStatus.end()
13126 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13128 if( msg )
13129 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13130 return false;
13133 // check for all quests further up the chain
13134 // only necessary if there are quest chains with more than one quest that can be skipped
13135 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13136 return true;
13139 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13141 // No previous quest in chain
13142 if( qInfo->prevChainQuests.empty())
13143 return true;
13145 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13147 uint32 prevId = *iter;
13149 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13151 if( i_prevstatus != mQuestStatus.end() )
13153 // If any of the previous quests in chain active, return false
13154 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13155 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13157 if( msg )
13158 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13159 return false;
13163 // check for all quests further down the chain
13164 // only necessary if there are quest chains with more than one quest that can be skipped
13165 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13166 // return false;
13169 // No previous quest in chain active
13170 return true;
13173 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13175 if(!qInfo->IsDaily())
13176 return true;
13178 bool have_slot = false;
13179 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13181 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13182 if(qInfo->GetQuestId()==id)
13183 return false;
13185 if(!id)
13186 have_slot = true;
13189 if(!have_slot)
13191 if( msg )
13192 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13193 return false;
13196 return true;
13199 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13201 uint32 srcitem = pQuest->GetSrcItemId();
13202 if( srcitem > 0 )
13204 uint32 count = pQuest->GetSrcItemCount();
13205 if( count <= 0 )
13206 count = 1;
13208 ItemPosCountVec dest;
13209 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13210 if( msg == EQUIP_ERR_OK )
13212 Item * item = StoreNewItem(dest, srcitem, true);
13213 SendNewItem(item, count, true, false);
13214 return true;
13216 // player already have max amount required item, just report success
13217 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13218 return true;
13219 else
13220 SendEquipError( msg, NULL, NULL );
13221 return false;
13224 return true;
13227 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13229 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13230 if( qInfo )
13232 uint32 srcitem = qInfo->GetSrcItemId();
13233 if( srcitem > 0 )
13235 uint32 count = qInfo->GetSrcItemCount();
13236 if( count <= 0 )
13237 count = 1;
13239 // exist one case when destroy source quest item not possible:
13240 // non un-equippable item (equipped non-empty bag, for example)
13241 uint8 res = CanUnequipItems(srcitem,count);
13242 if(res != EQUIP_ERR_OK)
13244 if(msg)
13245 SendEquipError( res, NULL, NULL );
13246 return false;
13249 DestroyItemCount(srcitem, count, true, true);
13252 return true;
13255 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13257 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13258 if( qInfo )
13260 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13261 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13262 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13263 && !qInfo->IsRepeatable() )
13264 return itr->second.m_rewarded;
13266 return false;
13268 return false;
13271 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13273 if( quest_id )
13275 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13276 if( itr != mQuestStatus.end() )
13277 return itr->second.m_status;
13279 return QUEST_STATUS_NONE;
13282 bool Player::CanShareQuest(uint32 quest_id) const
13284 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13285 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13287 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13288 if( itr != mQuestStatus.end() )
13289 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13291 return false;
13294 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13296 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13297 if( qInfo )
13299 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13301 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13302 m_timedquests.erase(qInfo->GetQuestId());
13305 QuestStatusData& q_status = mQuestStatus[quest_id];
13307 q_status.m_status = status;
13308 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13311 UpdateForQuestsGO();
13314 // not used in MaNGOS, but used in scripting code
13315 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13317 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13318 if( !qInfo )
13319 return 0;
13321 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13322 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13323 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13325 return 0;
13328 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13330 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13332 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13334 uint32 reqitemcount = pQuest->ReqItemCount[i];
13335 if( reqitemcount != 0 )
13337 uint32 quest_id = pQuest->GetQuestId();
13338 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13340 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13341 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13347 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13349 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13350 if ( GetQuestSlotQuestId(i) == quest_id )
13351 return i;
13353 return MAX_QUEST_LOG_SIZE;
13356 void Player::AreaExploredOrEventHappens( uint32 questId )
13358 if( questId )
13360 uint16 log_slot = FindQuestSlot( questId );
13361 if( log_slot < MAX_QUEST_LOG_SIZE)
13363 QuestStatusData& q_status = mQuestStatus[questId];
13365 if(!q_status.m_explored)
13367 q_status.m_explored = true;
13368 if (q_status.uState != QUEST_NEW)
13369 q_status.uState = QUEST_CHANGED;
13372 if( CanCompleteQuest( questId ) )
13373 CompleteQuest( questId );
13377 //not used in mangosd, function for external script library
13378 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13380 if( Group *pGroup = GetGroup() )
13382 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13384 Player *pGroupGuy = itr->getSource();
13386 // for any leave or dead (with not released body) group member at appropriate distance
13387 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13388 pGroupGuy->AreaExploredOrEventHappens(questId);
13391 else
13392 AreaExploredOrEventHappens(questId);
13395 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13397 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13399 uint32 questid = GetQuestSlotQuestId(i);
13400 if ( questid == 0 )
13401 continue;
13403 QuestStatusData& q_status = mQuestStatus[questid];
13405 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13406 continue;
13408 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13409 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13410 continue;
13412 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13414 uint32 reqitem = qInfo->ReqItemId[j];
13415 if ( reqitem == entry )
13417 uint32 reqitemcount = qInfo->ReqItemCount[j];
13418 uint32 curitemcount = q_status.m_itemcount[j];
13419 if ( curitemcount < reqitemcount )
13421 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13422 q_status.m_itemcount[j] += additemcount;
13423 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13425 SendQuestUpdateAddItem( qInfo, j, additemcount );
13427 if ( CanCompleteQuest( questid ) )
13428 CompleteQuest( questid );
13429 return;
13433 UpdateForQuestsGO();
13434 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13437 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13439 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13441 uint32 questid = GetQuestSlotQuestId(i);
13442 if(!questid)
13443 continue;
13444 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13445 if ( !qInfo )
13446 continue;
13447 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13448 continue;
13450 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13452 uint32 reqitem = qInfo->ReqItemId[j];
13453 if ( reqitem == entry )
13455 QuestStatusData& q_status = mQuestStatus[questid];
13457 uint32 reqitemcount = qInfo->ReqItemCount[j];
13458 uint32 curitemcount;
13459 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13460 curitemcount = q_status.m_itemcount[j];
13461 else
13462 curitemcount = GetItemCount(entry,true);
13463 if ( curitemcount < reqitemcount + count )
13465 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13466 q_status.m_itemcount[j] = curitemcount - remitemcount;
13467 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13469 IncompleteQuest( questid );
13471 return;
13475 UpdateForQuestsGO();
13478 void Player::KilledMonster( uint32 entry, uint64 guid )
13480 uint32 addkillcount = 1;
13481 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13482 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13484 uint32 questid = GetQuestSlotQuestId(i);
13485 if(!questid)
13486 continue;
13488 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13489 if( !qInfo )
13490 continue;
13491 // just if !ingroup || !noraidgroup || raidgroup
13492 QuestStatusData& q_status = mQuestStatus[questid];
13493 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13495 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13497 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13499 // skip GO activate objective or none
13500 if(qInfo->ReqCreatureOrGOId[j] <=0)
13501 continue;
13503 // skip Cast at creature objective
13504 if(qInfo->ReqSpell[j] !=0 )
13505 continue;
13507 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13509 if ( reqkill == entry )
13511 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13512 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13513 if ( curkillcount < reqkillcount )
13515 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13516 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13518 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13520 if ( CanCompleteQuest( questid ) )
13521 CompleteQuest( questid );
13523 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13524 continue;
13532 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13534 bool isCreature = IS_CREATURE_GUID(guid);
13536 uint32 addCastCount = 1;
13537 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13539 uint32 questid = GetQuestSlotQuestId(i);
13540 if(!questid)
13541 continue;
13543 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13544 if ( !qInfo )
13545 continue;
13547 QuestStatusData& q_status = mQuestStatus[questid];
13549 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13551 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13553 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13555 // skip kill creature objective (0) or wrong spell casts
13556 if(qInfo->ReqSpell[j] != spell_id )
13557 continue;
13559 uint32 reqTarget = 0;
13561 if(isCreature)
13563 // creature activate objectives
13564 if(qInfo->ReqCreatureOrGOId[j] > 0)
13565 // checked at quest_template loading
13566 reqTarget = qInfo->ReqCreatureOrGOId[j];
13568 else
13570 // GO activate objective
13571 if(qInfo->ReqCreatureOrGOId[j] < 0)
13572 // checked at quest_template loading
13573 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13576 // other not this creature/GO related objectives
13577 if( reqTarget != entry )
13578 continue;
13580 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13581 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13582 if ( curCastCount < reqCastCount )
13584 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13585 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13587 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13590 if ( CanCompleteQuest( questid ) )
13591 CompleteQuest( questid );
13593 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13594 break;
13601 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13603 uint32 addTalkCount = 1;
13604 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13606 uint32 questid = GetQuestSlotQuestId(i);
13607 if(!questid)
13608 continue;
13610 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13611 if ( !qInfo )
13612 continue;
13614 QuestStatusData& q_status = mQuestStatus[questid];
13616 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13618 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13620 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13622 // skip spell casts and Gameobject objectives
13623 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13624 continue;
13626 uint32 reqTarget = 0;
13628 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13629 // checked at quest_template loading
13630 reqTarget = qInfo->ReqCreatureOrGOId[j];
13631 else
13632 continue;
13634 if ( reqTarget == entry )
13636 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13637 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13638 if ( curTalkCount < reqTalkCount )
13640 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13641 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13643 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13645 if ( CanCompleteQuest( questid ) )
13646 CompleteQuest( questid );
13648 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13649 continue;
13657 void Player::MoneyChanged( uint32 count )
13659 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13661 uint32 questid = GetQuestSlotQuestId(i);
13662 if (!questid)
13663 continue;
13665 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13666 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13668 QuestStatusData& q_status = mQuestStatus[questid];
13670 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13672 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13674 if ( CanCompleteQuest( questid ) )
13675 CompleteQuest( questid );
13678 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13680 if(int32(count) < -qInfo->GetRewOrReqMoney())
13681 IncompleteQuest( questid );
13687 bool Player::HasQuestForItem( uint32 itemid ) const
13689 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13691 QuestStatusData const& q_status = i->second;
13693 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13695 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13696 if(!qinfo)
13697 continue;
13699 // hide quest if player is in raid-group and quest is no raid quest
13700 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13701 continue;
13703 // There should be no mixed ReqItem/ReqSource drop
13704 // This part for ReqItem drop
13705 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13707 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13708 return true;
13710 // This part - for ReqSource
13711 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13713 // examined item is a source item
13714 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13716 uint32 idx = qinfo->ReqSourceRef[j]-1;
13718 // total count of created ReqItems and SourceItems is less than ReqItemCount
13719 if(qinfo->ReqItemId[idx] != 0 &&
13720 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13721 return true;
13723 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13724 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13726 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13727 return true;
13729 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13730 else if(qinfo->ReqSpell[idx] != 0)
13732 // not casted and need more reagents/item for use.
13733 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13734 return true;
13740 return false;
13743 void Player::SendQuestComplete( uint32 quest_id )
13745 if( quest_id )
13747 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13748 data << uint32(quest_id);
13749 GetSession()->SendPacket( &data );
13750 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13754 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13756 uint32 questid = pQuest->GetQuestId();
13757 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13758 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13759 data << uint32(questid);
13761 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13763 data << uint32(XP);
13764 data << uint32(pQuest->GetRewOrReqMoney());
13766 else
13768 data << uint32(0);
13769 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13772 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13773 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13774 GetSession()->SendPacket( &data );
13776 if (pQuest->GetQuestCompleteScript() != 0)
13777 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13780 void Player::SendQuestFailed( uint32 quest_id )
13782 if( quest_id )
13784 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13785 data << quest_id;
13786 data << uint32(0); // failed reason (4 for inventory is full)
13787 GetSession()->SendPacket( &data );
13788 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13792 void Player::SendQuestTimerFailed( uint32 quest_id )
13794 if( quest_id )
13796 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13797 data << quest_id;
13798 GetSession()->SendPacket( &data );
13799 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13803 void Player::SendCanTakeQuestResponse( uint32 msg )
13805 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13806 data << uint32(msg);
13807 GetSession()->SendPacket( &data );
13808 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13811 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13813 if( pPlayer )
13815 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13816 data << uint64(pPlayer->GetGUID());
13817 data << uint8(msg); // valid values: 0-8
13818 GetSession()->SendPacket( &data );
13819 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13823 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13825 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13826 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13827 //data << pQuest->ReqItemId[item_idx];
13828 //data << count;
13829 GetSession()->SendPacket( &data );
13832 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13834 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13836 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13837 if (entry < 0)
13838 // client expected gameobject template id in form (id|0x80000000)
13839 entry = (-entry) | 0x80000000;
13841 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13842 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13843 data << uint32(pQuest->GetQuestId());
13844 data << uint32(entry);
13845 data << uint32(old_count + add_count);
13846 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13847 data << uint64(guid);
13848 GetSession()->SendPacket(&data);
13850 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13851 if( log_slot < MAX_QUEST_LOG_SIZE)
13852 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13855 /*********************************************************/
13856 /*** LOAD SYSTEM ***/
13857 /*********************************************************/
13859 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13861 bool delete_result = true;
13862 if(!result)
13864 // 0 1 2 3 4 5 6 7 8 9
13865 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13866 if(!result) return false;
13868 else delete_result = false;
13870 Field *fields = result->Fetch();
13872 if(!LoadValues( fields[1].GetString()))
13874 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13875 if(delete_result) delete result;
13876 return false;
13879 // overwrite possible wrong/corrupted guid
13880 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13882 m_name = fields[2].GetCppString();
13884 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13885 SetMapId(fields[6].GetUInt32());
13886 // the instance id is not needed at character enum
13888 m_Played_time[0] = fields[7].GetUInt32();
13889 m_Played_time[1] = fields[8].GetUInt32();
13891 m_atLoginFlags = fields[9].GetUInt32();
13893 // I don't see these used anywhere ..
13894 /*_LoadGroup();
13896 _LoadBoundInstances();*/
13898 if (delete_result) delete result;
13900 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13901 m_items[i] = NULL;
13903 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13904 m_deathState = DEAD;
13906 return true;
13909 void Player::_LoadDeclinedNames(QueryResult* result)
13911 if(!result)
13912 return;
13914 if(m_declinedname)
13915 delete m_declinedname;
13917 m_declinedname = new DeclinedName;
13918 Field *fields = result->Fetch();
13919 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13920 m_declinedname->name[i] = fields[i].GetCppString();
13922 delete result;
13925 void Player::_LoadArenaTeamInfo(QueryResult *result)
13927 // arenateamid, played_week, played_season, personal_rating
13928 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13929 if (!result)
13930 return;
13934 Field *fields = result->Fetch();
13936 uint32 arenateamid = fields[0].GetUInt32();
13937 uint32 played_week = fields[1].GetUInt32();
13938 uint32 played_season = fields[2].GetUInt32();
13939 uint32 personal_rating = fields[3].GetUInt32();
13941 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13942 if(!aTeam)
13944 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13945 continue;
13947 uint8 arenaSlot = aTeam->GetSlot();
13949 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13950 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13951 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13952 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13953 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13954 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13956 }while (result->NextRow());
13957 delete result;
13960 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13962 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13963 if(!result)
13964 return false;
13966 Field *fields = result->Fetch();
13968 x = fields[0].GetFloat();
13969 y = fields[1].GetFloat();
13970 z = fields[2].GetFloat();
13971 o = fields[3].GetFloat();
13972 mapid = fields[4].GetUInt32();
13973 in_flight = !fields[5].GetCppString().empty();
13975 delete result;
13976 return true;
13979 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13981 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13982 if( !result )
13983 return false;
13985 Field *fields = result->Fetch();
13987 data = StrSplit(fields[0].GetCppString(), " ");
13989 delete result;
13991 return true;
13994 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13996 if(index >= data.size())
13997 return 0;
13999 return (uint32)atoi(data[index].c_str());
14002 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14004 float result;
14005 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14006 memcpy(&result, &temp, sizeof(result));
14008 return result;
14011 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14013 Tokens data;
14014 if(!LoadValuesArrayFromDB(data,guid))
14015 return 0;
14017 return GetUInt32ValueFromArray(data,index);
14020 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14022 float result;
14023 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14024 memcpy(&result, &temp, sizeof(result));
14026 return result;
14029 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14031 //// 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
14032 //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);
14033 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14035 if(!result)
14037 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14038 return false;
14041 Field *fields = result->Fetch();
14043 uint32 dbAccountId = fields[1].GetUInt32();
14045 // check if the character's account in the db and the logged in account match.
14046 // player should be able to load/delete character only with correct account!
14047 if( dbAccountId != GetSession()->GetAccountId() )
14049 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14050 delete result;
14051 return false;
14054 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14056 m_name = fields[3].GetCppString();
14058 // check name limitations
14059 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14061 delete result;
14062 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14063 return false;
14066 if(!LoadValues( fields[2].GetString()))
14068 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
14069 delete result;
14070 return false;
14073 // overwrite possible wrong/corrupted guid
14074 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14076 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14077 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14079 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
14080 SetVisibleItemSlot(slot,NULL);
14082 if (m_items[slot])
14084 delete m_items[slot];
14085 m_items[slot] = NULL;
14089 // update money limits
14090 if(GetMoney() > MAX_MONEY_AMOUNT)
14091 SetMoney(MAX_MONEY_AMOUNT);
14093 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14094 outDebugValues();
14096 m_race = fields[4].GetUInt8();
14097 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14098 //Other way is to saves m_team into characters table.
14099 setFactionForRace(m_race);
14100 SetCharm(0);
14102 m_class = fields[5].GetUInt8();
14104 // load home bind and check in same time class/race pair, it used later for restore broken positions
14105 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14106 return false;
14108 InitPrimaryProffesions(); // to max set before any spell loaded
14110 // init saved position, and fix it later if problematic
14111 uint32 transGUID = fields[24].GetUInt32();
14112 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
14113 SetMapId(fields[9].GetUInt32());
14114 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
14116 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14118 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14120 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
14121 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14122 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14124 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14126 // check arena teams integrity
14127 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14129 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14130 if(!arena_team_id)
14131 continue;
14133 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14134 if(at->HaveMember(GetGUID()))
14135 continue;
14137 // arena team not exist or not member, cleanup fields
14138 for(int j =0; j < 6; ++j)
14139 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14142 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14144 if(!IsPositionValid())
14146 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());
14147 RelocateToHomebind();
14149 transGUID = 0;
14151 m_movementInfo.t_x = 0.0f;
14152 m_movementInfo.t_y = 0.0f;
14153 m_movementInfo.t_z = 0.0f;
14154 m_movementInfo.t_o = 0.0f;
14157 uint32 bgid = fields[34].GetUInt32();
14158 uint32 bgteam = fields[35].GetUInt32();
14160 if(bgid) //saved in BattleGround
14162 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14164 // check entry point and fix to homebind if need
14165 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14166 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14167 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14169 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid);
14171 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14173 uint32 bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14174 uint32 queueSlot = AddBattleGroundQueueId(bgQueueTypeId);
14176 SetBattleGroundId(currentBg->GetInstanceID());
14177 SetBGTeam(bgteam);
14179 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14181 else
14183 Relocate(GetBattleGroundEntryPoint());
14184 //RemoveArenaAuras(true);
14187 else
14189 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14190 // if server restart after player save in BG or area
14191 // player can have current coordinates in to BG/Arean map, fix this
14192 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14194 // return to BG master
14195 SetMapId(fields[36].GetUInt32());
14196 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14198 // check entry point and fix to homebind if need
14199 mapEntry = sMapStore.LookupEntry(GetMapId());
14200 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14201 RelocateToHomebind();
14205 if (transGUID != 0)
14207 m_movementInfo.t_x = fields[20].GetFloat();
14208 m_movementInfo.t_y = fields[21].GetFloat();
14209 m_movementInfo.t_z = fields[22].GetFloat();
14210 m_movementInfo.t_o = fields[23].GetFloat();
14212 if( !MaNGOS::IsValidMapCoord(
14213 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14214 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14215 // transport size limited
14216 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14218 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14219 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14220 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14222 RelocateToHomebind();
14224 m_movementInfo.t_x = 0.0f;
14225 m_movementInfo.t_y = 0.0f;
14226 m_movementInfo.t_z = 0.0f;
14227 m_movementInfo.t_o = 0.0f;
14229 transGUID = 0;
14233 if (transGUID != 0)
14235 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14237 if( (*iter)->GetGUIDLow() == transGUID)
14239 m_transport = *iter;
14240 m_transport->AddPassenger(this);
14241 SetMapId(m_transport->GetMapId());
14242 break;
14246 if(!m_transport)
14248 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14249 guid,transGUID);
14251 RelocateToHomebind();
14253 m_movementInfo.t_x = 0.0f;
14254 m_movementInfo.t_y = 0.0f;
14255 m_movementInfo.t_z = 0.0f;
14256 m_movementInfo.t_o = 0.0f;
14258 transGUID = 0;
14262 // NOW player must have valid map
14263 // load the player's map here if it's not already loaded
14264 Map *map = GetMap();
14266 // since the player may not be bound to the map yet, make sure subsequent
14267 // getmap calls won't create new maps
14268 SetInstanceId(map->GetInstanceId());
14270 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14271 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14273 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14274 if(at)
14275 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14276 else
14277 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());
14280 SaveRecallPosition();
14282 time_t now = time(NULL);
14283 time_t logoutTime = time_t(fields[16].GetUInt64());
14285 // since last logout (in seconds)
14286 uint64 time_diff = uint64(now - logoutTime);
14288 // set value, including drunk invisibility detection
14289 // calculate sobering. after 15 minutes logged out, the player will be sober again
14290 float soberFactor;
14291 if(time_diff > 15*MINUTE)
14292 soberFactor = 0;
14293 else
14294 soberFactor = 1-time_diff/(15.0f*MINUTE);
14295 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14296 SetDrunkValue(newDrunkenValue);
14298 m_rest_bonus = fields[15].GetFloat();
14299 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14300 float bubble0 = 0.031;
14301 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14302 float bubble1 = 0.125;
14304 if((int32)fields[16].GetUInt32() > 0)
14306 float bubble = fields[17].GetUInt32() > 0
14307 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14308 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14310 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14313 m_cinematic = fields[12].GetUInt32();
14314 m_Played_time[0]= fields[13].GetUInt32();
14315 m_Played_time[1]= fields[14].GetUInt32();
14317 m_resetTalentsCost = fields[18].GetUInt32();
14318 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14320 // reserve some flags
14321 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14323 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14324 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14326 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14328 uint32 extraflags = fields[25].GetUInt32();
14330 m_stableSlots = fields[26].GetUInt32();
14331 if(m_stableSlots > 4)
14333 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14334 m_stableSlots = 4;
14337 m_atLoginFlags = fields[27].GetUInt32();
14339 // Honor system
14340 // Update Honor kills data
14341 m_lastHonorUpdateTime = logoutTime;
14342 UpdateHonorFields();
14344 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14345 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14346 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14348 std::string taxi_nodes = fields[31].GetCppString();
14350 delete result;
14352 // clear channel spell data (if saved at channel spell casting)
14353 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14354 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14356 // clear charm/summon related fields
14357 SetCharm(NULL);
14358 SetPet(NULL);
14359 SetCharmerGUID(0);
14360 SetOwnerGUID(0);
14361 SetCreatorGUID(0);
14363 // reset some aura modifiers before aura apply
14364 SetFarSightGUID(0);
14365 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14366 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14368 _LoadSkills();
14370 // make sure the unit is considered out of combat for proper loading
14371 ClearInCombat();
14373 // make sure the unit is considered not in duel for proper loading
14374 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14375 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14377 // remember loaded power/health values to restore after stats initialization and modifier applying
14378 uint32 savedHealth = GetHealth();
14379 uint32 savedPower[MAX_POWERS];
14380 for(uint32 i = 0; i < MAX_POWERS; ++i)
14381 savedPower[i] = GetPower(Powers(i));
14383 // reset stats before loading any modifiers
14384 InitStatsForLevel();
14385 InitTaxiNodesForLevel();
14386 InitGlyphsForLevel();
14387 InitRunes();
14389 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14391 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14392 //_LoadMail();
14394 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14395 _LoadGlyphAuras();
14397 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14398 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14399 m_deathState = DEAD;
14401 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14403 // after spell load, learn rewarded spell if need also
14404 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14405 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14407 // after spell and quest load
14408 InitTalentForLevel();
14409 learnDefaultSpells();
14411 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14413 // must be before inventory (some items required reputation check)
14414 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14416 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14418 // update items with duration and realtime
14419 UpdateItemDuration(time_diff, true);
14421 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14423 // unread mails and next delivery time, actual mails not loaded
14424 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14426 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14428 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14429 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14430 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14432 if(!HasTitle(curTitle))
14433 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14436 // Not finish taxi flight path
14437 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14439 // problems with taxi path loading
14440 TaxiNodesEntry const* nodeEntry = NULL;
14441 if(uint32 node_id = m_taxi.GetTaxiSource())
14442 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14444 if(!nodeEntry) // don't know taxi start node, to homebind
14446 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14447 RelocateToHomebind();
14448 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14450 else // have start node, to it
14452 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14453 SetMapId(nodeEntry->map_id);
14454 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14455 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14457 m_taxi.ClearTaxiDestinations();
14459 else if(uint32 node_id = m_taxi.GetTaxiSource())
14461 // save source node as recall coord to prevent recall and fall from sky
14462 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14463 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14464 m_recallMap = nodeEntry->map_id;
14465 m_recallX = nodeEntry->x;
14466 m_recallY = nodeEntry->y;
14467 m_recallZ = nodeEntry->z;
14469 // flight will started later
14472 // has to be called after last Relocate() in Player::LoadFromDB
14473 SetFallInformation(0, GetPositionZ());
14475 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14477 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14478 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14479 if(!isAlive())
14480 RemoveAllAurasOnDeath();
14482 //apply all stat bonuses from items and auras
14483 SetCanModifyStats(true);
14484 UpdateAllStats();
14486 // restore remembered power/health values (but not more max values)
14487 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14488 for(uint32 i = 0; i < MAX_POWERS; ++i)
14489 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14491 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14492 outDebugValues();
14494 // GM state
14495 if(GetSession()->GetSecurity() > SEC_PLAYER)
14497 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14499 default:
14500 case 0: break; // disable
14501 case 1: SetGameMaster(true); break; // enable
14502 case 2: // save state
14503 if(extraflags & PLAYER_EXTRA_GM_ON)
14504 SetGameMaster(true);
14505 break;
14508 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14510 default:
14511 case 0: SetGMVisible(false); break; // invisible
14512 case 1: break; // visible
14513 case 2: // save state
14514 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14515 SetGMVisible(false);
14516 break;
14519 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14521 default:
14522 case 0: break; // disable
14523 case 1: SetAcceptTicket(true); break; // enable
14524 case 2: // save state
14525 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14526 SetAcceptTicket(true);
14527 break;
14530 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14532 default:
14533 case 0: break; // disable
14534 case 1: SetGMChat(true); break; // enable
14535 case 2: // save state
14536 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14537 SetGMChat(true);
14538 break;
14541 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14543 default:
14544 case 0: break; // disable
14545 case 1: SetAcceptWhispers(true); break; // enable
14546 case 2: // save state
14547 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14548 SetAcceptWhispers(true);
14549 break;
14553 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14555 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14556 m_achievementMgr.CheckAllAchievementCriteria();
14557 return true;
14560 bool Player::isAllowedToLoot(Creature* creature)
14562 if(Player* recipient = creature->GetLootRecipient())
14564 if (recipient == this)
14565 return true;
14566 if( Group* otherGroup = recipient->GetGroup())
14568 Group* thisGroup = GetGroup();
14569 if(!thisGroup)
14570 return false;
14571 return thisGroup == otherGroup;
14573 return false;
14575 else
14576 // prevent other players from looting if the recipient got disconnected
14577 return !creature->hasLootRecipient();
14580 void Player::_LoadActions(QueryResult *result)
14582 m_actionButtons.clear();
14584 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14586 if(result)
14590 Field *fields = result->Fetch();
14592 uint8 button = fields[0].GetUInt8();
14594 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14596 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14598 while( result->NextRow() );
14600 delete result;
14604 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14606 m_Auras.clear();
14607 for (int i = 0; i < TOTAL_AURAS; i++)
14608 m_modAuras[i].clear();
14610 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14612 if(result)
14616 Field *fields = result->Fetch();
14617 uint64 caster_guid = fields[0].GetUInt64();
14618 uint32 spellid = fields[1].GetUInt32();
14619 uint32 effindex = fields[2].GetUInt32();
14620 uint32 stackcount = fields[3].GetUInt32();
14621 int32 damage = (int32)fields[4].GetUInt32();
14622 int32 maxduration = (int32)fields[5].GetUInt32();
14623 int32 remaintime = (int32)fields[6].GetUInt32();
14624 int32 remaincharges = (int32)fields[7].GetUInt32();
14626 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14627 if(!spellproto)
14629 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14630 continue;
14633 if(effindex >= 3)
14635 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14636 continue;
14639 // negative effects should continue counting down after logout
14640 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14642 if(remaintime <= int32(timediff))
14643 continue;
14645 remaintime -= timediff;
14648 // prevent wrong values of remaincharges
14649 if(spellproto->procCharges)
14651 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14652 remaincharges = spellproto->procCharges;
14654 else
14655 remaincharges = 0;
14657 //do not load single target auras (unless they were cast by the player)
14658 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14659 continue;
14661 for(uint32 i=0; i<stackcount; i++)
14663 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14664 if(!damage)
14665 damage = aura->GetModifier()->m_amount;
14666 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14667 AddAura(aura);
14668 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14671 while( result->NextRow() );
14673 delete result;
14676 if(m_class == CLASS_WARRIOR)
14677 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14680 void Player::_LoadGlyphAuras()
14682 for (uint8 i = 0; i <= MAX_GLYPH_SLOT_INDEX; ++i)
14684 if (uint32 glyph = GetGlyph(i))
14686 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14688 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14690 if(gp->TypeFlags == gs->TypeFlags)
14692 CastSpell(this, gp->SpellId, true);
14693 continue;
14695 else
14696 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14698 else
14699 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14701 else
14702 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14704 // On any error remove glyph
14705 SetGlyph(i, 0);
14710 void Player::LoadCorpse()
14712 if( isAlive() )
14714 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14716 else
14718 if(Corpse *corpse = GetCorpse())
14720 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14722 else
14724 //Prevent Dead Player login without corpse
14725 ResurrectPlayer(0.5f);
14730 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14732 //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());
14733 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14734 //NOTE: the "order by `bag`" is important because it makes sure
14735 //the bagMap is filled before items in the bags are loaded
14736 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14737 //expected to be equipped before offhand items (TODO: fixme)
14739 uint32 zone = GetZoneId();
14741 if (result)
14743 std::list<Item*> problematicItems;
14745 // prevent items from being added to the queue when stored
14746 m_itemUpdateQueueBlocked = true;
14749 Field *fields = result->Fetch();
14750 uint32 bag_guid = fields[1].GetUInt32();
14751 uint8 slot = fields[2].GetUInt8();
14752 uint32 item_guid = fields[3].GetUInt32();
14753 uint32 item_id = fields[4].GetUInt32();
14755 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14757 if(!proto)
14759 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14760 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14761 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14762 continue;
14765 Item *item = NewItemOrBag(proto);
14767 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14769 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14770 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14771 item->FSetState(ITEM_REMOVED);
14772 item->SaveToDB(); // it also deletes item object !
14773 continue;
14776 // not allow have in alive state item limited to another map/zone
14777 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14779 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14780 item->FSetState(ITEM_REMOVED);
14781 item->SaveToDB(); // it also deletes item object !
14782 continue;
14785 // "Conjured items disappear if you are logged out for more than 15 minutes"
14786 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14788 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14789 item->FSetState(ITEM_REMOVED);
14790 item->SaveToDB(); // it also deletes item object !
14791 continue;
14794 bool success = true;
14796 if (!bag_guid)
14798 // the item is not in a bag
14799 item->SetContainer( NULL );
14800 item->SetSlot(slot);
14802 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14804 ItemPosCountVec dest;
14805 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14806 item = StoreItem(dest, item, true);
14807 else
14808 success = false;
14810 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14812 uint16 dest;
14813 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14814 QuickEquipItem(dest, item);
14815 else
14816 success = false;
14818 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14820 ItemPosCountVec dest;
14821 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14822 item = BankItem(dest, item, true);
14823 else
14824 success = false;
14827 if(success)
14829 // store bags that may contain items in them
14830 if(item->IsBag() && IsBagPos(item->GetPos()))
14831 bagMap[item_guid] = (Bag*)item;
14834 else
14836 item->SetSlot(NULL_SLOT);
14837 // the item is in a bag, find the bag
14838 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14839 if(itr != bagMap.end())
14840 itr->second->StoreItem(slot, item, true );
14841 else
14842 success = false;
14845 // item's state may have changed after stored
14846 if (success)
14847 item->SetState(ITEM_UNCHANGED, this);
14848 else
14850 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);
14851 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14852 problematicItems.push_back(item);
14854 } while (result->NextRow());
14856 delete result;
14857 m_itemUpdateQueueBlocked = false;
14859 // send by mail problematic items
14860 while(!problematicItems.empty())
14862 // fill mail
14863 MailItemsInfo mi; // item list preparing
14865 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14867 Item* item = problematicItems.front();
14868 problematicItems.pop_front();
14870 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14873 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14875 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14878 //if(isAlive())
14879 _ApplyAllItemMods();
14882 // load mailed item which should receive current player
14883 void Player::_LoadMailedItems(Mail *mail)
14885 // data needs to be at first place for Item::LoadFromDB
14886 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);
14887 if(!result)
14888 return;
14892 Field *fields = result->Fetch();
14893 uint32 item_guid_low = fields[1].GetUInt32();
14894 uint32 item_template = fields[2].GetUInt32();
14896 mail->AddItem(item_guid_low, item_template);
14898 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14900 if(!proto)
14902 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);
14903 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14904 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14905 continue;
14908 Item *item = NewItemOrBag(proto);
14910 if(!item->LoadFromDB(item_guid_low, 0, result))
14912 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14913 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14914 item->FSetState(ITEM_REMOVED);
14915 item->SaveToDB(); // it also deletes item object !
14916 continue;
14919 AddMItem(item);
14920 } while (result->NextRow());
14922 delete result;
14925 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14927 //set a count of unread mails
14928 //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);
14929 if (resultUnread)
14931 Field *fieldMail = resultUnread->Fetch();
14932 unReadMails = fieldMail[0].GetUInt8();
14933 delete resultUnread;
14936 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14937 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14938 if (resultDelivery)
14940 Field *fieldMail = resultDelivery->Fetch();
14941 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14942 delete resultDelivery;
14946 void Player::_LoadMail()
14948 m_mail.clear();
14949 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14950 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());
14951 if(result)
14955 Field *fields = result->Fetch();
14956 Mail *m = new Mail;
14957 m->messageID = fields[0].GetUInt32();
14958 m->messageType = fields[1].GetUInt8();
14959 m->sender = fields[2].GetUInt32();
14960 m->receiver = fields[3].GetUInt32();
14961 m->subject = fields[4].GetCppString();
14962 m->itemTextId = fields[5].GetUInt32();
14963 bool has_items = fields[6].GetBool();
14964 m->expire_time = (time_t)fields[7].GetUInt64();
14965 m->deliver_time = (time_t)fields[8].GetUInt64();
14966 m->money = fields[9].GetUInt32();
14967 m->COD = fields[10].GetUInt32();
14968 m->checked = fields[11].GetUInt32();
14969 m->stationery = fields[12].GetUInt8();
14970 m->mailTemplateId = fields[13].GetInt16();
14972 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14974 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14975 m->mailTemplateId = 0;
14978 m->state = MAIL_STATE_UNCHANGED;
14980 if (has_items)
14981 _LoadMailedItems(m);
14983 m_mail.push_back(m);
14984 } while( result->NextRow() );
14985 delete result;
14987 m_mailsLoaded = true;
14990 void Player::LoadPet()
14992 //fixme: the pet should still be loaded if the player is not in world
14993 // just not added to the map
14994 if(IsInWorld())
14996 Pet *pet = new Pet;
14997 if(!pet->LoadPetFromDB(this,0,0,true))
14998 delete pet;
15002 void Player::_LoadQuestStatus(QueryResult *result)
15004 mQuestStatus.clear();
15006 uint32 slot = 0;
15008 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15009 //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());
15011 if(result)
15015 Field *fields = result->Fetch();
15017 uint32 quest_id = fields[0].GetUInt32();
15018 // used to be new, no delete?
15019 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15020 if( pQuest )
15022 // find or create
15023 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15025 uint32 qstatus = fields[1].GetUInt32();
15026 if(qstatus < MAX_QUEST_STATUS)
15027 questStatusData.m_status = QuestStatus(qstatus);
15028 else
15030 questStatusData.m_status = QUEST_STATUS_NONE;
15031 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15034 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15035 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15037 time_t quest_time = time_t(fields[4].GetUInt64());
15039 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15041 AddTimedQuest( quest_id );
15043 if (quest_time <= sWorld.GetGameTime())
15044 questStatusData.m_timer = 1;
15045 else
15046 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
15048 else
15049 quest_time = 0;
15051 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15052 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15053 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15054 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15055 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15056 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15057 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15058 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15060 questStatusData.uState = QUEST_UNCHANGED;
15062 // add to quest log
15063 if( slot < MAX_QUEST_LOG_SIZE &&
15064 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
15065 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
15066 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15068 SetQuestSlot(slot,quest_id,quest_time);
15070 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15071 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
15073 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15074 if(questStatusData.m_creatureOrGOcount[idx])
15075 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
15077 ++slot;
15080 if(questStatusData.m_rewarded)
15082 // learn rewarded spell if unknown
15083 learnQuestRewardedSpells(pQuest);
15085 // set rewarded title if any
15086 if(pQuest->GetCharTitleId())
15088 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15089 SetTitle(titleEntry);
15092 if(pQuest->GetBonusTalents())
15093 m_questRewardTalentCount+=pQuest->GetBonusTalents();
15096 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15099 while( result->NextRow() );
15101 delete result;
15104 // clear quest log tail
15105 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15106 SetQuestSlot(i,0);
15109 void Player::_LoadDailyQuestStatus(QueryResult *result)
15111 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15112 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15114 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15116 if(result)
15118 uint32 quest_daily_idx = 0;
15122 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15124 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15125 break;
15128 Field *fields = result->Fetch();
15130 uint32 quest_id = fields[0].GetUInt32();
15132 // save _any_ from daily quest times (it must be after last reset anyway)
15133 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15135 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15136 if( !pQuest )
15137 continue;
15139 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15140 ++quest_daily_idx;
15142 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15144 while( result->NextRow() );
15146 delete result;
15149 m_DailyQuestChanged = false;
15152 void Player::_LoadReputation(QueryResult *result)
15154 m_factions.clear();
15156 // Set initial reputations (so everything is nifty before DB data load)
15157 SetInitialFactions();
15159 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15161 if(result)
15165 Field *fields = result->Fetch();
15167 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
15168 if( factionEntry && (factionEntry->reputationListID >= 0))
15170 FactionState* faction = &m_factions[factionEntry->reputationListID];
15172 // update standing to current
15173 faction->Standing = int32(fields[1].GetUInt32());
15175 uint32 dbFactionFlags = fields[2].GetUInt32();
15177 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
15178 SetFactionVisible(faction); // have internal checks for forced invisibility
15180 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
15181 SetFactionInactive(faction,true); // have internal checks for visibility requirement
15183 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
15184 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15185 else // DB not at war
15187 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15188 if( faction->Flags & FACTION_FLAG_VISIBLE )
15189 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15192 // set atWar for hostile
15193 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
15194 SetFactionAtWar(faction,true);
15196 // reset changed flag if values similar to saved in DB
15197 if(faction->Flags==dbFactionFlags)
15198 faction->Changed = false;
15201 while( result->NextRow() );
15203 delete result;
15207 void Player::_LoadSpells(QueryResult *result)
15209 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15211 if(result)
15215 Field *fields = result->Fetch();
15217 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15219 while( result->NextRow() );
15221 delete result;
15225 void Player::_LoadTutorials(QueryResult *result)
15227 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15229 if(result)
15233 Field *fields = result->Fetch();
15235 for (int iI=0; iI<8; iI++)
15236 m_Tutorials[iI] = fields[iI].GetUInt32();
15238 while( result->NextRow() );
15240 delete result;
15243 m_TutorialsChanged = false;
15246 void Player::_LoadGroup(QueryResult *result)
15248 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15249 if(result)
15251 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15252 delete result;
15253 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15254 if(group)
15256 uint8 subgroup = group->GetMemberGroup(GetGUID());
15257 SetGroup(group, subgroup);
15258 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15260 // the group leader may change the instance difficulty while the player is offline
15261 SetDifficulty(group->GetDifficulty());
15267 void Player::_LoadBoundInstances(QueryResult *result)
15269 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15270 m_boundInstances[i].clear();
15272 Group *group = GetGroup();
15274 //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));
15275 if(result)
15279 Field *fields = result->Fetch();
15280 bool perm = fields[1].GetBool();
15281 uint32 mapId = fields[2].GetUInt32();
15282 uint32 instanceId = fields[0].GetUInt32();
15283 uint8 difficulty = fields[3].GetUInt8();
15284 time_t resetTime = (time_t)fields[4].GetUInt64();
15285 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15286 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15287 // and in that case it is not used
15289 if(!perm && group)
15291 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);
15292 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15293 continue;
15296 // since non permanent binds are always solo bind, they can always be reset
15297 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15298 if(save) BindToInstance(save, perm, true);
15299 } while(result->NextRow());
15300 delete result;
15304 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15306 // some instances only have one difficulty
15307 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15308 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15310 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15311 if(itr != m_boundInstances[difficulty].end())
15312 return &itr->second;
15313 else
15314 return NULL;
15317 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15319 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15320 UnbindInstance(itr, difficulty, unload);
15323 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15325 if(itr != m_boundInstances[difficulty].end())
15327 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15328 itr->second.save->RemovePlayer(this); // save can become invalid
15329 m_boundInstances[difficulty].erase(itr++);
15333 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15335 if(save)
15337 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15338 if(bind.save)
15340 // update the save when the group kills a boss
15341 if(permanent != bind.perm || save != bind.save)
15342 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());
15344 else
15345 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15347 if(bind.save != save)
15349 if(bind.save) bind.save->RemovePlayer(this);
15350 save->AddPlayer(this);
15353 if(permanent) save->SetCanReset(false);
15355 bind.save = save;
15356 bind.perm = permanent;
15357 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());
15358 return &bind;
15360 else
15361 return NULL;
15364 void Player::SendRaidInfo()
15366 uint32 counter = 0;
15368 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15370 size_t p_counter = data.wpos();
15371 data << uint32(counter); // placeholder
15373 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15375 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15377 if(itr->second.perm)
15379 InstanceSave *save = itr->second.save;
15380 data << uint32(save->GetMapId());
15381 data << uint32(save->GetResetTime() - time(NULL));
15382 data << uint32(save->GetInstanceId());
15383 data << uint32(save->GetDifficulty());
15384 ++counter;
15388 data.put<uint32>(p_counter,counter);
15389 GetSession()->SendPacket(&data);
15393 - called on every successful teleportation to a map
15395 void Player::SendSavedInstances()
15397 bool hasBeenSaved = false;
15398 WorldPacket data;
15400 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15402 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15404 if(itr->second.perm) // only permanent binds are sent
15406 hasBeenSaved = true;
15407 break;
15412 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15413 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15414 data << uint32(hasBeenSaved);
15415 GetSession()->SendPacket(&data);
15417 if(!hasBeenSaved)
15418 return;
15420 for(uint8 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 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15427 data << uint32(itr->second.save->GetMapId());
15428 GetSession()->SendPacket(&data);
15434 /// convert the player's binds to the group
15435 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15437 bool has_binds = false;
15438 bool has_solo = false;
15440 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15441 assert(player_guid);
15443 // copy all binds to the group, when changing leader it's assumed the character
15444 // will not have any solo binds
15446 if(player)
15448 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15450 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15452 has_binds = true;
15453 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15454 // permanent binds are not removed
15455 if(!itr->second.perm)
15457 player->UnbindInstance(itr, i, true); // increments itr
15458 has_solo = true;
15460 else
15461 ++itr;
15466 // if the player's not online we don't know what binds it has
15467 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));
15468 // the following should not get executed when changing leaders
15469 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15472 bool Player::_LoadHomeBind(QueryResult *result)
15474 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15475 if(!info)
15477 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15478 return false;
15481 bool ok = false;
15482 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15483 if (result)
15485 Field *fields = result->Fetch();
15486 m_homebindMapId = fields[0].GetUInt32();
15487 m_homebindZoneId = fields[1].GetUInt16();
15488 m_homebindX = fields[2].GetFloat();
15489 m_homebindY = fields[3].GetFloat();
15490 m_homebindZ = fields[4].GetFloat();
15491 delete result;
15493 // accept saved data only for valid position (and non instanceable)
15494 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15495 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15497 ok = true;
15499 else
15500 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15503 if(!ok)
15505 m_homebindMapId = info->mapId;
15506 m_homebindZoneId = info->zoneId;
15507 m_homebindX = info->positionX;
15508 m_homebindY = info->positionY;
15509 m_homebindZ = info->positionZ;
15511 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);
15514 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15515 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15517 return true;
15520 /*********************************************************/
15521 /*** SAVE SYSTEM ***/
15522 /*********************************************************/
15524 void Player::SaveToDB()
15526 // delay auto save at any saves (manual, in code, or autosave)
15527 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15529 // first save/honor gain after midnight will also update the player's honor fields
15530 UpdateHonorFields();
15532 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15533 //save, far from tavern/city
15534 //save, but in tavern/city
15535 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15536 outDebugValues();
15538 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15539 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15540 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15541 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15542 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15543 uint32 tmp_displayid = GetDisplayId();
15545 // Set player sit state to standing on save, also stealth and shifted form
15546 SetStandState(UNIT_STAND_STATE_STAND); // stand state
15547 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // stand flags?
15548 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15549 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15550 SetDisplayId(GetNativeDisplayId());
15552 bool inworld = IsInWorld();
15554 CharacterDatabase.BeginTransaction();
15556 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15558 std::string sql_name = m_name;
15559 CharacterDatabase.escape_string(sql_name);
15561 std::ostringstream ss;
15562 ss << "INSERT INTO characters (guid,account,name,race,class,"
15563 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15564 "taximask, online, cinematic, "
15565 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15566 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15567 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15568 << GetGUIDLow() << ", "
15569 << GetSession()->GetAccountId() << ", '"
15570 << sql_name << "', "
15571 << m_race << ", "
15572 << m_class << ", ";
15574 if(!IsBeingTeleported())
15576 ss << GetMapId() << ", "
15577 << (uint32)GetDifficulty() << ", "
15578 << finiteAlways(GetPositionX()) << ", "
15579 << finiteAlways(GetPositionY()) << ", "
15580 << finiteAlways(GetPositionZ()) << ", "
15581 << finiteAlways(GetOrientation()) << ", '";
15583 else
15585 ss << GetTeleportDest().mapid << ", "
15586 << (uint32)GetDifficulty() << ", "
15587 << finiteAlways(GetTeleportDest().x) << ", "
15588 << finiteAlways(GetTeleportDest().y) << ", "
15589 << finiteAlways(GetTeleportDest().z) << ", "
15590 << finiteAlways(GetTeleportDest().o) << ", '";
15593 uint16 i;
15594 for( i = 0; i < m_valuesCount; i++ )
15596 ss << GetUInt32Value(i) << " ";
15599 ss << "', ";
15601 ss << m_taxi; // string with TaxiMaskSize numbers
15603 ss << ", ";
15604 ss << (inworld ? 1 : 0);
15606 ss << ", ";
15607 ss << m_cinematic;
15609 ss << ", ";
15610 ss << m_Played_time[0];
15611 ss << ", ";
15612 ss << m_Played_time[1];
15614 ss << ", ";
15615 ss << finiteAlways(m_rest_bonus);
15616 ss << ", ";
15617 ss << (uint64)time(NULL);
15618 ss << ", ";
15619 ss << is_save_resting;
15620 ss << ", ";
15621 ss << m_resetTalentsCost;
15622 ss << ", ";
15623 ss << (uint64)m_resetTalentsTime;
15625 ss << ", ";
15626 ss << finiteAlways(m_movementInfo.t_x);
15627 ss << ", ";
15628 ss << finiteAlways(m_movementInfo.t_y);
15629 ss << ", ";
15630 ss << finiteAlways(m_movementInfo.t_z);
15631 ss << ", ";
15632 ss << finiteAlways(m_movementInfo.t_o);
15633 ss << ", ";
15634 if (m_transport)
15635 ss << m_transport->GetGUIDLow();
15636 else
15637 ss << "0";
15639 ss << ", ";
15640 ss << m_ExtraFlags;
15642 ss << ", ";
15643 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15645 ss << ", ";
15646 ss << uint32(m_atLoginFlags);
15648 ss << ", ";
15649 ss << GetZoneId();
15651 ss << ", ";
15652 ss << (uint64)m_deathExpireTime;
15654 ss << ", '";
15655 ss << m_taxi.SaveTaxiDestinationsToString();
15656 ss << "', '0', ";
15657 ss << GetBattleGroundId();
15658 ss << ", ";
15659 ss << GetBGTeam();
15660 ss << ", ";
15661 ss << m_bgEntryPoint.mapid << ", "
15662 << finiteAlways(m_bgEntryPoint.x) << ", "
15663 << finiteAlways(m_bgEntryPoint.y) << ", "
15664 << finiteAlways(m_bgEntryPoint.z) << ", "
15665 << finiteAlways(m_bgEntryPoint.o);
15666 ss << ")";
15668 CharacterDatabase.Execute( ss.str().c_str() );
15670 if(m_mailsUpdated) //save mails only when needed
15671 _SaveMail();
15673 _SaveInventory();
15674 _SaveQuestStatus();
15675 _SaveDailyQuestStatus();
15676 _SaveTutorials();
15677 _SaveSpells();
15678 _SaveSpellCooldowns();
15679 _SaveActions();
15680 _SaveAuras();
15681 _SaveReputation();
15683 CharacterDatabase.CommitTransaction();
15685 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15686 SetDisplayId(tmp_displayid);
15687 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15688 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15689 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15690 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15692 // save pet (hunter pet level and experience and all type pets health/mana).
15693 if(Pet* pet = GetPet())
15694 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15695 m_achievementMgr.SaveToDB();
15698 // fast save function for item/money cheating preventing - save only inventory and money state
15699 void Player::SaveInventoryAndGoldToDB()
15701 _SaveInventory();
15702 //money is in data field
15703 SaveDataFieldToDB();
15706 void Player::_SaveActions()
15708 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15710 switch (itr->second.uState)
15712 case ACTIONBUTTON_NEW:
15713 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15714 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15715 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15716 ++itr;
15717 break;
15718 case ACTIONBUTTON_CHANGED:
15719 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15720 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15721 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15722 ++itr;
15723 break;
15724 case ACTIONBUTTON_DELETED:
15725 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15726 m_actionButtons.erase(itr++);
15727 break;
15728 default:
15729 ++itr;
15730 break;
15735 void Player::_SaveAuras()
15737 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15739 AuraMap const& auras = GetAuras();
15741 if (auras.empty())
15742 return;
15744 spellEffectPair lastEffectPair = auras.begin()->first;
15745 uint32 stackCounter = 1;
15747 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15749 if(itr == auras.end() || lastEffectPair != itr->first)
15751 AuraMap::const_iterator itr2 = itr;
15752 // save previous spellEffectPair to db
15753 itr2--;
15754 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15756 //skip all auras from spells that are passive or need a shapeshift
15757 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15759 //do not save single target auras (unless they were cast by the player)
15760 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15762 uint8 i;
15763 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15764 for (i = 0; i < 3; i++)
15765 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15766 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15767 break;
15769 if (i == 3)
15771 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15772 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15773 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()));
15778 if(itr == auras.end())
15779 break;
15782 if (lastEffectPair == itr->first)
15783 stackCounter++;
15784 else
15786 lastEffectPair = itr->first;
15787 stackCounter = 1;
15792 void Player::_SaveInventory()
15794 // force items in buyback slots to new state
15795 // and remove those that aren't already
15796 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15798 Item *item = m_items[i];
15799 if (!item || item->GetState() == ITEM_NEW) continue;
15800 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15801 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15802 m_items[i]->FSetState(ITEM_NEW);
15805 // update enchantment durations
15806 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15808 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15811 // if no changes
15812 if (m_itemUpdateQueue.empty()) return;
15814 // do not save if the update queue is corrupt
15815 bool error = false;
15816 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15818 Item *item = m_itemUpdateQueue[i];
15819 if(!item || item->GetState() == ITEM_REMOVED) continue;
15820 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15822 if (test == NULL)
15824 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());
15825 error = true;
15827 else if (test != item)
15829 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());
15830 error = true;
15834 if (error)
15836 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15837 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15838 return;
15841 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15843 Item *item = m_itemUpdateQueue[i];
15844 if(!item) continue;
15846 Bag *container = item->GetContainer();
15847 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15849 switch(item->GetState())
15851 case ITEM_NEW:
15852 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());
15853 break;
15854 case ITEM_CHANGED:
15855 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());
15856 break;
15857 case ITEM_REMOVED:
15858 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15859 break;
15860 case ITEM_UNCHANGED:
15861 break;
15864 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15866 m_itemUpdateQueue.clear();
15869 void Player::_SaveMail()
15871 if (!m_mailsLoaded)
15872 return;
15874 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15876 Mail *m = (*itr);
15877 if (m->state == MAIL_STATE_CHANGED)
15879 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'",
15880 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15881 if(m->removedItems.size())
15883 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15884 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15885 m->removedItems.clear();
15887 m->state = MAIL_STATE_UNCHANGED;
15889 else if (m->state == MAIL_STATE_DELETED)
15891 if (m->HasItems())
15892 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15893 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15894 if (m->itemTextId)
15895 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15896 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15897 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15901 //deallocate deleted mails...
15902 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15904 if ((*itr)->state == MAIL_STATE_DELETED)
15906 Mail* m = *itr;
15907 m_mail.erase(itr);
15908 delete m;
15909 itr = m_mail.begin();
15911 else
15912 ++itr;
15915 m_mailsUpdated = false;
15918 void Player::_SaveQuestStatus()
15920 // we don't need transactions here.
15921 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15923 switch (i->second.uState)
15925 case QUEST_NEW :
15926 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15927 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15928 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]);
15929 break;
15930 case QUEST_CHANGED :
15931 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' ",
15932 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 );
15933 break;
15934 case QUEST_UNCHANGED:
15935 break;
15937 i->second.uState = QUEST_UNCHANGED;
15941 void Player::_SaveDailyQuestStatus()
15943 if(!m_DailyQuestChanged)
15944 return;
15946 m_DailyQuestChanged = false;
15948 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15950 // we don't need transactions here.
15951 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15952 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15953 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15954 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15955 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15958 void Player::_SaveReputation()
15960 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15962 if (itr->second.Changed)
15964 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15965 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);
15966 itr->second.Changed = false;
15971 void Player::_SaveSpells()
15973 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15975 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15976 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15978 // add only changed/new not dependent spells
15979 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15980 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);
15982 if (itr->second->state == PLAYERSPELL_REMOVED)
15984 delete itr->second;
15985 m_spells.erase(itr++);
15987 else
15989 itr->second->state = PLAYERSPELL_UNCHANGED;
15990 ++itr;
15996 void Player::_SaveTutorials()
15998 if(!m_TutorialsChanged)
15999 return;
16001 uint32 Rows=0;
16002 // it's better than rebuilding indexes multiple times
16003 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
16004 if(result)
16006 Rows = result->Fetch()[0].GetUInt32();
16007 delete result;
16010 if (Rows)
16012 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'",
16013 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 );
16015 else
16017 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]);
16020 m_TutorialsChanged = false;
16023 void Player::outDebugValues() const
16025 if(!sLog.IsOutDebug()) // optimize disabled debug output
16026 return;
16028 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16029 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16030 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16031 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
16032 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16033 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16034 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16035 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16036 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16037 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16038 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16039 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16042 /*********************************************************/
16043 /*** FLOOD FILTER SYSTEM ***/
16044 /*********************************************************/
16046 void Player::UpdateSpeakTime()
16048 // ignore chat spam protection for GMs in any mode
16049 if(GetSession()->GetSecurity() > SEC_PLAYER)
16050 return;
16052 time_t current = time (NULL);
16053 if(m_speakTime > current)
16055 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16056 if(!max_count)
16057 return;
16059 ++m_speakCount;
16060 if(m_speakCount >= max_count)
16062 // prevent overwrite mute time, if message send just before mutes set, for example.
16063 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16064 if(GetSession()->m_muteTime < new_mute)
16065 GetSession()->m_muteTime = new_mute;
16067 m_speakCount = 0;
16070 else
16071 m_speakCount = 0;
16073 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16076 bool Player::CanSpeak() const
16078 return GetSession()->m_muteTime <= time (NULL);
16081 /*********************************************************/
16082 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16083 /*********************************************************/
16085 void Player::SendAttackSwingNotInRange()
16087 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16088 GetSession()->SendPacket( &data );
16091 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16093 std::ostringstream ss;
16094 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16095 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16096 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16097 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16098 sLog.outDebug(ss.str().c_str());
16099 CharacterDatabase.Execute(ss.str().c_str());
16102 void Player::SaveDataFieldToDB()
16104 std::ostringstream ss;
16105 ss<<"UPDATE characters SET data='";
16107 for(uint16 i = 0; i < m_valuesCount; i++ )
16109 ss << GetUInt32Value(i) << " ";
16111 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16113 CharacterDatabase.Execute(ss.str().c_str());
16116 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16118 std::ostringstream ss2;
16119 ss2<<"UPDATE characters SET data='";
16120 int i=0;
16121 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16123 ss2<<tokens[i]<<" ";
16125 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16127 return CharacterDatabase.Execute(ss2.str().c_str());
16130 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16132 char buf[11];
16133 snprintf(buf,11,"%u",value);
16135 if(index >= tokens.size())
16136 return;
16138 tokens[index] = buf;
16141 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16143 Tokens tokens;
16144 if(!LoadValuesArrayFromDB(tokens,guid))
16145 return;
16147 if(index >= tokens.size())
16148 return;
16150 char buf[11];
16151 snprintf(buf,11,"%u",value);
16152 tokens[index] = buf;
16154 SaveValuesArrayInDB(tokens,guid);
16157 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16159 uint32 temp;
16160 memcpy(&temp, &value, sizeof(value));
16161 Player::SetUInt32ValueInDB(index, temp, guid);
16164 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16166 Tokens tokens;
16167 if(!LoadValuesArrayFromDB(tokens, guid))
16168 return;
16170 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
16171 uint8 race = unit_bytes0 & 0xFF;
16172 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
16174 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
16175 if(!info)
16176 return;
16178 unit_bytes0 &= ~(0xFF << 16);
16179 unit_bytes0 |= (gender << 16);
16180 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
16182 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16183 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16185 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16187 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16188 player_bytes2 &= ~0xFF;
16189 player_bytes2 |= facialHair;
16190 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16192 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16193 player_bytes3 &= ~0xFF;
16194 player_bytes3 |= gender;
16195 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16197 SaveValuesArrayInDB(tokens, guid);
16200 void Player::SendAttackSwingNotStanding()
16202 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16203 GetSession()->SendPacket( &data );
16206 void Player::SendAttackSwingDeadTarget()
16208 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16209 GetSession()->SendPacket( &data );
16212 void Player::SendAttackSwingCantAttack()
16214 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16215 GetSession()->SendPacket( &data );
16218 void Player::SendAttackSwingCancelAttack()
16220 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16221 GetSession()->SendPacket( &data );
16224 void Player::SendAttackSwingBadFacingAttack()
16226 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16227 GetSession()->SendPacket( &data );
16230 void Player::SendAutoRepeatCancel()
16232 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16233 data.append(GetPackGUID()); // may be it's target guid
16234 GetSession()->SendPacket( &data );
16237 void Player::PlaySound(uint32 Sound, bool OnlySelf)
16239 WorldPacket data(SMSG_PLAY_SOUND, 4);
16240 data << Sound;
16241 if (OnlySelf)
16242 GetSession()->SendPacket( &data );
16243 else
16244 SendMessageToSet( &data, true );
16247 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16249 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16250 data << Area;
16251 data << Experience;
16252 GetSession()->SendPacket(&data);
16255 void Player::SendDungeonDifficulty(bool IsInGroup)
16257 uint8 val = 0x00000001;
16258 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16259 data << (uint32)GetDifficulty();
16260 data << uint32(val);
16261 data << uint32(IsInGroup);
16262 GetSession()->SendPacket(&data);
16265 void Player::SendResetFailedNotify(uint32 mapid)
16267 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16268 data << uint32(mapid);
16269 GetSession()->SendPacket(&data);
16272 /// Reset all solo instances and optionally send a message on success for each
16273 void Player::ResetInstances(uint8 method)
16275 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16277 // we assume that when the difficulty changes, all instances that can be reset will be
16278 uint8 dif = GetDifficulty();
16280 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16282 InstanceSave *p = itr->second.save;
16283 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16284 if(!entry || !p->CanReset())
16286 ++itr;
16287 continue;
16290 if(method == INSTANCE_RESET_ALL)
16292 // the "reset all instances" method can only reset normal maps
16293 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16295 ++itr;
16296 continue;
16300 // if the map is loaded, reset it
16301 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16302 if(map && map->IsDungeon())
16303 ((InstanceMap*)map)->Reset(method);
16305 // since this is a solo instance there should not be any players inside
16306 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16307 SendResetInstanceSuccess(p->GetMapId());
16309 p->DeleteFromDB();
16310 m_boundInstances[dif].erase(itr++);
16312 // the following should remove the instance save from the manager and delete it as well
16313 p->RemovePlayer(this);
16317 void Player::SendResetInstanceSuccess(uint32 MapId)
16319 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16320 data << MapId;
16321 GetSession()->SendPacket(&data);
16324 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16326 // TODO: find what other fail reasons there are besides players in the instance
16327 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16328 data << reason;
16329 data << MapId;
16330 GetSession()->SendPacket(&data);
16333 /*********************************************************/
16334 /*** Update timers ***/
16335 /*********************************************************/
16337 ///checks the 15 afk reports per 5 minutes limit
16338 void Player::UpdateAfkReport(time_t currTime)
16340 if(m_bgAfkReportedTimer <= currTime)
16342 m_bgAfkReportedCount = 0;
16343 m_bgAfkReportedTimer = currTime+5*MINUTE;
16347 void Player::UpdateContestedPvP(uint32 diff)
16349 if(!m_contestedPvPTimer||isInCombat())
16350 return;
16351 if(m_contestedPvPTimer <= diff)
16353 ResetContestedPvP();
16355 else
16356 m_contestedPvPTimer -= diff;
16359 void Player::UpdatePvPFlag(time_t currTime)
16361 if(!IsPvP())
16362 return;
16363 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16364 return;
16366 UpdatePvP(false);
16369 void Player::UpdateDuelFlag(time_t currTime)
16371 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16372 return;
16374 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16375 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16377 duel->startTimer = 0;
16378 duel->startTime = currTime;
16379 duel->opponent->duel->startTimer = 0;
16380 duel->opponent->duel->startTime = currTime;
16383 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16385 if(!pet)
16386 pet = GetPet();
16388 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16390 //returning of reagents only for players, so best done here
16391 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16392 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16394 if(spellInfo)
16396 for(uint32 i = 0; i < 7; ++i)
16398 if(spellInfo->Reagent[i] > 0)
16400 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16401 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16402 if( msg == EQUIP_ERR_OK )
16404 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16405 if(IsInWorld())
16406 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16411 m_temporaryUnsummonedPetNumber = 0;
16414 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16415 return;
16417 // only if current pet in slot
16418 switch(pet->getPetType())
16420 case MINI_PET:
16421 m_miniPet = 0;
16422 break;
16423 case GUARDIAN_PET:
16424 m_guardianPets.erase(pet->GetGUID());
16425 break;
16426 default:
16427 if(GetPetGUID() == pet->GetGUID())
16428 SetPet(NULL);
16429 break;
16432 pet->CombatStop();
16434 if(returnreagent)
16436 switch(pet->GetEntry())
16438 //warlock pets except imp are removed(?) when logging out
16439 case 1860:
16440 case 1863:
16441 case 417:
16442 case 17252:
16443 mode = PET_SAVE_NOT_IN_SLOT;
16444 break;
16448 pet->SavePetToDB(mode);
16450 pet->CleanupsBeforeDelete();
16451 pet->AddObjectToRemoveList();
16452 pet->m_removed = true;
16454 if(pet->isControlled())
16456 WorldPacket data(SMSG_PET_SPELLS, 8);
16457 data << uint64(0);
16458 data << uint32(0);
16459 GetSession()->SendPacket(&data);
16461 if(GetGroup())
16462 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16466 void Player::RemoveMiniPet()
16468 if(Pet* pet = GetMiniPet())
16470 pet->Remove(PET_SAVE_AS_DELETED);
16471 m_miniPet = 0;
16475 Pet* Player::GetMiniPet()
16477 if(!m_miniPet)
16478 return NULL;
16479 return ObjectAccessor::GetPet(m_miniPet);
16482 void Player::RemoveGuardians()
16484 while(!m_guardianPets.empty())
16486 uint64 guid = *m_guardianPets.begin();
16487 if(Pet* pet = ObjectAccessor::GetPet(guid))
16488 pet->Remove(PET_SAVE_AS_DELETED);
16490 m_guardianPets.erase(guid);
16494 bool Player::HasGuardianWithEntry(uint32 entry)
16496 // pet guid middle part is entry (and creature also)
16497 // and in guardian list must be guardians with same entry _always_
16498 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16499 if(GUID_ENPART(*itr)==entry)
16500 return true;
16502 return false;
16505 void Player::Uncharm()
16507 Unit* charm = GetCharm();
16508 if(!charm)
16509 return;
16511 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16512 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16515 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16517 *data << (uint8)msgtype;
16518 *data << (uint32)language;
16519 *data << (uint64)GetGUID();
16520 *data << (uint32)language; //language 2.1.0 ?
16521 *data << (uint64)GetGUID();
16522 *data << (uint32)(text.length()+1);
16523 *data << text;
16524 *data << (uint8)chatTag();
16527 void Player::Say(const std::string& text, const uint32 language)
16529 WorldPacket data(SMSG_MESSAGECHAT, 200);
16530 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16531 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16534 void Player::Yell(const std::string& text, const uint32 language)
16536 WorldPacket data(SMSG_MESSAGECHAT, 200);
16537 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16538 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16541 void Player::TextEmote(const std::string& text)
16543 WorldPacket data(SMSG_MESSAGECHAT, 200);
16544 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16545 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16548 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16550 if (language != LANG_ADDON) // if not addon data
16551 language = LANG_UNIVERSAL; // whispers should always be readable
16553 Player *rPlayer = objmgr.GetPlayer(receiver);
16555 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16556 if(!rPlayer->isDND() || isGameMaster())
16558 WorldPacket data(SMSG_MESSAGECHAT, 200);
16559 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16560 rPlayer->GetSession()->SendPacket(&data);
16562 data.Initialize(SMSG_MESSAGECHAT, 200);
16563 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16564 GetSession()->SendPacket(&data);
16566 else
16568 // announce to player that player he is whispering to is dnd and cannot receive his message
16569 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16572 if(!isAcceptWhispers())
16574 SetAcceptWhispers(true);
16575 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16578 // announce to player that player he is whispering to is afk
16579 if(rPlayer->isAFK())
16580 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16582 // if player whisper someone, auto turn of dnd to be able to receive an answer
16583 if(isDND() && !rPlayer->isGameMaster())
16584 ToggleDND();
16587 void Player::PetSpellInitialize()
16589 Pet* pet = GetPet();
16591 if(!pet)
16592 return;
16594 sLog.outDebug("Pet Spells Groups");
16596 CharmInfo *charmInfo = pet->GetCharmInfo();
16598 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16599 data << uint64(pet->GetGUID());
16600 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16601 data << uint32(0);
16602 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16604 // action bar loop
16605 for(uint32 i = 0; i < 10; i++)
16607 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16610 size_t spellsCountPos = data.wpos();
16612 // spells count
16613 uint8 addlist = 0;
16614 data << uint8(addlist); // placeholder
16616 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16618 // spells loop
16619 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16621 if(itr->second->state == PETSPELL_REMOVED)
16622 continue;
16624 data << uint16(itr->first);
16625 data << uint16(itr->second->active); // pet spell active state isn't boolean
16626 ++addlist;
16630 data.put<uint8>(spellsCountPos, addlist);
16632 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16633 data << uint8(cooldownsCount);
16635 time_t curTime = time(NULL);
16637 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16639 time_t cooldown = 0;
16641 if(itr->second > curTime)
16642 cooldown = (itr->second - curTime) * 1000;
16644 data << uint16(itr->first); // spellid
16645 data << uint16(0); // spell category?
16646 data << uint32(itr->second); // cooldown
16647 data << uint32(0); // category cooldown
16650 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16652 time_t cooldown = 0;
16654 if(itr->second > curTime)
16655 cooldown = (itr->second - curTime) * 1000;
16657 data << uint16(itr->first); // spellid
16658 data << uint16(0); // spell category?
16659 data << uint32(0); // cooldown
16660 data << uint32(itr->second); // category cooldown
16663 GetSession()->SendPacket(&data);
16666 void Player::PossessSpellInitialize()
16668 Unit* charm = GetCharm();
16670 if(!charm)
16671 return;
16673 CharmInfo *charmInfo = charm->GetCharmInfo();
16675 if(!charmInfo)
16677 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16678 return;
16681 uint8 addlist = 0;
16682 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16684 //16
16685 data << uint64(charm->GetGUID());
16686 data << uint32(0x00000000);
16687 data << uint32(0);
16688 data << uint8(0) << uint8(0) << uint16(0);
16690 for(uint32 i = 0; i < 10; i++) //40
16692 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16695 data << uint8(addlist); //1
16697 uint8 count = 0;
16698 data << uint8(count); // cooldowns count
16700 GetSession()->SendPacket(&data);
16703 void Player::CharmSpellInitialize()
16705 Unit* charm = GetCharm();
16707 if(!charm)
16708 return;
16710 CharmInfo *charmInfo = charm->GetCharmInfo();
16711 if(!charmInfo)
16713 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16714 return;
16717 uint8 addlist = 0;
16719 if(charm->GetTypeId() != TYPEID_PLAYER)
16721 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16723 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16725 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16727 if(charmInfo->GetCharmSpell(i)->spellId)
16728 ++addlist;
16733 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16735 data << uint64(charm->GetGUID());
16736 data << uint32(0x00000000);
16737 data << uint32(0);
16738 if(charm->GetTypeId() != TYPEID_PLAYER)
16739 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16740 else
16741 data << uint8(0) << uint8(0);
16742 data << uint16(0);
16744 for(uint32 i = 0; i < 10; i++) //40
16746 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16749 data << uint8(addlist); //1
16751 if(addlist)
16753 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16755 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16756 if(cspell->spellId)
16758 data << uint16(cspell->spellId);
16759 data << uint16(cspell->active);
16764 uint8 count = 0;
16765 data << uint8(count); // cooldowns count
16767 GetSession()->SendPacket(&data);
16770 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16772 if (!mod || !spellInfo)
16773 return false;
16775 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16777 // prevent apply to any spell except spell that trigger expire
16778 if(spell)
16780 if(mod->lastAffected != spell)
16781 return false;
16783 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16784 return false;
16787 return spellmgr.IsAffectedByMod(spellInfo, mod);
16790 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16792 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16794 for(int eff=0;eff<96;++eff)
16796 uint64 _mask = 0;
16797 uint64 _mask2= 0;
16798 if (eff<64) _mask = uint64(1) << (eff- 0);
16799 else _mask2= uint64(1) << (eff-64);
16800 if ( mod->mask & _mask || mod->mask2 & _mask2)
16802 int32 val = 0;
16803 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16805 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16806 val += (*itr)->value;
16808 val += apply ? mod->value : -(mod->value);
16809 WorldPacket data(Opcode, (1+1+4));
16810 data << uint8(eff);
16811 data << uint8(mod->op);
16812 data << int32(val);
16813 SendDirectMessage(&data);
16817 if (apply)
16818 m_spellMods[mod->op].push_back(mod);
16819 else
16821 if (mod->charges == -1)
16822 --m_SpellModRemoveCount;
16823 m_spellMods[mod->op].remove(mod);
16824 delete mod;
16828 void Player::RemoveSpellMods(Spell const* spell)
16830 if(!spell || (m_SpellModRemoveCount == 0))
16831 return;
16833 for(int i=0;i<MAX_SPELLMOD;++i)
16835 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16837 SpellModifier *mod = *itr;
16838 ++itr;
16840 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16842 RemoveAurasDueToSpell(mod->spellId);
16843 if (m_spellMods[i].empty())
16844 break;
16845 else
16846 itr = m_spellMods[i].begin();
16852 // send Proficiency
16853 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16855 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16856 data << pr1 << pr2;
16857 GetSession()->SendPacket (&data);
16860 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16862 QueryResult *result = NULL;
16863 if(type==10)
16864 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16865 else
16866 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16867 if(result)
16869 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.
16870 { // and SendPetitionQueryOpcode reads data from the DB
16871 Field *fields = result->Fetch();
16872 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16873 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16875 // send update if charter owner in game
16876 Player* owner = objmgr.GetPlayer(ownerguid);
16877 if(owner)
16878 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16880 } while ( result->NextRow() );
16882 delete result;
16884 if(type==10)
16885 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16886 else
16887 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16890 CharacterDatabase.BeginTransaction();
16891 if(type == 10)
16893 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16894 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16896 else
16898 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16899 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16901 CharacterDatabase.CommitTransaction();
16904 void Player::LeaveAllArenaTeams(uint64 guid)
16906 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));
16907 if(!result)
16908 return;
16912 Field *fields = result->Fetch();
16913 uint32 at_id = fields[0].GetUInt32();
16914 if(at_id != 0)
16916 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16917 if(at)
16918 at->DelMember(guid);
16920 } while (result->NextRow());
16922 delete result;
16925 void Player::SetRestBonus (float rest_bonus_new)
16927 // Prevent resting on max level
16928 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16929 rest_bonus_new = 0;
16931 if(rest_bonus_new < 0)
16932 rest_bonus_new = 0;
16934 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16936 if(rest_bonus_new > rest_bonus_max)
16937 m_rest_bonus = rest_bonus_max;
16938 else
16939 m_rest_bonus = rest_bonus_new;
16941 // update data for client
16942 if(m_rest_bonus>10)
16943 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16944 else if(m_rest_bonus<=1)
16945 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16947 //RestTickUpdate
16948 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16951 void Player::HandleStealthedUnitsDetection()
16953 std::list<Unit*> stealthedUnits;
16955 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16956 Cell cell(p);
16957 cell.data.Part.reserved = ALL_DISTRICT;
16958 cell.SetNoCreate();
16960 MaNGOS::AnyStealthedCheck u_check;
16961 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16963 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16964 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16966 CellLock<GridReadGuard> cell_lock(cell, p);
16967 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16968 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16970 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16972 if((*i)==this)
16974 i = stealthedUnits.erase(i);
16975 continue;
16978 if ((*i)->isVisibleForOrDetect(this,true))
16981 (*i)->SendUpdateToPlayer(this);
16982 m_clientGUIDs.insert((*i)->GetGUID());
16984 #ifdef MANGOS_DEBUG
16985 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16986 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16987 #endif
16989 // target aura duration for caster show only if target exist at caster client
16990 // send data at target visibility change (adding to client)
16991 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16992 SendAurasForTarget(*i);
16994 i = stealthedUnits.erase(i);
16995 continue;
16998 ++i;
17002 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
17004 if(nodes.size() < 2)
17005 return false;
17007 // not let cheating with start flight mounted
17008 if(IsMounted())
17010 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17011 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17012 GetSession()->SendPacket(&data);
17013 return false;
17016 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17018 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17019 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17020 GetSession()->SendPacket(&data);
17021 return false;
17024 // 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
17025 if(GetSession()->isLogingOut() ||
17026 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
17027 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
17028 IsNonMeleeSpellCasted(false) ||
17029 isInCombat())
17031 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17032 data << uint32(ERR_TAXIPLAYERBUSY);
17033 GetSession()->SendPacket(&data);
17034 return false;
17037 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17038 return false;
17040 uint32 sourcenode = nodes[0];
17042 // starting node too far away (cheat?)
17043 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17044 if( !node || node->map_id != GetMapId() ||
17045 (node->x - GetPositionX())*(node->x - GetPositionX())+
17046 (node->y - GetPositionY())*(node->y - GetPositionY())+
17047 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17048 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
17050 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17051 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17052 GetSession()->SendPacket(&data);
17053 return false;
17056 // Prepare to flight start now
17058 // stop combat at start taxi flight if any
17059 CombatStop();
17061 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17062 TradeCancel(true);
17064 // clean not finished taxi path if any
17065 m_taxi.ClearTaxiDestinations();
17067 // 0 element current node
17068 m_taxi.AddTaxiDestination(sourcenode);
17070 // fill destinations path tail
17071 uint32 sourcepath = 0;
17072 uint32 totalcost = 0;
17074 uint32 prevnode = sourcenode;
17075 uint32 lastnode = 0;
17077 for(uint32 i = 1; i < nodes.size(); ++i)
17079 uint32 path, cost;
17081 lastnode = nodes[i];
17082 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17084 if(!path)
17086 m_taxi.ClearTaxiDestinations();
17087 return false;
17090 totalcost += cost;
17092 if(prevnode == sourcenode)
17093 sourcepath = path;
17095 m_taxi.AddTaxiDestination(lastnode);
17097 prevnode = lastnode;
17100 if(!mount_id) // if not provide then attempt use default.
17101 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
17103 if (mount_id == 0 || sourcepath == 0)
17105 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17106 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17107 GetSession()->SendPacket(&data);
17108 m_taxi.ClearTaxiDestinations();
17109 return false;
17112 uint32 money = GetMoney();
17114 if(npc)
17116 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17119 if(money < totalcost)
17121 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17122 data << uint32(ERR_TAXINOTENOUGHMONEY);
17123 GetSession()->SendPacket(&data);
17124 m_taxi.ClearTaxiDestinations();
17125 return false;
17128 //Checks and preparations done, DO FLIGHT
17129 ModifyMoney(-(int32)totalcost);
17131 // prevent stealth flight
17132 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17134 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17135 data << uint32(ERR_TAXIOK);
17136 GetSession()->SendPacket(&data);
17138 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17140 GetSession()->SendDoFlight(mount_id, sourcepath);
17142 return true;
17145 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17147 // last check 2.0.10
17148 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17149 data << GetGUID();
17150 data << uint8(0x0); // flags (0x1, 0x2)
17151 time_t curTime = time(NULL);
17152 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17154 if (itr->second->state == PLAYERSPELL_REMOVED)
17155 continue;
17156 uint32 unSpellId = itr->first;
17157 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17158 if (!spellInfo)
17160 ASSERT(spellInfo);
17161 continue;
17164 // Not send cooldown for this spells
17165 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17166 continue;
17168 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17170 data << unSpellId;
17171 data << unTimeMs; // in m.secs
17172 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
17175 GetSession()->SendPacket(&data);
17178 void Player::InitDataForForm(bool reapplyMods)
17180 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17181 if(ssEntry && ssEntry->attackSpeed)
17183 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17184 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17185 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17187 else
17188 SetRegularAttackTime();
17190 switch(m_form)
17192 case FORM_CAT:
17194 if(getPowerType()!=POWER_ENERGY)
17195 setPowerType(POWER_ENERGY);
17196 break;
17198 case FORM_BEAR:
17199 case FORM_DIREBEAR:
17201 if(getPowerType()!=POWER_RAGE)
17202 setPowerType(POWER_RAGE);
17203 break;
17205 default: // 0, for example
17207 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17208 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17209 setPowerType(Powers(cEntry->powerType));
17210 break;
17214 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17215 if (!reapplyMods)
17216 UpdateEquipSpellsAtFormChange();
17218 UpdateAttackPowerAndDamage();
17219 UpdateAttackPowerAndDamage(true);
17222 // Return true is the bought item has a max count to force refresh of window by caller
17223 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17225 // cheating attempt
17226 if(count < 1) count = 1;
17228 if(!isAlive())
17229 return false;
17231 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17232 if( !pProto )
17234 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17235 return false;
17238 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
17239 if (!pCreature)
17241 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17242 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17243 return false;
17246 VendorItemData const* vItems = pCreature->GetVendorItems();
17247 if(!vItems || vItems->Empty())
17249 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17250 return false;
17253 size_t vendor_slot = vItems->FindItemSlot(item);
17254 if(vendor_slot >= vItems->GetItemCount())
17256 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17257 return false;
17260 VendorItem const* crItem = vItems->m_items[vendor_slot];
17262 // check current item amount if it limited
17263 if( crItem->maxcount != 0 )
17265 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17267 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17268 return false;
17272 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17274 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17275 return false;
17278 if(crItem->ExtendedCost)
17280 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17281 if(!iece)
17283 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17284 return false;
17287 // honor points price
17288 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17290 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17291 return false;
17294 // arena points price
17295 if(GetArenaPoints() < (iece->reqarenapoints * count))
17297 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17298 return false;
17301 // item base price
17302 for (uint8 i = 0; i < 5; ++i)
17304 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17306 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17307 return false;
17311 // check for personal arena rating requirement
17312 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17314 // probably not the proper equip err
17315 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17316 return false;
17320 uint32 price = pProto->BuyPrice * count;
17322 // reputation discount
17323 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17325 if( GetMoney() < price )
17327 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17328 return false;
17331 uint8 bag = 0; // init for case invalid bagGUID
17333 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17335 Bag *pBag;
17336 if( bagguid == GetGUID() )
17338 bag = INVENTORY_SLOT_BAG_0;
17340 else
17342 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17344 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17345 if( pBag )
17347 if( bagguid == pBag->GetGUID() )
17349 bag = i;
17350 break;
17357 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17359 ItemPosCountVec dest;
17360 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17361 if( msg != EQUIP_ERR_OK )
17363 SendEquipError( msg, NULL, NULL );
17364 return false;
17367 ModifyMoney( -(int32)price );
17368 if(crItem->ExtendedCost) // case for new honor system
17370 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17371 if(iece->reqhonorpoints)
17372 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17373 if(iece->reqarenapoints)
17374 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17375 for (uint8 i = 0; i < 5; ++i)
17377 if(iece->reqitem[i])
17378 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17382 if(Item *it = StoreNewItem( dest, item, true ))
17384 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17386 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17387 data << pCreature->GetGUID();
17388 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17389 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17390 data << (uint32)count;
17391 GetSession()->SendPacket(&data);
17393 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17396 else if( IsEquipmentPos( bag, slot ) )
17398 if(pProto->BuyCount * count != 1)
17400 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17401 return false;
17404 uint16 dest;
17405 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17406 if( msg != EQUIP_ERR_OK )
17408 SendEquipError( msg, NULL, NULL );
17409 return false;
17412 ModifyMoney( -(int32)price );
17413 if(crItem->ExtendedCost) // case for new honor system
17415 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17416 if(iece->reqhonorpoints)
17417 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17418 if(iece->reqarenapoints)
17419 ModifyArenaPoints( - int32(iece->reqarenapoints));
17420 for (uint8 i = 0; i < 5; ++i)
17422 if(iece->reqitem[i])
17423 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17427 if(Item *it = EquipNewItem( dest, item, true ))
17429 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17431 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17432 data << pCreature->GetGUID();
17433 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17434 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17435 data << (uint32)count;
17436 GetSession()->SendPacket(&data);
17438 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17440 AutoUnequipOffhandIfNeed();
17443 else
17445 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17446 return false;
17449 return crItem->maxcount!=0;
17452 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17454 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17455 // the personal rating of the arena team must match the required limit as well
17456 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17457 uint32 max_personal_rating = 0;
17458 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17460 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17462 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17463 uint32 t_rating = at->GetRating();
17464 p_rating = p_rating<t_rating? p_rating : t_rating;
17465 if(max_personal_rating < p_rating)
17466 max_personal_rating = p_rating;
17469 return max_personal_rating;
17472 void Player::UpdateHomebindTime(uint32 time)
17474 // GMs never get homebind timer online
17475 if (m_InstanceValid || isGameMaster())
17477 if(m_HomebindTimer) // instance valid, but timer not reset
17479 // hide reminder
17480 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17481 data << uint32(0);
17482 data << uint32(0);
17483 GetSession()->SendPacket(&data);
17485 // instance is valid, reset homebind timer
17486 m_HomebindTimer = 0;
17488 else if (m_HomebindTimer > 0)
17490 if (time >= m_HomebindTimer)
17492 // teleport to homebind location
17493 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17495 else
17496 m_HomebindTimer -= time;
17498 else
17500 // instance is invalid, start homebind timer
17501 m_HomebindTimer = 60000;
17502 // send message to player
17503 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17504 data << m_HomebindTimer;
17505 data << uint32(1);
17506 GetSession()->SendPacket(&data);
17507 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17511 void Player::UpdatePvP(bool state, bool ovrride)
17513 if(!state || ovrride)
17515 SetPvP(state);
17516 if(Pet* pet = GetPet())
17517 pet->SetPvP(state);
17518 if(Unit* charmed = GetCharm())
17519 charmed->SetPvP(state);
17521 pvpInfo.endTimer = 0;
17523 else
17525 if(pvpInfo.endTimer != 0)
17526 pvpInfo.endTimer = time(NULL);
17527 else
17529 SetPvP(state);
17531 if(Pet* pet = GetPet())
17532 pet->SetPvP(state);
17533 if(Unit* charmed = GetCharm())
17534 charmed->SetPvP(state);
17539 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17541 SpellCooldown sc;
17542 sc.end = end_time;
17543 sc.itemid = itemid;
17544 m_spellCooldowns[spellid] = sc;
17547 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17549 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17550 return;
17552 // Get spell cooldown
17553 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17554 // Apply spellmods
17555 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17556 if (cooldown < 0)
17557 cooldown = 0;
17558 // Add cooldown
17559 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17560 // Send activate
17561 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17562 data << spellInfo->Id;
17563 data << GetGUID();
17564 SendDirectMessage(&data);
17566 //slot to be excluded while counting
17567 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17569 if(!enchantmentcondition)
17570 return true;
17572 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17574 if(!Condition)
17575 return true;
17577 uint8 curcount[4] = {0, 0, 0, 0};
17579 //counting current equipped gem colors
17580 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17582 if(i == slot)
17583 continue;
17584 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17585 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17587 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17589 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17590 if(!enchant_id)
17591 continue;
17593 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17594 if(!enchantEntry)
17595 continue;
17597 uint32 gemid = enchantEntry->GemID;
17598 if(!gemid)
17599 continue;
17601 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17602 if(!gemProto)
17603 continue;
17605 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17606 if(!gemProperty)
17607 continue;
17609 uint8 GemColor = gemProperty->color;
17611 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17613 if(tmpcolormask & GemColor)
17614 ++curcount[b];
17620 bool activate = true;
17622 for(int i = 0; i < 5; i++)
17624 if(!Condition->Color[i])
17625 continue;
17627 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17629 // if have <CompareColor> use them as count, else use <value> from Condition
17630 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17632 switch(Condition->Comparator[i])
17634 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17635 activate &= (_cur_gem < _cmp_gem) ? true : false;
17636 break;
17637 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17638 activate &= (_cur_gem > _cmp_gem) ? true : false;
17639 break;
17640 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17641 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17642 break;
17646 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");
17648 return activate;
17651 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17653 //cycle all equipped items
17654 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17656 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17657 if(slot == exceptslot)
17658 continue;
17660 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17662 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17663 continue;
17665 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17667 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17668 if(!enchant_id)
17669 continue;
17671 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17672 if(!enchantEntry)
17673 continue;
17675 uint32 condition = enchantEntry->EnchantmentCondition;
17676 if(condition)
17678 //was enchant active with/without item?
17679 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17680 //should it now be?
17681 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17683 // ignore item gem conditions
17684 //if state changed, (dis)apply enchant
17685 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17692 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17693 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17695 //cycle all equipped items
17696 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17698 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17699 if(slot == exceptslot)
17700 continue;
17702 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17704 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17705 continue;
17707 //cycle all (gem)enchants
17708 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17710 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17711 if(!enchant_id) //if no enchant go to next enchant(slot)
17712 continue;
17714 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17715 if(!enchantEntry)
17716 continue;
17718 //only metagems to be (de)activated, so only enchants with condition
17719 uint32 condition = enchantEntry->EnchantmentCondition;
17720 if(condition)
17721 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17726 void Player::LeaveBattleground(bool teleportToEntryPoint)
17728 if(BattleGround *bg = GetBattleGround())
17730 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17732 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17734 // call after remove to be sure that player resurrected for correct cast
17735 if(need_debuf)
17736 CastSpell(this, 26013, true); // Deserter
17740 bool Player::CanJoinToBattleground() const
17742 // check Deserter debuff
17743 if(GetDummyAura(26013))
17744 return false;
17746 return true;
17749 bool Player::CanReportAfkDueToLimit()
17751 // a player can complain about 15 people per 5 minutes
17752 if(m_bgAfkReportedCount >= 15)
17753 return false;
17754 ++m_bgAfkReportedCount;
17755 return true;
17758 ///This player has been blamed to be inactive in a battleground
17759 void Player::ReportedAfkBy(Player* reporter)
17761 BattleGround *bg = GetBattleGround();
17762 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17763 return;
17765 // check if player has 'Idle' or 'Inactive' debuff
17766 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17768 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17769 // 3 players have to complain to apply debuff
17770 if(m_bgAfkReporter.size() >= 3)
17772 // cast 'Idle' spell
17773 CastSpell(this, 43680, true);
17774 m_bgAfkReporter.clear();
17779 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17781 // gamemaster in GM mode see all, including ghosts
17782 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17783 return true;
17785 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17786 if (InBattleGround())
17788 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17789 return false;
17790 return true;
17793 // Live player see live player or dead player with not realized corpse
17794 if(pl->isAlive() || pl->m_deathTimer > 0)
17796 return isAlive() || m_deathTimer > 0;
17799 // Ghost see other friendly ghosts, that's for sure
17800 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17801 return true;
17803 // Dead player see live players near own corpse
17804 if(isAlive())
17806 Corpse *corpse = pl->GetCorpse();
17807 if(corpse)
17809 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17810 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17811 return true;
17815 // and not see any other
17816 return false;
17819 bool Player::IsVisibleGloballyFor( Player* u ) const
17821 if(!u)
17822 return false;
17824 // Always can see self
17825 if (u==this)
17826 return true;
17828 // Visible units, always are visible for all players
17829 if (GetVisibility() == VISIBILITY_ON)
17830 return true;
17832 // GMs are visible for higher gms (or players are visible for gms)
17833 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17834 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17836 // non faction visibility non-breakable for non-GMs
17837 if (GetVisibility() == VISIBILITY_OFF)
17838 return false;
17840 // non-gm stealth/invisibility not hide from global player lists
17841 return true;
17844 void Player::UpdateVisibilityOf(WorldObject* target)
17846 if(HaveAtClient(target))
17848 if(!target->isVisibleForInState(this,true))
17850 target->DestroyForPlayer(this);
17851 m_clientGUIDs.erase(target->GetGUID());
17853 #ifdef MANGOS_DEBUG
17854 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17855 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17856 #endif
17859 else
17861 if(target->isVisibleForInState(this,false))
17863 target->SendUpdateToPlayer(this);
17864 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17865 m_clientGUIDs.insert(target->GetGUID());
17867 #ifdef MANGOS_DEBUG
17868 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17869 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17870 #endif
17872 // target aura duration for caster show only if target exist at caster client
17873 // send data at target visibility change (adding to client)
17874 if(target!=this && target->isType(TYPEMASK_UNIT))
17875 SendAurasForTarget((Unit*)target);
17877 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17878 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17883 template<class T>
17884 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17886 s64.insert(target->GetGUID());
17889 template<>
17890 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17892 if(!target->IsTransport())
17893 s64.insert(target->GetGUID());
17896 template<class T>
17897 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17899 if(HaveAtClient(target))
17901 if(!target->isVisibleForInState(this,true))
17903 target->BuildOutOfRangeUpdateBlock(&data);
17904 m_clientGUIDs.erase(target->GetGUID());
17906 #ifdef MANGOS_DEBUG
17907 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17908 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));
17909 #endif
17912 else
17914 if(target->isVisibleForInState(this,false))
17916 visibleNow.insert(target);
17917 target->BuildUpdate(data_updates);
17918 target->BuildCreateUpdateBlockForPlayer(&data, this);
17919 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17921 #ifdef MANGOS_DEBUG
17922 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17923 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));
17924 #endif
17929 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17930 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17931 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17932 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17933 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17935 void Player::InitPrimaryProffesions()
17937 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17940 void Player::SendComboPoints()
17942 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17943 if (combotarget)
17945 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17946 data.append(combotarget->GetPackGUID());
17947 data << uint8(m_comboPoints);
17948 GetSession()->SendPacket(&data);
17952 void Player::AddComboPoints(Unit* target, int8 count)
17954 if(!count)
17955 return;
17957 // without combo points lost (duration checked in aura)
17958 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17960 if(target->GetGUID() == m_comboTarget)
17962 m_comboPoints += count;
17964 else
17966 if(m_comboTarget)
17967 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17968 target->RemoveComboPointHolder(GetGUIDLow());
17970 m_comboTarget = target->GetGUID();
17971 m_comboPoints = count;
17973 target->AddComboPointHolder(GetGUIDLow());
17976 if (m_comboPoints > 5) m_comboPoints = 5;
17977 if (m_comboPoints < 0) m_comboPoints = 0;
17979 SendComboPoints();
17982 void Player::ClearComboPoints()
17984 if(!m_comboTarget)
17985 return;
17987 // without combopoints lost (duration checked in aura)
17988 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17990 m_comboPoints = 0;
17992 SendComboPoints();
17994 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17995 target->RemoveComboPointHolder(GetGUIDLow());
17997 m_comboTarget = 0;
18000 void Player::SetGroup(Group *group, int8 subgroup)
18002 if(group == NULL) m_group.unlink();
18003 else
18005 // never use SetGroup without a subgroup unless you specify NULL for group
18006 assert(subgroup >= 0);
18007 m_group.link(group, this);
18008 m_group.setSubGroup((uint8)subgroup);
18012 void Player::SendInitialPacketsBeforeAddToMap()
18014 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18015 data << uint32(0); // unknown, may be rest state time or experience
18016 GetSession()->SendPacket(&data);
18018 // Homebind
18019 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18020 data << m_homebindX << m_homebindY << m_homebindZ;
18021 data << (uint32) m_homebindMapId;
18022 data << (uint32) m_homebindZoneId;
18023 GetSession()->SendPacket(&data);
18025 // SMSG_SET_PROFICIENCY
18026 // SMSG_UPDATE_AURA_DURATION
18028 // tutorial stuff
18029 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
18030 for (int i = 0; i < 8; ++i)
18031 data << uint32( GetTutorialInt(i) );
18032 GetSession()->SendPacket(&data);
18034 SendInitialSpells();
18036 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18037 data << uint32(0); // count, for(count) uint32;
18038 GetSession()->SendPacket(&data);
18040 SendInitialActionButtons();
18041 SendInitialReputations();
18042 m_achievementMgr.SendAllAchievementData();
18043 UpdateZone(GetZoneId());
18044 SendInitWorldStates();
18046 // SMSG_SET_AURA_SINGLE
18048 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18049 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18050 data << (float)0.01666667f; // game speed
18051 GetSession()->SendPacket( &data );
18053 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18054 data << uint32(0x00000000); // on blizz it increments periodically
18055 GetSession()->SendPacket(&data);
18057 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18058 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18059 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18061 m_mover = this;
18064 void Player::SendInitialPacketsAfterAddToMap()
18066 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18067 data << uint32(0x00000000); // on blizz it increments periodically
18068 GetSession()->SendPacket(&data);
18070 CastSpell(this, 836, true); // LOGINEFFECT
18072 // set some aura effects that send packet to player client after add player to map
18073 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18074 // same auras state lost at far teleport, send it one more time in this case also
18075 static const AuraType auratypes[] =
18077 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18078 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18079 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18081 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18083 Unit::AuraList const& auraList = GetAurasByType(*itr);
18084 if(!auraList.empty())
18085 auraList.front()->ApplyModifier(true,true);
18088 if(HasAuraType(SPELL_AURA_MOD_STUN))
18089 SetMovement(MOVE_ROOT);
18091 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18092 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18094 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
18095 data.append(GetPackGUID());
18096 data << (uint32)2;
18097 SendMessageToSet(&data,true);
18100 // setup BG group membership if need
18101 if(BattleGround* currentBg = GetBattleGround())
18103 // call for invited (join) or listed (relogin) and avoid other cases (GM teleport)
18104 if (IsInvitedForBattleGroundInstance(GetBattleGroundId()) ||
18105 currentBg->IsPlayerInBattleGround(GetGUID()))
18107 currentBg->PlayerRelogin(this);
18108 if(currentBg->GetMapId() == GetMapId()) // we teleported/login to/in bg
18110 uint32 team = currentBg->GetPlayerTeam(GetGUID());
18111 if(!team)
18112 team = GetTeam();
18113 Group* group = currentBg->GetBgRaid(team);
18114 if(!group) // first player joined
18116 group = new Group;
18117 currentBg->SetBgRaid(team, group);
18118 group->Create(GetGUIDLow(), GetName());
18120 else // raid already exist
18122 if(group->IsMember(GetGUID()))
18124 uint8 subgroup = group->GetMemberGroup(GetGUID());
18125 SetGroup(group, subgroup);
18127 else
18128 currentBg->GetBgRaid(team)->AddMember(GetGUID(), GetName());
18134 SendAurasForTarget(this);
18135 SendEnchantmentDurations(); // must be after add to map
18136 SendItemDurations(); // must be after add to map
18139 void Player::SendUpdateToOutOfRangeGroupMembers()
18141 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18142 return;
18143 if(Group* group = GetGroup())
18144 group->UpdatePlayerOutOfRange(this);
18146 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18147 m_auraUpdateMask = 0;
18148 if(Pet *pet = GetPet())
18149 pet->ResetAuraUpdateMask();
18152 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18154 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18155 data << uint32(mapid);
18156 data << uint8(reason); // transfer abort reason
18157 switch(reason)
18159 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18160 case TRANSFER_ABORT_DIFFICULTY:
18161 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18162 data << uint8(arg);
18163 break;
18165 GetSession()->SendPacket(&data);
18168 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18170 // type of warning, based on the time remaining until reset
18171 uint32 type;
18172 if(time > 3600)
18173 type = RAID_INSTANCE_WELCOME;
18174 else if(time > 900 && time <= 3600)
18175 type = RAID_INSTANCE_WARNING_HOURS;
18176 else if(time > 300 && time <= 900)
18177 type = RAID_INSTANCE_WARNING_MIN;
18178 else
18179 type = RAID_INSTANCE_WARNING_MIN_SOON;
18180 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18181 data << uint32(type);
18182 data << uint32(mapid);
18183 data << uint32(time);
18184 GetSession()->SendPacket(&data);
18187 void Player::ApplyEquipCooldown( Item * pItem )
18189 for(int i = 0; i <5; ++i)
18191 _Spell const& spellData = pItem->GetProto()->Spells[i];
18193 // no spell
18194 if( !spellData.SpellId )
18195 continue;
18197 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18198 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18199 continue;
18201 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18203 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18204 data << pItem->GetGUID();
18205 data << uint32(spellData.SpellId);
18206 GetSession()->SendPacket(&data);
18210 void Player::resetSpells()
18212 // not need after this call
18213 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18215 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18216 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18219 // make full copy of map (spells removed and marked as deleted at another spell remove
18220 // and we can't use original map for safe iterative with visit each spell at loop end
18221 PlayerSpellMap smap = GetSpellMap();
18223 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18224 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18226 learnDefaultSpells();
18227 learnQuestRewardedSpells();
18230 void Player::learnDefaultSpells()
18232 // learn default race/class spells
18233 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18234 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18236 uint32 tspell = *itr;
18237 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18238 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18239 addSpell(tspell,true,true,true,false);
18240 else // but send in normal spell in game learn case
18241 learnSpell(tspell,true);
18245 void Player::learnQuestRewardedSpells(Quest const* quest)
18247 uint32 spell_id = quest->GetRewSpellCast();
18249 // skip quests without rewarded spell
18250 if( !spell_id )
18251 return;
18253 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18254 if(!spellInfo)
18255 return;
18257 // check learned spells state
18258 bool found = false;
18259 for(int i=0; i < 3; ++i)
18261 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18263 found = true;
18264 break;
18268 // skip quests with not teaching spell or already known spell
18269 if(!found)
18270 return;
18272 // prevent learn non first rank unknown profession and second specialization for same profession)
18273 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18274 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18276 // not have first rank learned (unlearned prof?)
18277 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18278 if( !HasSpell(first_spell) )
18279 return;
18281 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18282 if(!learnedInfo)
18283 return;
18285 // specialization
18286 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18288 // search other specialization for same prof
18289 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18291 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18292 continue;
18294 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18295 if(!itrInfo)
18296 return;
18298 // compare only specializations
18299 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18300 continue;
18302 // compare same chain spells
18303 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18304 continue;
18306 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18307 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18308 return;
18313 CastSpell( this, spell_id, true);
18316 void Player::learnQuestRewardedSpells()
18318 // learn spells received from quest completing
18319 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18321 // skip no rewarded quests
18322 if(!itr->second.m_rewarded)
18323 continue;
18325 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18326 if( !quest )
18327 continue;
18329 learnQuestRewardedSpells(quest);
18333 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18335 uint32 raceMask = getRaceMask();
18336 uint32 classMask = getClassMask();
18337 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18339 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18340 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18341 continue;
18342 // Check race if set
18343 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18344 continue;
18345 // Check class if set
18346 if (pAbility->classmask && !(pAbility->classmask & classMask))
18347 continue;
18349 if (sSpellStore.LookupEntry(pAbility->spellId))
18351 // need unlearn spell
18352 if (skill_value < pAbility->req_skill_value)
18353 removeSpell(pAbility->spellId);
18354 // need learn
18355 else if (!IsInWorld())
18356 addSpell(pAbility->spellId,true,true,true,false);
18357 else
18358 learnSpell(pAbility->spellId,true);
18363 void Player::SendAurasForTarget(Unit *target)
18365 if(target->GetVisibleAuras()->empty()) // speedup things
18366 return;
18368 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18369 data.append(target->GetPackGUID());
18371 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18372 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18374 for(uint32 j = 0; j < 3; ++j)
18376 if(Aura *aura = target->GetAura(itr->second, j))
18378 data << uint8(aura->GetAuraSlot());
18379 data << uint32(aura->GetId());
18381 if(aura->GetId())
18383 uint8 auraFlags = aura->GetAuraFlags();
18384 // flags
18385 data << uint8(auraFlags);
18386 // level
18387 data << uint8(aura->GetAuraLevel());
18388 // charges
18389 data << uint8(aura->GetAuraCharges());
18391 if(!(auraFlags & AFLAG_NOT_CASTER))
18393 data << uint8(0); // packed GUID of someone (caster?)
18396 if(auraFlags & AFLAG_DURATION) // include aura duration
18398 data << uint32(aura->GetAuraMaxDuration());
18399 data << uint32(aura->GetAuraDuration());
18402 break;
18407 GetSession()->SendPacket(&data);
18410 void Player::SetDailyQuestStatus( uint32 quest_id )
18412 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18414 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18416 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18417 m_lastDailyQuestTime = time(NULL); // last daily quest time
18418 m_DailyQuestChanged = true;
18419 break;
18424 void Player::ResetDailyQuestStatus()
18426 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18427 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18429 // DB data deleted in caller
18430 m_DailyQuestChanged = false;
18431 m_lastDailyQuestTime = 0;
18434 BattleGround* Player::GetBattleGround() const
18436 if(GetBattleGroundId()==0)
18437 return NULL;
18439 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18442 bool Player::InArena() const
18444 BattleGround *bg = GetBattleGround();
18445 if(!bg || !bg->isArena())
18446 return false;
18448 return true;
18451 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18453 // get a template bg instead of running one
18454 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18455 if(!bg)
18456 return false;
18458 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18459 return false;
18461 return true;
18464 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18466 if(queue_id < 1)
18467 return 0;
18469 if(queue_id >=7)
18470 queue_id = 7;
18472 return 10*(queue_id+1);
18475 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18477 if(queue_id >=7)
18478 return 255; // hardcoded max level
18480 return 10*(queue_id+2)-1;
18483 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18485 uint32 level = getLevel();
18486 if(level <= 19)
18487 return 0;
18488 else if (level > 79)
18489 return 7;
18490 else
18491 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18493 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18494 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18495 assert(bg);
18496 return (getLevel() - bg->GetMinLevel()) / 10;*/
18499 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18501 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18502 if(!vendor_faction)
18503 return 1.0f;
18505 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18506 if(rank <= REP_NEUTRAL)
18507 return 1.0f;
18509 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18512 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18514 uint32 racemask = getRaceMask();
18515 uint32 classmask = getClassMask();
18517 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18518 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18519 if(lower==upper)
18520 return true;
18522 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18524 // skip wrong race skills
18525 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18526 continue;
18528 // skip wrong class skills
18529 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18530 continue;
18532 return true;
18535 return false;
18538 bool Player::HasQuestForGO(int32 GOId)
18540 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18542 QuestStatusData qs=i->second;
18543 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18545 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18546 if(!qinfo)
18547 continue;
18549 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18550 continue;
18552 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18554 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18555 continue;
18557 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18558 return true;
18562 return false;
18565 void Player::UpdateForQuestsGO()
18567 if(m_clientGUIDs.empty())
18568 return;
18570 UpdateData udata;
18571 WorldPacket packet;
18572 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18574 if(IS_GAMEOBJECT_GUID(*itr))
18576 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18577 if(obj)
18578 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18581 udata.BuildPacket(&packet);
18582 GetSession()->SendPacket(&packet);
18585 void Player::SummonIfPossible(bool agree)
18587 if(!agree)
18589 m_summon_expire = 0;
18590 return;
18593 // expire and auto declined
18594 if(m_summon_expire < time(NULL))
18595 return;
18597 // stop taxi flight at summon
18598 if(isInFlight())
18600 GetMotionMaster()->MovementExpired();
18601 m_taxi.ClearTaxiDestinations();
18604 // drop flag at summon
18605 if(BattleGround *bg = GetBattleGround())
18606 bg->EventPlayerDroppedFlag(this);
18608 m_summon_expire = 0;
18610 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18613 void Player::RemoveItemDurations( Item *item )
18615 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18617 if(*itr==item)
18619 m_itemDuration.erase(itr);
18620 break;
18625 void Player::AddItemDurations( Item *item )
18627 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18629 m_itemDuration.push_back(item);
18630 item->SendTimeUpdate(this);
18634 void Player::AutoUnequipOffhandIfNeed()
18636 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18637 if(!offItem)
18638 return;
18640 // need unequip for 2h-weapon without TitanGrip
18641 if (!IsTwoHandUsed())
18642 return;
18644 ItemPosCountVec off_dest;
18645 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18646 if( off_msg == EQUIP_ERR_OK )
18648 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18649 StoreItem( off_dest, offItem, true );
18651 else
18653 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18657 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18659 if(spellInfo->EquippedItemClass < 0)
18660 return true;
18662 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18663 // for optimize check 2 used cases only
18664 switch(spellInfo->EquippedItemClass)
18666 case ITEM_CLASS_WEAPON:
18668 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18669 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18670 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18671 return true;
18672 break;
18674 case ITEM_CLASS_ARMOR:
18676 // tabard not have dependent spells
18677 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18678 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18679 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18680 return true;
18682 // shields can be equipped to offhand slot
18683 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18684 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18685 return true;
18687 // ranged slot can have some armor subclasses
18688 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18689 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18690 return true;
18692 break;
18694 default:
18695 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18696 break;
18699 return false;
18702 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18704 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18705 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18706 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18707 return true;
18709 // Check no reagent use mask
18710 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18711 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18712 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18713 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18714 return true;
18716 return false;
18719 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18721 AuraMap& auras = GetAuras();
18722 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18724 Aura* aura = itr->second;
18726 // skip passive (passive item dependent spells work in another way) and not self applied auras
18727 SpellEntry const* spellInfo = aura->GetSpellProto();
18728 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18730 ++itr;
18731 continue;
18734 // skip if not item dependent or have alternative item
18735 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18737 ++itr;
18738 continue;
18741 // no alt item, remove aura, restart check
18742 RemoveAurasDueToSpell(aura->GetId());
18743 itr = auras.begin();
18746 // currently casted spells can be dependent from item
18747 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18749 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18750 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18751 InterruptSpell(i);
18755 uint32 Player::GetResurrectionSpellId()
18757 // search priceless resurrection possibilities
18758 uint32 prio = 0;
18759 uint32 spell_id = 0;
18760 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18761 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18763 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18764 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18766 switch((*itr)->GetId())
18768 case 20707: spell_id = 3026; break; // rank 1
18769 case 20762: spell_id = 20758; break; // rank 2
18770 case 20763: spell_id = 20759; break; // rank 3
18771 case 20764: spell_id = 20760; break; // rank 4
18772 case 20765: spell_id = 20761; break; // rank 5
18773 case 27239: spell_id = 27240; break; // rank 6
18774 case 47883: spell_id = 47882; break; // rank 7
18775 default:
18776 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18777 continue;
18780 prio = 3;
18782 // Twisting Nether // prio: 2 (max)
18783 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18785 prio = 2;
18786 spell_id = 23700;
18790 // Reincarnation (passive spell) // prio: 1
18791 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18792 spell_id = 21169;
18794 return spell_id;
18797 // Used in triggers for check "Only to targets that grant experience or honor" req
18798 bool Player::isHonorOrXPTarget(Unit* pVictim)
18800 uint32 v_level = pVictim->getLevel();
18801 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18803 // Victim level less gray level
18804 if(v_level<=k_grey)
18805 return false;
18807 if(pVictim->GetTypeId() == TYPEID_UNIT)
18809 if (((Creature*)pVictim)->isTotem() ||
18810 ((Creature*)pVictim)->isPet() ||
18811 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18812 return false;
18814 return true;
18817 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18819 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18821 // prepare data for near group iteration (PvP and !PvP cases)
18822 uint32 xp = 0;
18823 bool honored_kill = false;
18825 if(Group *pGroup = GetGroup())
18827 uint32 count = 0;
18828 uint32 sum_level = 0;
18829 Player* member_with_max_level = NULL;
18830 Player* not_gray_member_with_max_level = NULL;
18832 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18834 if(member_with_max_level)
18836 /// not get Xp in PvP or no not gray players in group
18837 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18839 /// skip in check PvP case (for speed, not used)
18840 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18841 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18842 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18844 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18846 Player* pGroupGuy = itr->getSource();
18847 if(!pGroupGuy)
18848 continue;
18850 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18851 continue; // member (alive or dead) or his corpse at req. distance
18853 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18854 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18855 honored_kill = true;
18857 // xp and reputation only in !PvP case
18858 if(!PvP)
18860 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18862 // if is in dungeon then all receive full reputation at kill
18863 // rewarded any alive/dead/near_corpse group member
18864 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18866 // XP updated only for alive group member
18867 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18868 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18870 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18872 pGroupGuy->GiveXP(itr_xp, pVictim);
18873 if(Pet* pet = pGroupGuy->GetPet())
18874 pet->GivePetXP(itr_xp/2);
18877 // quest objectives updated only for alive group member or dead but with not released body
18878 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18880 // normal creature (not pet/etc) can be only in !PvP case
18881 if(pVictim->GetTypeId()==TYPEID_UNIT)
18882 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18888 else // if (!pGroup)
18890 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18892 // honor can be in PvP and !PvP (racial leader) cases
18893 if(RewardHonor(pVictim,1))
18894 honored_kill = true;
18896 // xp and reputation only in !PvP case
18897 if(!PvP)
18899 RewardReputation(pVictim,1);
18900 GiveXP(xp, pVictim);
18902 if(Pet* pet = GetPet())
18903 pet->GivePetXP(xp);
18905 // normal creature (not pet/etc) can be only in !PvP case
18906 if(pVictim->GetTypeId()==TYPEID_UNIT)
18907 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18910 return xp || honored_kill;
18913 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18915 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18916 return true;
18918 if(isAlive())
18919 return false;
18921 Corpse* corpse = GetCorpse();
18922 if(!corpse)
18923 return false;
18925 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18928 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18930 Item* item = GetWeaponForAttack(attType,true);
18932 // unarmed only with base attack
18933 if(attType != BASE_ATTACK && !item)
18934 return 0;
18936 // weapon skill or (unarmed for base attack)
18937 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18938 return GetBaseSkillValue(skill);
18941 void Player::ResurectUsingRequestData()
18943 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18944 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18946 ResurrectPlayer(0.0f,false);
18948 if(GetMaxHealth() > m_resurrectHealth)
18949 SetHealth( m_resurrectHealth );
18950 else
18951 SetHealth( GetMaxHealth() );
18953 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18954 SetPower(POWER_MANA, m_resurrectMana );
18955 else
18956 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18958 SetPower(POWER_RAGE, 0 );
18960 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18962 SpawnCorpseBones();
18965 void Player::SetClientControl(Unit* target, uint8 allowMove)
18967 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18968 data.append(target->GetPackGUID());
18969 data << uint8(allowMove);
18970 GetSession()->SendPacket(&data);
18973 void Player::UpdateZoneDependentAuras( uint32 newZone )
18975 // remove new continent flight forms
18976 if( !IsAllowUseFlyMountsHere() )
18978 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18979 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18982 // Some spells applied at enter into zone (with subzones)
18983 switch(newZone)
18985 case 2367: // Old Hillsbrad Foothills
18987 // Human Illusion
18988 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18989 uint32 spellid = 0;
18990 // all horde races
18991 if( GetTeam() == HORDE )
18992 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18993 // and some alliance races
18994 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18995 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18997 if(spellid && !HasAura(spellid,0) )
18998 CastSpell(this,spellid,true);
18999 break;
19004 void Player::UpdateAreaDependentAuras( uint32 newArea )
19006 // remove auras from spells with area limitations
19007 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19009 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19010 if(GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,GetBattleGroundId())!=0)
19011 RemoveAura(iter);
19012 else
19013 ++iter;
19016 // some auras applied at subzone enter
19017 switch(newArea)
19019 // Dragonmaw Illusion
19020 case 3759: // Netherwing Ledge
19021 case 3939: // Dragonmaw Fortress
19022 case 3966: // Dragonmaw Base Camp
19023 if( GetDummyAura(40214) )
19025 if( !HasAura(40216,0) )
19026 CastSpell(this,40216,true);
19027 if( !HasAura(42016,0) )
19028 CastSpell(this,42016,true);
19030 break;
19031 // Dominion Over Acherus
19032 case 4281: // Acherus: The Ebon Hold
19033 case 4342: // Acherus: The Ebon Hold
19034 if( HasSpell(51721) )
19035 if( !HasAura(51721,0) )
19036 CastSpell(this,51721,true);
19037 break;
19038 // Mist of the Kvaldir
19039 case 4028: //Riplash Strand
19040 case 4029: //Riplash Ruins
19041 case 4106: //Garrosh's Landing
19042 case 4031: //Pal'ea
19043 CastSpell(this,54119,true);
19044 break;
19048 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19050 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19051 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19053 return copseReclaimDelay[0];
19056 time_t now = time(NULL);
19057 // 0..2 full period
19058 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19059 return copseReclaimDelay[count];
19062 void Player::UpdateCorpseReclaimDelay()
19064 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19066 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19067 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19068 return;
19070 time_t now = time(NULL);
19071 if(now < m_deathExpireTime)
19073 // full and partly periods 1..3
19074 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19075 if(count < MAX_DEATH_COUNT)
19076 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19077 else
19078 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19080 else
19081 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19084 void Player::SendCorpseReclaimDelay(bool load)
19086 Corpse* corpse = GetCorpse();
19087 if(!corpse)
19088 return;
19090 uint32 delay;
19091 if(load)
19093 if(corpse->GetGhostTime() > m_deathExpireTime)
19094 return;
19096 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19098 uint32 count;
19099 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19100 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19102 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19103 if(count>=MAX_DEATH_COUNT)
19104 count = MAX_DEATH_COUNT-1;
19106 else
19107 count=0;
19109 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19111 time_t now = time(NULL);
19112 if(now >= expected_time)
19113 return;
19115 delay = expected_time-now;
19117 else
19118 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19120 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19121 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19122 data << uint32(delay*1000);
19123 GetSession()->SendPacket( &data );
19126 Player* Player::GetNextRandomRaidMember(float radius)
19128 Group *pGroup = GetGroup();
19129 if(!pGroup)
19130 return NULL;
19132 std::vector<Player*> nearMembers;
19133 nearMembers.reserve(pGroup->GetMembersCount());
19135 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19137 Player* Target = itr->getSource();
19139 // IsHostileTo check duel and controlled by enemy
19140 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19141 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19142 nearMembers.push_back(Target);
19145 if (nearMembers.empty())
19146 return NULL;
19148 uint32 randTarget = urand(0,nearMembers.size()-1);
19149 return nearMembers[randTarget];
19152 PartyResult Player::CanUninviteFromGroup() const
19154 const Group* grp = GetGroup();
19155 if(!grp)
19156 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19158 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19159 return PARTY_RESULT_YOU_NOT_LEADER;
19161 if(InBattleGround())
19162 return PARTY_RESULT_INVITE_RESTRICTED;
19164 return PARTY_RESULT_OK;
19167 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19169 float water_z = m->GetWaterLevel(x,y);
19170 float terrain_z = m->GetHeight(x,y,z, false); // use .map base surface height
19171 uint8 flag1 = m->GetTerrainType(x,y);
19173 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19174 if (terrain_z <= INVALID_HEIGHT || z < (terrain_z-2) || z > (water_z - 2) )
19175 m_isunderwater &= ~UNDERWATER_INWATER;
19176 else if ((z < (water_z - 2)) && (flag1 & 0x01))
19177 m_isunderwater |= UNDERWATER_INWATER;
19179 //!in lava check, anywhere under lava level
19180 if ((terrain_z <= INVALID_HEIGHT || z < (terrain_z - 0)) && (flag1 == 0x00) && IsInWater())
19181 m_isunderwater |= UNDERWATER_INLAVA;
19182 else
19183 m_isunderwater &= ~UNDERWATER_INLAVA;
19186 void Player::SetCanParry( bool value )
19188 if(m_canParry==value)
19189 return;
19191 m_canParry = value;
19192 UpdateParryPercentage();
19195 void Player::SetCanBlock( bool value )
19197 if(m_canBlock==value)
19198 return;
19200 m_canBlock = value;
19201 UpdateBlockPercentage();
19204 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19206 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19207 if(itr->pos == pos)
19208 return true;
19210 return false;
19213 bool Player::isAllowUseBattleGroundObject()
19215 return ( //InBattleGround() && // in battleground - not need, check in other cases
19216 !IsMounted() && // not mounted
19217 !HasStealthAura() && // not stealthed
19218 !HasInvisibilityAura() && // not invisible
19219 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19220 isAlive() // live player
19224 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19226 uint32 level = getLevel();
19228 if(level > GT_MAX_LEVEL)
19229 level = GT_MAX_LEVEL; // max level in this dbc
19231 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19232 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19233 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19235 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19236 return 0;
19238 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19240 if(!bsc) // shouldn't happen
19241 return 0xFFFFFFFF;
19243 float cost = 0;
19245 if(hairstyle != newhairstyle)
19246 cost += bsc->cost; // full price
19248 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19249 cost += bsc->cost * 0.5f; // +1/2 of price
19251 if(facialhair != newfacialhair)
19252 cost += bsc->cost * 0.75f; // +3/4 of price
19254 return uint32(cost);
19257 void Player::InitGlyphsForLevel()
19259 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19260 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19261 if(gs->Order)
19262 SetGlyphSlot(gs->Order - 1, gs->Id);
19264 uint32 level = getLevel();
19265 uint32 value = 0;
19267 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19268 if(level >= 15)
19269 value |= (0x01 | 0x02);
19270 if(level >= 30)
19271 value |= 0x08;
19272 if(level >= 50)
19273 value |= 0x04;
19274 if(level >= 70)
19275 value |= 0x10;
19276 if(level >= 80)
19277 value |= 0x20;
19279 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19282 void Player::EnterVehicle(Vehicle *vehicle)
19284 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19285 if(!ve)
19286 return;
19288 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19289 if(!veSeat)
19290 return;
19292 vehicle->SetCharmerGUID(GetGUID());
19293 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19294 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19295 vehicle->setFaction(getFaction());
19297 SetCharm(vehicle); // charm
19298 SetFarSightGUID(vehicle->GetGUID()); // set view
19300 SetClientControl(vehicle, 1); // redirect controls to vehicle
19302 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19303 GetSession()->SendPacket(&data);
19305 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19306 data.append(GetPackGUID());
19307 data << uint32(0); // counter?
19308 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19309 data << uint16(0); // special flags
19310 data << uint32(getMSTime()); // time
19311 data << vehicle->GetPositionX(); // x
19312 data << vehicle->GetPositionY(); // y
19313 data << vehicle->GetPositionZ(); // z
19314 data << vehicle->GetOrientation(); // o
19315 // transport part, TODO: load/calculate seat offsets
19316 data << uint64(vehicle->GetGUID()); // transport guid
19317 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19318 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19319 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19320 data << float(0); // transport orientation
19321 data << uint32(getMSTime()); // transport time
19322 data << uint8(0); // seat
19323 // end of transport part
19324 data << uint32(0); // fall time
19325 GetSession()->SendPacket(&data);
19327 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19328 data << uint64(vehicle->GetGUID());
19329 data << uint32(0x00000000);
19330 data << uint32(0x00000000);
19331 data << uint32(0x00000101);
19333 for(uint32 i = 0; i < 10; ++i)
19334 data << uint16(0) << uint8(0) << uint8(i+8);
19336 data << uint8(0);
19337 data << uint8(0);
19338 GetSession()->SendPacket(&data);
19341 void Player::ExitVehicle(Vehicle *vehicle)
19343 vehicle->SetCharmerGUID(0);
19344 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19345 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19346 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19348 SetCharm(NULL);
19349 SetFarSightGUID(0);
19351 SetClientControl(vehicle, 0);
19353 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19354 data.append(GetPackGUID());
19355 data << uint32(0); // counter?
19356 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19357 data << uint16(0x40); // special flags
19358 data << uint32(getMSTime()); // time
19359 data << vehicle->GetPositionX(); // x
19360 data << vehicle->GetPositionY(); // y
19361 data << vehicle->GetPositionZ(); // z
19362 data << vehicle->GetOrientation(); // o
19363 data << uint32(0); // fall time
19364 GetSession()->SendPacket(&data);
19366 data.Initialize(SMSG_PET_SPELLS, 8+4);
19367 data << uint64(0);
19368 data << uint32(0);
19369 GetSession()->SendPacket(&data);
19371 // only for flyable vehicles?
19372 CastSpell(this, 45472, true); // Parachute
19375 bool Player::HasTitle(uint32 bitIndex)
19377 if (bitIndex > 128)
19378 return false;
19380 uint32 fieldIndexOffset = bitIndex/32;
19381 uint32 flag = 1 << (bitIndex%32);
19382 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19385 void Player::SetTitle(CharTitlesEntry const* title)
19387 uint32 fieldIndexOffset = title->bit_index/32;
19388 uint32 flag = 1 << (title->bit_index%32);
19389 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19392 void Player::ConvertRune(uint8 index, uint8 newType)
19394 SetCurrentRune(index, newType);
19396 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19397 data << uint8(index);
19398 data << uint8(newType);
19399 GetSession()->SendPacket(&data);
19402 void Player::ResyncRunes(uint8 count)
19404 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19405 for(uint32 i = 0; i < count; ++i)
19407 data << uint8(GetCurrentRune(i)); // rune type
19408 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19410 GetSession()->SendPacket(&data);
19413 void Player::AddRunePower(uint8 index)
19415 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19416 data << uint32(1 << index); // mask (0x00-0x3F probably)
19417 GetSession()->SendPacket(&data);
19420 void Player::InitRunes()
19422 if(getClass() != CLASS_DEATH_KNIGHT)
19423 return;
19425 m_runes = new Runes;
19427 m_runes->runeState = 0;
19429 for(uint32 i = 0; i < MAX_RUNES; ++i)
19431 SetBaseRune(i, i / 2); // init base types
19432 SetCurrentRune(i, i / 2); // init current types
19433 SetRuneCooldown(i, 0); // reset cooldowns
19434 m_runes->SetRuneState(i);
19437 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19438 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19441 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19443 Loot loot;
19444 loot.FillLoot (loot_id,store,this,true);
19446 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19447 for(uint32 i = 0; i < max_slot; ++i)
19449 LootItem* lootItem = loot.LootItemInSlot(i,this);
19451 ItemPosCountVec dest;
19452 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19453 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19454 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19455 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19456 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19457 if(msg != EQUIP_ERR_OK)
19459 SendEquipError( msg, NULL, NULL );
19460 continue;
19463 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19464 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19468 uint32 Player::CalculateTalentsPoints() const
19470 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19472 if(getClass() != CLASS_DEATH_KNIGHT)
19473 return base_talent;
19475 uint32 talentPointsForLevel =
19476 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19477 + m_questRewardTalentCount;
19479 if(talentPointsForLevel > base_talent)
19480 talentPointsForLevel = base_talent;
19482 return talentPointsForLevel;
19485 bool Player::IsAllowUseFlyMountsHere() const
19487 if (isGameMaster())
19488 return true;
19490 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19491 return v_map == 530 || v_map == 571 && HasSpell(54197);
19494 void Player::learnSpellHighRank(uint32 spellid)
19496 learnSpell(spellid,false);
19498 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19499 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19500 learnSpellHighRank(itr->second);
19503 void Player::_LoadSkills()
19505 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19507 // reset skill modifiers and set correct unlearn flags
19508 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
19510 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19512 // set correct unlearn bit
19513 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19514 if(!id) continue;
19516 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19517 if(!pSkill) continue;
19519 // enable unlearn button for primary professions only
19520 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19521 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19522 else
19523 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19525 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19527 learnSkillRewardedSpells(id, vskill);
19530 // special settings
19531 if(getClass()==CLASS_DEATH_KNIGHT)
19533 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19534 if(base_level < 1)
19535 base_level = 1;
19536 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19537 if(base_skill < 1)
19538 base_skill = 1; // skill mast be known and then > 0 in any case
19540 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19541 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19542 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19543 SetSkill(SKILL_AXES, base_skill,base_skill);
19544 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19545 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19546 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19547 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19548 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19549 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19550 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19551 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19552 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19553 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19554 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19555 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19559 uint32 Player::GetPhaseMaskForSpawn() const
19561 uint32 phase = PHASEMASK_NORMAL;
19562 if(!isGameMaster())
19563 phase = GetPhaseMask();
19564 else
19566 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19567 if(!phases.empty())
19568 phase = phases.front()->GetMiscValue();
19571 // some aura phases include 1 normal map in addition to phase itself
19572 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19573 return n_phase;
19575 return PHASEMASK_NORMAL;