removed duplicated includes
[getmangos.git] / src / game / Player.cpp
blobf6547288ceec772781beda192273339e49298c7a
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 "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "SkillDiscovery.h"
31 #include "QuestDef.h"
32 #include "GossipDef.h"
33 #include "UpdateData.h"
34 #include "Channel.h"
35 #include "ChannelMgr.h"
36 #include "MapManager.h"
37 #include "MapInstanced.h"
38 #include "InstanceSaveMgr.h"
39 #include "GridNotifiers.h"
40 #include "GridNotifiersImpl.h"
41 #include "CellImpl.h"
42 #include "ObjectMgr.h"
43 #include "ObjectAccessor.h"
44 #include "CreatureAI.h"
45 #include "Formulas.h"
46 #include "Group.h"
47 #include "Guild.h"
48 #include "Pet.h"
49 #include "SpellAuras.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // capital and taxi hub masks
132 switch(race)
134 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
135 case RACE_ORC: SetTaximaskNode(23); break; // Orc
136 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
137 case RACE_NIGHTELF: SetTaximaskNode(26);
138 SetTaximaskNode(27); break; // Night Elf
139 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
140 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
141 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
142 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
143 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
144 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
147 switch(chrClass)
149 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
150 break;
153 // new continent starting masks (It will be accessible only at new map)
154 switch(Player::TeamForRace(race))
156 case ALLIANCE: SetTaximaskNode(100); break;
157 case HORDE: SetTaximaskNode(99); break;
159 // level dependent taxi hubs
160 if(level>=68)
161 SetTaximaskNode(213); //Shattered Sun Staging Area
164 void PlayerTaxi::LoadTaxiMask(const char* data)
166 Tokens tokens = StrSplit(data, " ");
168 int index;
169 Tokens::iterator iter;
170 for (iter = tokens.begin(), index = 0;
171 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
173 // load and set bits only for existed taxi nodes
174 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
178 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
180 if(all)
182 for (uint8 i=0; i<TaxiMaskSize; i++)
183 data << uint32(sTaxiNodesMask[i]); // all existed nodes
185 else
187 for (uint8 i=0; i<TaxiMaskSize; i++)
188 data << uint32(m_taximask[i]); // known nodes
192 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
194 ClearTaxiDestinations();
196 Tokens tokens = StrSplit(values," ");
198 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
200 uint32 node = uint32(atol(iter->c_str()));
201 AddTaxiDestination(node);
204 if(m_TaxiDestinations.empty())
205 return true;
207 // Check integrity
208 if(m_TaxiDestinations.size() < 2)
209 return false;
211 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
213 uint32 cost;
214 uint32 path;
215 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
216 if(!path)
217 return false;
220 // can't load taxi path without mount set (quest taxi path?)
221 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
222 return false;
224 return true;
227 std::string PlayerTaxi::SaveTaxiDestinationsToString()
229 if(m_TaxiDestinations.empty())
230 return "";
232 std::ostringstream ss;
234 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
235 ss << m_TaxiDestinations[i] << " ";
237 return ss.str();
240 uint32 PlayerTaxi::GetCurrentTaxiPath() const
242 if(m_TaxiDestinations.size() < 2)
243 return 0;
245 uint32 path;
246 uint32 cost;
248 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
250 return path;
253 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
255 ss << "'";
256 for(int i = 0; i < TaxiMaskSize; ++i)
257 ss << taxi.m_taximask[i] << " ";
258 ss << "'";
259 return ss;
262 //== Player ====================================================
264 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
266 UpdateMask Player::updateVisualBits;
268 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
270 m_transport = 0;
272 m_speakTime = 0;
273 m_speakCount = 0;
275 m_objectType |= TYPEMASK_PLAYER;
276 m_objectTypeId = TYPEID_PLAYER;
278 m_valuesCount = PLAYER_END;
280 m_session = session;
282 m_divider = 0;
284 m_ExtraFlags = 0;
285 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
286 SetAcceptTicket(true);
288 // players always accept
289 if(GetSession()->GetSecurity() == SEC_PLAYER)
290 SetAcceptWhispers(true);
292 m_curSelection = 0;
293 m_lootGuid = 0;
295 m_comboTarget = 0;
296 m_comboPoints = 0;
298 m_usedTalentCount = 0;
299 m_questRewardTalentCount = 0;
301 m_regenTimer = 0;
302 m_weaponChangeTimer = 0;
304 m_zoneUpdateId = 0;
305 m_zoneUpdateTimer = 0;
307 m_areaUpdateId = 0;
309 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
311 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
312 // this must help in case next save after mass player load after server startup
313 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
315 clearResurrectRequestData();
317 m_SpellModRemoveCount = 0;
319 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
321 m_social = NULL;
323 // group is initialized in the reference constructor
324 SetGroupInvite(NULL);
325 m_groupUpdateMask = 0;
326 m_auraUpdateMask = 0;
328 duel = NULL;
330 m_GuildIdInvited = 0;
331 m_ArenaTeamIdInvited = 0;
333 m_atLoginFlags = AT_LOGIN_NONE;
335 m_dontMove = false;
337 pTrader = 0;
338 ClearTrade();
340 m_cinematic = 0;
342 PlayerTalkClass = new PlayerMenu( GetSession() );
343 m_currentBuybackSlot = BUYBACK_SLOT_START;
345 for ( int aX = 0 ; aX < 8 ; aX++ )
346 m_Tutorials[ aX ] = 0x00;
347 m_TutorialsChanged = false;
349 m_DailyQuestChanged = false;
350 m_lastDailyQuestTime = 0;
352 m_regenTimer = 0;
353 m_weaponChangeTimer = 0;
354 m_breathTimer = 0;
355 m_isunderwater = UNDERWATER_NONE;
356 m_isInWater = false;
357 m_drunkTimer = 0;
358 m_drunk = 0;
359 m_restTime = 0;
360 m_deathTimer = 0;
361 m_deathExpireTime = 0;
363 m_swingErrorMsg = 0;
365 m_DetectInvTimer = 1*IN_MILISECONDS;
367 m_bgBattleGroundID = 0;
368 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
369 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
371 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
372 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
374 m_bgTeam = 0;
376 m_logintime = time(NULL);
377 m_Last_tick = m_logintime;
378 m_WeaponProficiency = 0;
379 m_ArmorProficiency = 0;
380 m_canParry = false;
381 m_canBlock = false;
382 m_canDualWield = false;
383 m_canTitanGrip = false;
384 m_ammoDPS = 0.0f;
386 m_temporaryUnsummonedPetNumber = 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
390 m_oldpetspell = 0;
392 ////////////////////Rest System/////////////////////
393 time_inn_enter=0;
394 inn_pos_mapid=0;
395 inn_pos_x=0;
396 inn_pos_y=0;
397 inn_pos_z=0;
398 m_rest_bonus=0;
399 rest_type=REST_TYPE_NO;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded = false;
403 m_mailsUpdated = false;
404 unReadMails = 0;
405 m_nextMailDelivereTime = 0;
407 m_resetTalentsCost = 0;
408 m_resetTalentsTime = 0;
409 m_itemUpdateQueueBlocked = false;
411 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
412 m_forced_speed_changes[i] = 0;
414 m_stableSlots = 0;
416 /////////////////// Instance System /////////////////////
418 m_HomebindTimer = 0;
419 m_InstanceValid = true;
420 m_dungeonDifficulty = DIFFICULTY_NORMAL;
422 m_lastPotionId = 0;
424 for (int i = 0; i < BASEMOD_END; i++)
426 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
427 m_auraBaseMod[i][PCT_MOD] = 1.0f;
430 for (int i = 0; i < MAX_COMBAT_RATING; i++)
431 m_baseRatingValue[i] = 0;
433 m_baseSpellDamage = 0;
434 m_baseSpellHealing = 0;
435 m_baseFeralAP = 0;
436 m_baseManaRegen = 0;
438 // Honor System
439 m_lastHonorUpdateTime = time(NULL);
441 // Player summoning
442 m_summon_expire = 0;
443 m_summon_mapid = 0;
444 m_summon_x = 0.0f;
445 m_summon_y = 0.0f;
446 m_summon_z = 0.0f;
448 //Default movement to run mode
449 m_unit_movement_flags = 0;
451 m_mover = NULL;
453 m_miniPet = 0;
454 m_bgAfkReportedTimer = 0;
455 m_contestedPvPTimer = 0;
457 m_declinedname = NULL;
458 m_runes = NULL;
461 Player::~Player ()
463 CleanupsBeforeDelete();
465 // it must be unloaded already in PlayerLogout and accessed only for loggined player
466 //m_social = NULL;
468 // Note: buy back item already deleted from DB when player was saved
469 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
471 if(m_items[i])
472 delete m_items[i];
474 CleanupChannels();
476 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
477 delete itr->second;
479 //all mailed items should be deleted, also all mail should be deallocated
480 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
481 delete *itr;
483 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
484 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
486 delete PlayerTalkClass;
488 if (m_transport)
490 m_transport->RemovePassenger(this);
493 for(size_t x = 0; x < ItemSetEff.size(); x++)
494 if(ItemSetEff[x])
495 delete ItemSetEff[x];
497 // clean up player-instance binds, may unload some instance saves
498 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
499 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
500 itr->second.save->RemovePlayer(this);
502 delete m_declinedname;
503 delete m_runes;
506 void Player::CleanupsBeforeDelete()
508 if(m_uint32Values) // only for fully created Object
510 TradeCancel(false);
511 DuelComplete(DUEL_INTERUPTED);
513 Unit::CleanupsBeforeDelete();
516 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 )
518 //FIXME: outfitId not used in player creating
520 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
522 m_name = name;
524 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
525 if(!info)
527 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
528 return false;
531 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
532 m_items[i] = NULL;
534 m_race = race;
535 m_class = class_;
537 SetMapId(info->mapId);
538 Relocate(info->positionX,info->positionY,info->positionZ);
540 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
541 if(!cEntry)
543 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
544 return false;
547 uint8 powertype = cEntry->powerType;
549 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
550 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
552 switch(gender)
554 case GENDER_FEMALE:
555 SetDisplayId(info->displayId_f );
556 SetNativeDisplayId(info->displayId_f );
557 break;
558 case GENDER_MALE:
559 SetDisplayId(info->displayId_m );
560 SetNativeDisplayId(info->displayId_m );
561 break;
562 default:
563 sLog.outError("Invalid gender %u for player",gender);
564 return false;
565 break;
568 setFactionForRace(m_race);
570 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
572 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
573 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
574 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
575 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
576 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
577 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
579 // -1 is default value
580 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
582 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
583 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
584 SetByteValue(PLAYER_BYTES_3, 0, gender);
586 SetUInt32Value( PLAYER_GUILDID, 0 );
587 SetUInt32Value( PLAYER_GUILDRANK, 0 );
588 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
591 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
592 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
593 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
594 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
595 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
596 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
598 // set starting level
599 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
600 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
601 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
603 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
605 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
606 if(gm_level > start_level)
607 start_level = gm_level;
610 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
612 InitRunes();
614 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
615 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
616 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
618 // Played time
619 m_Last_tick = time(NULL);
620 m_Played_time[0] = 0;
621 m_Played_time[1] = 0;
623 // base stats and related field values
624 InitStatsForLevel();
625 InitTaxiNodesForLevel();
626 InitGlyphsForLevel();
627 InitTalentForLevel();
628 InitPrimaryProffesions(); // to max set before any spell added
630 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
631 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
632 SetHealth(GetMaxHealth());
633 if (getPowerType()==POWER_MANA)
635 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
636 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
639 if(getPowerType() == POWER_RUNIC_POWER)
641 SetPower(POWER_RUNE, 8);
642 SetMaxPower(POWER_RUNE, 8);
643 SetPower(POWER_RUNIC_POWER, 0);
644 SetMaxPower(POWER_RUNIC_POWER, 1000);
647 // original spells
648 learnDefaultSpells();
650 // original action bar
651 std::list<uint16>::const_iterator action_itr[4];
652 for(int i=0; i<4; i++)
653 action_itr[i] = info->action[i].begin();
655 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
657 uint16 taction[4];
658 for(int i=0; i<4 ;i++)
659 taction[i] = (*action_itr[i]);
661 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
663 for(int i=0; i<4 ;i++)
664 ++action_itr[i];
667 // original items
668 CharStartOutfitEntry const* oEntry = NULL;
669 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
671 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
673 if(entry->RaceClassGender == RaceClassGender)
675 oEntry = entry;
676 break;
681 if(oEntry)
683 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
685 if(oEntry->ItemId[j] <= 0)
686 continue;
688 uint32 item_id = oEntry->ItemId[j];
691 // Hack for not existed item id in dbc 3.0.3
692 if(item_id==40582)
693 continue;
695 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
696 if(!iProto)
698 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
699 continue;
702 // max stack by default (mostly 1), 1 for infinity stackable
703 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
705 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
707 switch(iProto->Spells[0].SpellCategory)
709 case 11: // food
710 if(iProto->Stackable > 4)
711 count = 4;
712 break;
713 case 59: // drink
714 if(iProto->Stackable > 2)
715 count = 2;
716 break;
720 StoreNewItemInBestSlots(item_id, count);
724 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
725 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
727 // bags and main-hand weapon must equipped at this moment
728 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
729 // or ammo not equipped in special bag
730 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
732 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
734 uint16 eDest;
735 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
736 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
737 if( msg == EQUIP_ERR_OK )
739 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
740 EquipItem( eDest, pItem, true);
742 // move other items to more appropriate slots (ammo not equipped in special bag)
743 else
745 ItemPosCountVec sDest;
746 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
747 if( msg == EQUIP_ERR_OK )
749 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
750 pItem = StoreItem( sDest, pItem, true);
753 // if this is ammo then use it
754 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
755 if( msg == EQUIP_ERR_OK )
756 SetAmmo( pItem->GetProto()->ItemId );
760 // all item positions resolved
762 return true;
765 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
767 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
769 // attempt equip by one
770 while(titem_amount > 0)
772 uint16 eDest;
773 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
774 if( msg != EQUIP_ERR_OK )
775 break;
777 EquipNewItem( eDest, titem_id, true);
778 AutoUnequipOffhandIfNeed();
779 --titem_amount;
782 if(titem_amount == 0)
783 return true; // equipped
785 // attempt store
786 ItemPosCountVec sDest;
787 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
788 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
789 if( msg == EQUIP_ERR_OK )
791 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
792 return true; // stored
795 // item can't be added
796 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
797 return false;
800 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
802 uint32 BreathRegen = (uint32)-1;
804 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
805 data << (uint32)Type;
806 data << MaxValue;
807 data << MaxValue;
808 data << BreathRegen;
809 data << (uint8)0;
810 data << (uint32)0; // spell id
811 GetSession()->SendPacket(&data);
814 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
816 if(Type==BREATH_TIMER)
817 m_breathTimer = ((MaxValue + 1*IN_MILISECONDS) - CurrentValue) / Regen;
819 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
820 data << (uint32)Type;
821 data << CurrentValue;
822 data << MaxValue;
823 data << Regen;
824 data << (uint8)0;
825 data << (uint32)0; // spell id
826 GetSession()->SendPacket( &data );
829 void Player::StopMirrorTimer(MirrorTimerType Type)
831 if(Type==BREATH_TIMER)
832 m_breathTimer = 0;
834 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
835 data << (uint32)Type;
836 GetSession()->SendPacket( &data );
839 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
841 if(!isAlive() || isGameMaster())
842 return;
844 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
845 data << (uint64)guid;
846 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
847 data << (uint32)damage;
848 data << (uint32)0;
849 data << (uint32)0;
850 SendMessageToSet(&data, true);
852 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
854 if(!isAlive())
856 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
858 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
859 DurabilityLossAll(0.10f,false);
860 // durability lost message
861 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
862 GetSession()->SendPacket(&data);
865 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
869 void Player::HandleDrowning()
871 if(!(m_isunderwater&~UNDERWATER_INLAVA))
872 return;
874 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
875 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
877 StopMirrorTimer(BREATH_TIMER);
878 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
879 m_isunderwater &= UNDERWATER_INLAVA;
880 return;
883 uint32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS; // default duration
885 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
886 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
887 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
889 if ((m_isunderwater & UNDERWATER_INWATER) && !(m_isunderwater & UNDERWATER_INLAVA) && isAlive())
891 //single trigger timer
892 if (!(m_isunderwater & UNDERWATER_WATER_TRIGGER))
894 m_isunderwater|= UNDERWATER_WATER_TRIGGER;
895 m_breathTimer = UnderWaterTime + 1*IN_MILISECONDS;
897 //single trigger "show Breathbar"
898 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & UNDERWATER_WATER_BREATHB))
900 m_isunderwater|= UNDERWATER_WATER_BREATHB;
901 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
903 //continuous trigger drowning "Damage"
904 if ((m_breathTimer == 0) && (m_isunderwater & UNDERWATER_INWATER))
906 //TODO: Check this formula
907 uint64 guid = GetGUID();
908 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
910 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
911 m_breathTimer = 2000;
914 //single trigger retract bar
915 else if (!(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater & UNDERWATER_WATER_TRIGGER) && (m_breathTimer > 0) && isAlive())
917 uint32 BreathRegen = 10;
918 // m_breathTimer will be reduced in ModifyMirrorTimer
919 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
920 m_isunderwater = UNDERWATER_WATER_BREATHB_RETRACTING;
922 //remove bar
923 else if ((m_breathTimer < 50) && !(m_isunderwater & UNDERWATER_INWATER) && (m_isunderwater == UNDERWATER_WATER_BREATHB_RETRACTING))
925 StopMirrorTimer(BREATH_TIMER);
926 m_isunderwater = UNDERWATER_NONE;
930 void Player::HandleLava()
932 if ((m_isunderwater & UNDERWATER_INLAVA) && isAlive())
935 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
936 // Single trigger Set BreathTimer
937 if (!(m_isunderwater & UNDERWATER_INLAVA))
939 m_isunderwater|= UNDERWATER_WATER_BREATHB;
940 m_breathTimer = 1*IN_MILISECONDS;
943 // Reset BreathTimer and still in the lava
944 if (!m_breathTimer)
946 uint64 guid = GetGUID();
947 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
949 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
951 m_breathTimer = 1*IN_MILISECONDS;
954 else if (!isAlive()) // Disable breath timer and reset underwater flags
956 m_breathTimer = 0;
957 m_isunderwater = UNDERWATER_NONE;
961 ///The player sobers by 256 every 10 seconds
962 void Player::HandleSobering()
964 m_drunkTimer = 0;
966 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
967 SetDrunkValue(drunk);
970 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
972 if(value >= 23000)
973 return DRUNKEN_SMASHED;
974 if(value >= 12800)
975 return DRUNKEN_DRUNK;
976 if(value & 0xFFFE)
977 return DRUNKEN_TIPSY;
978 return DRUNKEN_SOBER;
981 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
983 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
985 m_drunk = newDrunkenValue;
986 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
988 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
990 // special drunk invisibility detection
991 if(newDrunkenState >= DRUNKEN_DRUNK)
992 m_detectInvisibilityMask |= (1<<6);
993 else
994 m_detectInvisibilityMask &= ~(1<<6);
996 if(newDrunkenState == oldDrunkenState)
997 return;
999 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1000 data << uint64(GetGUID());
1001 data << uint32(newDrunkenState);
1002 data << uint32(itemId);
1004 SendMessageToSet(&data, true);
1007 void Player::Update( uint32 p_time )
1009 if(!IsInWorld())
1010 return;
1012 // undelivered mail
1013 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1015 SendNewMail();
1016 ++unReadMails;
1018 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1019 m_nextMailDelivereTime = 0;
1022 Unit::Update( p_time );
1024 // update player only attacks
1025 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1027 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1030 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1032 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1035 time_t now = time (NULL);
1037 UpdatePvPFlag(now);
1039 UpdateContestedPvP(p_time);
1041 UpdateDuelFlag(now);
1043 CheckDuelDistance(now);
1045 UpdateAfkReport(now);
1047 CheckExploreSystem();
1049 // Update items that have just a limited lifetime
1050 if (now>m_Last_tick)
1051 UpdateItemDuration(uint32(now- m_Last_tick));
1053 if (!m_timedquests.empty())
1055 std::set<uint32>::iterator iter = m_timedquests.begin();
1056 while (iter != m_timedquests.end())
1058 QuestStatusData& q_status = mQuestStatus[*iter];
1059 if( q_status.m_timer <= p_time )
1061 uint32 quest_id = *iter;
1062 ++iter; // current iter will be removed in FailTimedQuest
1063 FailTimedQuest( quest_id );
1065 else
1067 q_status.m_timer -= p_time;
1068 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1069 ++iter;
1074 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1076 Unit *pVictim = getVictim();
1077 if( !IsNonMeleeSpellCasted(false) && pVictim)
1079 // default combat reach 10
1080 // TODO add weapon,skill check
1082 float pldistance = ATTACK_DISTANCE;
1084 if (isAttackReady(BASE_ATTACK))
1086 if(!IsWithinDistInMap(pVictim, pldistance))
1088 setAttackTimer(BASE_ATTACK,100);
1089 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1091 SendAttackSwingNotInRange();
1092 m_swingErrorMsg = 1;
1095 //120 degrees of radiant range
1096 else if( !HasInArc( 2*M_PI/3, pVictim ))
1098 setAttackTimer(BASE_ATTACK,100);
1099 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1101 SendAttackSwingBadFacingAttack();
1102 m_swingErrorMsg = 2;
1105 else
1107 m_swingErrorMsg = 0; // reset swing error state
1109 // prevent base and off attack in same time, delay attack at 0.2 sec
1110 if(haveOffhandWeapon())
1112 uint32 off_att = getAttackTimer(OFF_ATTACK);
1113 if(off_att < ATTACK_DISPLAY_DELAY)
1114 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1116 AttackerStateUpdate(pVictim, BASE_ATTACK);
1117 resetAttackTimer(BASE_ATTACK);
1121 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1123 if(!IsWithinDistInMap(pVictim, pldistance))
1125 setAttackTimer(OFF_ATTACK,100);
1127 else if( !HasInArc( 2*M_PI/3, pVictim ))
1129 setAttackTimer(OFF_ATTACK,100);
1131 else
1133 // prevent base and off attack in same time, delay attack at 0.2 sec
1134 uint32 base_att = getAttackTimer(BASE_ATTACK);
1135 if(base_att < ATTACK_DISPLAY_DELAY)
1136 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1137 // do attack
1138 AttackerStateUpdate(pVictim, OFF_ATTACK);
1139 resetAttackTimer(OFF_ATTACK);
1143 Unit *owner = pVictim->GetOwner();
1144 Unit *u = owner ? owner : pVictim;
1145 if(u->IsPvP() && (!duel || duel->opponent != u))
1147 UpdatePvP(true);
1148 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1153 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1155 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1157 int time_inn = time(NULL)-GetTimeInnEnter();
1158 if (time_inn >= 10) //freeze update
1160 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1161 //speed collect rest bonus (section/in hour)
1162 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1163 UpdateInnerTime(time(NULL));
1168 if(m_regenTimer > 0)
1170 if(p_time >= m_regenTimer)
1171 m_regenTimer = 0;
1172 else
1173 m_regenTimer -= p_time;
1176 if (m_weaponChangeTimer > 0)
1178 if(p_time >= m_weaponChangeTimer)
1179 m_weaponChangeTimer = 0;
1180 else
1181 m_weaponChangeTimer -= p_time;
1184 if (m_zoneUpdateTimer > 0)
1186 if(p_time >= m_zoneUpdateTimer)
1188 uint32 newzone = GetZoneId();
1189 if( m_zoneUpdateId != newzone )
1190 UpdateZone(newzone); // also update area
1191 else
1193 // use area updates as well
1194 // needed for free far all arenas for example
1195 uint32 newarea = GetAreaId();
1196 if( m_areaUpdateId != newarea )
1197 UpdateArea(newarea);
1199 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1202 else
1203 m_zoneUpdateTimer -= p_time;
1206 if (isAlive())
1208 RegenerateAll();
1211 if (m_deathState == JUST_DIED)
1213 KillPlayer();
1216 if(m_nextSave > 0)
1218 if(p_time >= m_nextSave)
1220 // m_nextSave reseted in SaveToDB call
1221 SaveToDB();
1222 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1224 else
1226 m_nextSave -= p_time;
1230 //Breathtimer
1231 if(m_breathTimer > 0)
1233 if(p_time >= m_breathTimer)
1234 m_breathTimer = 0;
1235 else
1236 m_breathTimer -= p_time;
1240 //Handle Water/drowning
1241 HandleDrowning();
1243 //Handle lava
1244 HandleLava();
1246 //Handle detect stealth players
1247 if (m_DetectInvTimer > 0)
1249 if (p_time >= m_DetectInvTimer)
1251 m_DetectInvTimer = 3000;
1252 HandleStealthedUnitsDetection();
1254 else
1255 m_DetectInvTimer -= p_time;
1258 // Played time
1259 if (now > m_Last_tick)
1261 uint32 elapsed = uint32(now - m_Last_tick);
1262 m_Played_time[0] += elapsed; // Total played time
1263 m_Played_time[1] += elapsed; // Level played time
1264 m_Last_tick = now;
1267 if (m_drunk)
1269 m_drunkTimer += p_time;
1271 if (m_drunkTimer > 10*IN_MILISECONDS)
1272 HandleSobering();
1275 // not auto-free ghost from body in instances
1276 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1278 if(p_time >= m_deathTimer)
1280 m_deathTimer = 0;
1281 BuildPlayerRepop();
1282 RepopAtGraveyard();
1284 else
1285 m_deathTimer -= p_time;
1288 UpdateEnchantTime(p_time);
1289 UpdateHomebindTime(p_time);
1291 // group update
1292 SendUpdateToOutOfRangeGroupMembers();
1294 Pet* pet = GetPet();
1295 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1297 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1298 return;
1302 void Player::setDeathState(DeathState s)
1304 uint32 ressSpellId = 0;
1306 bool cur = isAlive();
1308 if(s == JUST_DIED && cur)
1310 // drunken state is cleared on death
1311 SetDrunkValue(0);
1312 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1313 ClearComboPoints();
1315 clearResurrectRequestData();
1317 // remove form before other mods to prevent incorrect stats calculation
1318 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1320 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1321 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1323 // remove uncontrolled pets
1324 RemoveMiniPet();
1325 RemoveGuardians();
1327 // save value before aura remove in Unit::setDeathState
1328 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1330 // passive spell
1331 if(!ressSpellId)
1332 ressSpellId = GetResurrectionSpellId();
1333 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1334 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1335 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1337 Unit::setDeathState(s);
1339 // restore resurrection spell id for player after aura remove
1340 if(s == JUST_DIED && cur && ressSpellId)
1341 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1343 if(isAlive() && !cur)
1345 //clear aura case after resurrection by another way (spells will be applied before next death)
1346 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1348 // restore default warrior stance
1349 if(getClass()== CLASS_WARRIOR)
1350 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1354 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1356 Field *fields = result->Fetch();
1358 *p_data << uint64(GetGUID());
1359 *p_data << m_name;
1361 *p_data << uint8(getRace());
1362 uint8 pClass = getClass();
1363 *p_data << uint8(pClass);
1364 *p_data << uint8(getGender());
1366 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1367 *p_data << uint8(bytes);
1368 *p_data << uint8(bytes >> 8);
1369 *p_data << uint8(bytes >> 16);
1370 *p_data << uint8(bytes >> 24);
1372 bytes = GetUInt32Value(PLAYER_BYTES_2);
1373 *p_data << uint8(bytes);
1375 *p_data << uint8(getLevel()); // player level
1376 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1377 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1378 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1379 *p_data << uint32(zoneId);
1380 *p_data << uint32(GetMapId());
1382 *p_data << GetPositionX();
1383 *p_data << GetPositionY();
1384 *p_data << GetPositionZ();
1386 // guild id
1387 *p_data << (result ? fields[13].GetUInt32() : 0);
1389 uint32 char_flags = 0;
1390 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1391 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1392 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1393 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1394 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1395 char_flags |= CHARACTER_FLAG_GHOST;
1396 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1397 char_flags |= CHARACTER_FLAG_RENAME;
1398 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1399 char_flags |= CHARACTER_FLAG_DECLINED;
1401 *p_data << uint32(char_flags); // character flags
1402 // character customize (flags?)
1403 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1404 *p_data << uint8(1); // unknown
1406 // Pets info
1408 uint32 petDisplayId = 0;
1409 uint32 petLevel = 0;
1410 uint32 petFamily = 0;
1412 // show pet at selection character in character list only for non-ghost character
1413 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1415 uint32 entry = fields[10].GetUInt32();
1416 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1417 if(cInfo)
1419 petDisplayId = fields[11].GetUInt32();
1420 petLevel = fields[12].GetUInt32();
1421 petFamily = cInfo->family;
1425 *p_data << uint32(petDisplayId);
1426 *p_data << uint32(petLevel);
1427 *p_data << uint32(petFamily);
1430 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1432 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1433 uint32 item_id = GetUInt32Value(visualbase);
1434 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1435 SpellItemEnchantmentEntry const *enchant = NULL;
1437 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1439 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1440 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1441 break;
1444 if (proto != NULL)
1446 *p_data << uint32(proto->DisplayInfoID);
1447 *p_data << uint8(proto->InventoryType);
1448 *p_data << uint32(enchant ? enchant->aura_id : 0);
1450 else
1452 *p_data << uint32(0);
1453 *p_data << uint8(0);
1454 *p_data << uint32(0); // enchant?
1457 *p_data << uint32(0); // first bag display id
1458 *p_data << uint8(0); // first bag inventory type
1459 *p_data << uint32(0); // enchant?
1462 bool Player::ToggleAFK()
1464 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1466 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1468 // afk player not allowed in battleground
1469 if(state && InBattleGround())
1470 LeaveBattleground();
1472 return state;
1475 bool Player::ToggleDND()
1477 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1479 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1482 uint8 Player::chatTag() const
1484 // it's bitmask
1485 // 0x8 - ??
1486 // 0x4 - gm
1487 // 0x2 - dnd
1488 // 0x1 - afk
1489 if(isGMChat())
1490 return 4;
1491 else if(isDND())
1492 return 3;
1493 if(isAFK())
1494 return 1;
1495 else
1496 return 0;
1499 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1501 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1503 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1504 return false;
1507 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1508 Pet* pet = GetPet();
1510 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1512 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1513 // don't let gm level > 1 either
1514 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1515 return false;
1517 // client without expansion support
1518 if(GetSession()->Expansion() < mEntry->Expansion())
1520 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1522 if(GetTransport())
1523 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1525 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1527 return false; // normal client can't teleport to this map...
1529 else
1531 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1534 // if we were on a transport, leave
1535 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1537 m_transport->RemovePassenger(this);
1538 m_transport = NULL;
1539 m_movementInfo.t_x = 0.0f;
1540 m_movementInfo.t_y = 0.0f;
1541 m_movementInfo.t_z = 0.0f;
1542 m_movementInfo.t_o = 0.0f;
1543 m_movementInfo.t_time = 0;
1546 SetSemaphoreTeleport(true);
1548 // The player was ported to another map and looses the duel immediately.
1549 // We have to perform this check before the teleport, otherwise the
1550 // ObjectAccessor won't find the flag.
1551 if (duel && GetMapId()!=mapid)
1553 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1554 if (obj)
1555 DuelComplete(DUEL_FLED);
1558 // reset movement flags at teleport, because player will continue move with these flags after teleport
1559 SetUnitMovementFlags(0);
1561 if ((GetMapId() == mapid) && (!m_transport))
1563 // prepare zone change detect
1564 uint32 old_zone = GetZoneId();
1566 // near teleport
1567 if(!GetSession()->PlayerLogout())
1569 WorldPacket data;
1570 BuildTeleportAckMsg(&data, x, y, z, orientation);
1571 GetSession()->SendPacket(&data);
1572 SetPosition( x, y, z, orientation, true);
1574 else
1575 // this will be used instead of the current location in SaveToDB
1576 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1578 SetFallInformation(0, z);
1580 //BuildHeartBeatMsg(&data);
1581 //SendMessageToSet(&data, true);
1582 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1584 //same map, only remove pet if out of range
1585 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1587 if(pet->isControlled() && !pet->isTemporarySummoned() )
1588 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1589 else
1590 m_temporaryUnsummonedPetNumber = 0;
1592 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1596 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1597 CombatStop();
1599 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1601 // resummon pet
1602 if(pet && m_temporaryUnsummonedPetNumber)
1604 Pet* NewPet = new Pet;
1605 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1606 delete NewPet;
1608 m_temporaryUnsummonedPetNumber = 0;
1612 if(!GetSession()->PlayerLogout())
1614 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1615 SetSemaphoreTeleport(false);
1617 UpdateZone(GetZoneId());
1620 // new zone
1621 if(old_zone != GetZoneId())
1623 // honorless target
1624 if(pvpInfo.inHostileArea)
1625 CastSpell(this, 2479, true);
1628 else
1630 // far teleport to another map
1631 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1632 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1634 // Check enter rights before map getting to avoid creating instance copy for player
1635 // this check not dependent from map instance copy and same for all instance copies of selected map
1636 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1638 SetSemaphoreTeleport(false);
1639 return false;
1642 // If the map is not created, assume it is possible to enter it.
1643 // It will be created in the WorldPortAck.
1644 Map *map = MapManager::Instance().FindMap(mapid);
1645 if (!map || map->CanEnter(this))
1647 SetSelection(0);
1649 CombatStop();
1651 ResetContestedPvP();
1653 // remove player from battleground on far teleport (when changing maps)
1654 if(BattleGround const* bg = GetBattleGround())
1656 // Note: at battleground join battleground id set before teleport
1657 // and we already will found "current" battleground
1658 // just need check that this is targeted map or leave
1659 if(bg->GetMapId() != mapid)
1660 LeaveBattleground(false); // don't teleport to entry point
1663 // remove pet on map change
1664 if (pet)
1666 //leaving map -> delete pet right away (doing this later will cause problems)
1667 if(pet->isControlled() && !pet->isTemporarySummoned())
1668 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1669 else
1670 m_temporaryUnsummonedPetNumber = 0;
1672 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1675 // remove all dyn objects
1676 RemoveAllDynObjects();
1678 // stop spellcasting
1679 // not attempt interrupt teleportation spell at caster teleport
1680 if(!(options & TELE_TO_SPELL))
1681 if(IsNonMeleeSpellCasted(true))
1682 InterruptNonMeleeSpells(true);
1684 if(!GetSession()->PlayerLogout())
1686 // send transfer packets
1687 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1688 data << uint32(mapid);
1689 if (m_transport)
1691 data << m_transport->GetEntry() << GetMapId();
1693 GetSession()->SendPacket(&data);
1695 data.Initialize(SMSG_NEW_WORLD, (20));
1696 if (m_transport)
1698 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1700 else
1702 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1704 GetSession()->SendPacket( &data );
1705 SendSavedInstances();
1707 // remove from old map now
1708 if(oldmap) oldmap->Remove(this, false);
1711 // new final coordinates
1712 float final_x = x;
1713 float final_y = y;
1714 float final_z = z;
1715 float final_o = orientation;
1717 if(m_transport)
1719 final_x += m_movementInfo.t_x;
1720 final_y += m_movementInfo.t_y;
1721 final_z += m_movementInfo.t_z;
1722 final_o += m_movementInfo.t_o;
1725 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1726 SetFallInformation(0, final_z);
1727 // if the player is saved before worldportack (at logout for example)
1728 // this will be used instead of the current location in SaveToDB
1730 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1732 // move packet sent by client always after far teleport
1733 // SetPosition(final_x, final_y, final_z, final_o, true);
1734 SetDontMove(true);
1736 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1738 else
1739 return false;
1741 return true;
1744 void Player::AddToWorld()
1746 ///- Do not add/remove the player from the object storage
1747 ///- It will crash when updating the ObjectAccessor
1748 ///- The player should only be added when logging in
1749 Unit::AddToWorld();
1751 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1753 if(m_items[i])
1754 m_items[i]->AddToWorld();
1758 void Player::RemoveFromWorld()
1760 // cleanup
1761 if(IsInWorld())
1763 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1764 Uncharm();
1765 UnsummonAllTotems();
1766 RemoveMiniPet();
1767 RemoveGuardians();
1770 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1772 if(m_items[i])
1773 m_items[i]->RemoveFromWorld();
1776 ///- Do not add/remove the player from the object storage
1777 ///- It will crash when updating the ObjectAccessor
1778 ///- The player should only be removed when logging out
1779 Unit::RemoveFromWorld();
1782 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1784 float addRage;
1786 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1788 if(attacker)
1790 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1792 // talent who gave more rage on attack
1793 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1795 else
1797 addRage = damage/rageconversion*2.5;
1799 // Berserker Rage effect
1800 if(HasAura(18499,0))
1801 addRage *= 1.3;
1804 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1806 ModifyPower(POWER_RAGE, uint32(addRage*10));
1809 void Player::RegenerateAll()
1811 if (m_regenTimer != 0)
1812 return;
1813 uint32 regenDelay = 2000;
1815 // Not in combat or they have regeneration
1816 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1817 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1819 RegenerateHealth();
1820 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1822 Regenerate(POWER_RAGE);
1823 if(getClass() == CLASS_DEATH_KNIGHT)
1824 Regenerate(POWER_RUNIC_POWER);
1828 Regenerate( POWER_ENERGY );
1830 Regenerate( POWER_MANA );
1832 if(getClass() == CLASS_DEATH_KNIGHT)
1833 Regenerate( POWER_RUNE );
1835 m_regenTimer = regenDelay;
1838 void Player::Regenerate(Powers power)
1840 uint32 curValue = GetPower(power);
1841 uint32 maxValue = GetMaxPower(power);
1843 float addvalue = 0.0f;
1845 switch (power)
1847 case POWER_MANA:
1849 bool recentCast = IsUnderLastManaUseEffect();
1850 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1851 if (recentCast)
1853 // Mangos Updates Mana in intervals of 2s, which is correct
1854 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1856 else
1858 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1860 } break;
1861 case POWER_RAGE: // Regenerate rage
1863 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1864 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1865 } break;
1866 case POWER_ENERGY: // Regenerate energy (rogue)
1867 addvalue = 20;
1868 break;
1869 case POWER_RUNIC_POWER:
1871 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1872 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1873 } break;
1874 case POWER_RUNE:
1876 for(uint32 i = 0; i < MAX_RUNES; ++i)
1877 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1878 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1879 } break;
1880 case POWER_FOCUS:
1881 case POWER_HAPPINESS:
1882 break;
1885 // Mana regen calculated in Player::UpdateManaRegen()
1886 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1887 if(power != POWER_MANA)
1889 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1890 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1891 if ((*i)->GetModifier()->m_miscvalue == power)
1892 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1895 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1897 curValue += uint32(addvalue);
1898 if (curValue > maxValue)
1899 curValue = maxValue;
1901 else
1903 if(curValue <= uint32(addvalue))
1904 curValue = 0;
1905 else
1906 curValue -= uint32(addvalue);
1908 SetPower(power, curValue);
1911 void Player::RegenerateHealth()
1913 uint32 curValue = GetHealth();
1914 uint32 maxValue = GetMaxHealth();
1916 if (curValue >= maxValue) return;
1918 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1920 float addvalue = 0.0f;
1922 // polymorphed case
1923 if ( IsPolymorphed() )
1924 addvalue = GetMaxHealth()/3;
1925 // normal regen case (maybe partly in combat case)
1926 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1928 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1929 if (!isInCombat())
1931 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1932 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1933 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1935 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1936 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1938 if(!IsStandState())
1939 addvalue *= 1.5;
1942 // always regeneration bonus (including combat)
1943 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1945 if(addvalue < 0)
1946 addvalue = 0;
1948 ModifyHealth(int32(addvalue));
1951 bool Player::CanInteractWithNPCs(bool alive) const
1953 if(alive && !isAlive())
1954 return false;
1955 if(isInFlight())
1956 return false;
1958 return true;
1961 bool Player::IsUnderWater() const
1963 return IsInWater() &&
1964 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1967 void Player::SetInWater(bool apply)
1969 if(m_isInWater==apply)
1970 return;
1972 //define player in water by opcodes
1973 //move player's guid into HateOfflineList of those mobs
1974 //which can't swim and move guid back into ThreatList when
1975 //on surface.
1976 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1977 m_isInWater = apply;
1979 // remove auras that need water/land
1980 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1982 getHostilRefManager().updateThreatTables();
1985 void Player::SetGameMaster(bool on)
1987 if(on)
1989 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1990 setFaction(35);
1991 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1993 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1994 ResetContestedPvP();
1996 getHostilRefManager().setOnlineOfflineState(false);
1997 CombatStop();
1999 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2001 else
2003 // restore phase
2004 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2005 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2007 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2008 setFactionForRace(getRace());
2009 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2011 // restore FFA PvP Server state
2012 if(sWorld.IsFFAPvPRealm())
2013 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2015 // restore FFA PvP area state, remove not allowed for GM mounts
2016 UpdateArea(m_areaUpdateId);
2018 getHostilRefManager().setOnlineOfflineState(true);
2021 ObjectAccessor::UpdateVisibilityForPlayer(this);
2024 void Player::SetGMVisible(bool on)
2026 if(on)
2028 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2030 // Reapply stealth/invisibility if active or show if not any
2031 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2032 SetVisibility(VISIBILITY_GROUP_STEALTH);
2033 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2034 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2035 else
2036 SetVisibility(VISIBILITY_ON);
2038 else
2040 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2042 SetAcceptWhispers(false);
2043 SetGameMaster(true);
2045 SetVisibility(VISIBILITY_OFF);
2049 bool Player::IsGroupVisibleFor(Player* p) const
2051 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2053 default: return IsInSameGroupWith(p);
2054 case 1: return IsInSameRaidWith(p);
2055 case 2: return GetTeam()==p->GetTeam();
2059 bool Player::IsInSameGroupWith(Player const* p) const
2061 return p==this || GetGroup() != NULL &&
2062 GetGroup() == p->GetGroup() &&
2063 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2066 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2067 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2068 void Player::UninviteFromGroup()
2070 Group* group = GetGroupInvite();
2071 if(!group)
2072 return;
2074 group->RemoveInvite(this);
2076 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2078 if(group->IsCreated())
2080 group->Disband(true);
2081 objmgr.RemoveGroup(group);
2083 else
2084 group->RemoveAllInvites();
2086 delete group;
2090 void Player::RemoveFromGroup(Group* group, uint64 guid)
2092 if(group)
2094 if (group->RemoveMember(guid, 0) <= 1)
2096 // group->Disband(); already disbanded in RemoveMember
2097 objmgr.RemoveGroup(group);
2098 delete group;
2099 // removemember sets the player's group pointer to NULL
2104 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2106 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2107 data << uint64(victim ? victim->GetGUID() : 0); // guid
2108 data << uint32(GivenXP+RestXP); // given experience
2109 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2110 if(victim)
2112 data << uint32(GivenXP); // experience without rested bonus
2113 data << float(1); // 1 - none 0 - 100% group bonus output
2115 data << uint8(0); // new 2.4.0
2116 GetSession()->SendPacket(&data);
2119 void Player::GiveXP(uint32 xp, Unit* victim)
2121 if ( xp < 1 )
2122 return;
2124 if(!isAlive())
2125 return;
2127 uint32 level = getLevel();
2129 // XP to money conversion processed in Player::RewardQuest
2130 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2131 return;
2133 // handle SPELL_AURA_MOD_XP_PCT auras
2134 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2135 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2136 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2138 // XP resting bonus for kill
2139 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2141 SendLogXPGain(xp,victim,rested_bonus_xp);
2143 uint32 curXP = GetUInt32Value(PLAYER_XP);
2144 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2145 uint32 newXP = curXP + xp + rested_bonus_xp;
2147 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2149 newXP -= nextLvlXP;
2151 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2152 GiveLevel(level + 1);
2154 level = getLevel();
2155 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2158 SetUInt32Value(PLAYER_XP, newXP);
2161 // Update player to next level
2162 // Current player experience not update (must be update by caller)
2163 void Player::GiveLevel(uint32 level)
2165 if ( level == getLevel() )
2166 return;
2168 PlayerLevelInfo info;
2169 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2171 PlayerClassLevelInfo classInfo;
2172 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2174 // send levelup info to client
2175 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2176 data << uint32(level);
2177 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2178 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2179 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2180 data << uint32(0);
2181 data << uint32(0);
2182 data << uint32(0);
2183 data << uint32(0);
2184 data << uint32(0);
2185 data << uint32(0);
2186 // end for
2187 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2188 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2190 GetSession()->SendPacket(&data);
2192 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2194 //update level, max level of skills
2195 if(getLevel()!= level)
2196 m_Played_time[1] = 0; // Level Played Time reset
2197 SetLevel(level);
2198 UpdateSkillsForLevel ();
2200 // save base values (bonuses already included in stored stats
2201 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2202 SetCreateStat(Stats(i), info.stats[i]);
2204 SetCreateHealth(classInfo.basehealth);
2205 SetCreateMana(classInfo.basemana);
2207 InitTalentForLevel();
2208 InitTaxiNodesForLevel();
2209 InitGlyphsForLevel();
2211 UpdateAllStats();
2213 // set current level health and mana/energy to maximum after applying all mods.
2214 SetHealth(GetMaxHealth());
2215 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2216 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2217 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2218 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2219 SetPower(POWER_FOCUS, 0);
2220 SetPower(POWER_HAPPINESS, 0);
2222 // give level to summoned pet
2223 Pet* pet = GetPet();
2224 if(pet && pet->getPetType()==SUMMON_PET)
2225 pet->GivePetLevel(level);
2226 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2229 void Player::InitTalentForLevel()
2231 uint32 level = getLevel();
2232 // talents base at level diff ( talents = level - 9 but some can be used already)
2233 if(level < 10)
2235 // Remove all talent points
2236 if(m_usedTalentCount > 0) // Free any used talents
2238 resetTalents(true);
2239 SetFreeTalentPoints(0);
2242 else
2244 uint32 talentPointsForLevel = CalculateTalentsPoints();
2246 // if used more that have then reset
2247 if(m_usedTalentCount > talentPointsForLevel)
2249 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2250 resetTalents(true);
2251 else
2252 SetFreeTalentPoints(0);
2254 // else update amount of free points
2255 else
2256 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2260 void Player::InitStatsForLevel(bool reapplyMods)
2262 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2263 _RemoveAllStatBonuses();
2265 PlayerClassLevelInfo classInfo;
2266 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2268 PlayerLevelInfo info;
2269 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2271 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2272 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2274 UpdateSkillsForLevel ();
2276 // set default cast time multiplier
2277 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2279 // reset size before reapply auras
2280 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2282 // save base values (bonuses already included in stored stats
2283 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2284 SetCreateStat(Stats(i), info.stats[i]);
2286 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2287 SetStat(Stats(i), info.stats[i]);
2289 SetCreateHealth(classInfo.basehealth);
2291 //set create powers
2292 SetCreateMana(classInfo.basemana);
2294 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2296 InitStatBuffMods();
2298 //reset rating fields values
2299 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2300 SetUInt32Value(index, 0);
2302 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2303 for (int i = 0; i < 7; i++)
2305 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2306 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2307 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2310 //reset attack power, damage and attack speed fields
2311 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2312 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2313 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2315 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2316 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2317 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2318 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2319 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2320 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2322 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2323 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2324 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2325 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2326 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2327 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2329 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2330 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2331 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2332 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2334 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2335 for (uint8 i = 0; i < 7; ++i)
2336 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2338 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2339 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2340 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2342 // Dodge percentage
2343 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2345 // set armor (resistance 0) to original value (create_agility*2)
2346 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2347 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2348 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2349 // set other resistance to original value (0)
2350 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2352 SetResistance(SpellSchools(i), 0);
2353 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2354 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2357 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2358 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2359 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2361 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2362 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2364 // Reset no reagent cost field
2365 for(int i = 0; i < 3; i++)
2366 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2367 // Init data for form but skip reapply item mods for form
2368 InitDataForForm(reapplyMods);
2370 // save new stats
2371 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2372 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2374 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2376 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2377 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2379 // cleanup unit flags (will be re-applied if need at aura load).
2380 RemoveFlag( UNIT_FIELD_FLAGS,
2381 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2382 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2383 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2384 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2385 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2386 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2388 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2390 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2391 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2393 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2394 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2396 // restore if need some important flags
2397 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2399 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2400 _ApplyAllStatBonuses();
2402 // set current level health and mana/energy to maximum after applying all mods.
2403 SetHealth(GetMaxHealth());
2404 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2405 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2406 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2407 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2408 SetPower(POWER_FOCUS, 0);
2409 SetPower(POWER_HAPPINESS, 0);
2410 SetPower(POWER_RUNIC_POWER, 0);
2413 void Player::SendInitialSpells()
2415 time_t curTime = time(NULL);
2416 time_t infTime = curTime + MONTH/2;
2418 uint16 spellCount = 0;
2420 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2421 data << uint8(0);
2423 size_t countPos = data.wpos();
2424 data << uint16(spellCount); // spell count placeholder
2426 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2428 if(itr->second->state == PLAYERSPELL_REMOVED)
2429 continue;
2431 if(!itr->second->active || itr->second->disabled)
2432 continue;
2434 data << uint16(itr->first);
2435 data << uint16(0); // it's not slot id
2437 spellCount +=1;
2440 data.put<uint16>(countPos,spellCount); // write real count value
2442 uint16 spellCooldowns = m_spellCooldowns.size();
2443 data << uint16(spellCooldowns);
2444 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2446 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2447 if(!sEntry)
2448 continue;
2450 // not send infinity cooldown
2451 if(itr->second.end > infTime)
2452 continue;
2454 data << uint16(itr->first);
2456 time_t cooldown = 0;
2457 if(itr->second.end > curTime)
2458 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2460 data << uint16(itr->second.itemid); // cast item id
2461 data << uint16(sEntry->Category); // spell category
2462 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2464 data << uint32(0); // cooldown
2465 data << uint32(cooldown); // category cooldown
2467 else
2469 data << uint32(cooldown); // cooldown
2470 data << uint32(0); // category cooldown
2474 GetSession()->SendPacket(&data);
2476 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2479 void Player::RemoveMail(uint32 id)
2481 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2483 if ((*itr)->messageID == id)
2485 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2486 m_mail.erase(itr);
2487 return;
2492 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2494 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2495 data << (uint32) mailId;
2496 data << (uint32) mailAction;
2497 data << (uint32) mailError;
2498 if ( mailError == MAIL_ERR_BAG_FULL )
2499 data << (uint32) equipError;
2500 else if( mailAction == MAIL_ITEM_TAKEN )
2502 data << (uint32) item_guid; // item guid low?
2503 data << (uint32) item_count; // item count?
2505 GetSession()->SendPacket(&data);
2508 void Player::SendNewMail()
2510 // deliver undelivered mail
2511 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2512 data << (uint32) 0;
2513 GetSession()->SendPacket(&data);
2516 void Player::UpdateNextMailTimeAndUnreads()
2518 // calculate next delivery time (min. from non-delivered mails
2519 // and recalculate unReadMail
2520 time_t cTime = time(NULL);
2521 m_nextMailDelivereTime = 0;
2522 unReadMails = 0;
2523 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2525 if((*itr)->deliver_time > cTime)
2527 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2528 m_nextMailDelivereTime = (*itr)->deliver_time;
2530 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2531 ++unReadMails;
2535 void Player::AddNewMailDeliverTime(time_t deliver_time)
2537 if(deliver_time <= time(NULL)) // ready now
2539 ++unReadMails;
2540 SendNewMail();
2542 else // not ready and no have ready mails
2544 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2545 m_nextMailDelivereTime = deliver_time;
2549 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2551 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2552 if (!spellInfo)
2554 // do character spell book cleanup (all characters)
2555 if(!IsInWorld() && !learning) // spell load case
2557 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2558 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2560 else
2561 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2563 return false;
2566 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2568 // do character spell book cleanup (all characters)
2569 if(!IsInWorld() && !learning) // spell load case
2571 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2572 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2574 else
2575 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2577 return false;
2580 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2582 bool dependent_set = false;
2583 bool disabled_case = false;
2584 bool superceded_old = false;
2586 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2587 if (itr != m_spells.end())
2589 uint32 next_active_spell_id = 0;
2590 // fix activate state for non-stackable low rank (and find next spell for !active case)
2591 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2593 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2594 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2596 if(HasSpell(next_itr->second))
2598 // high rank already known so this must !active
2599 active = false;
2600 next_active_spell_id = next_itr->second;
2601 break;
2606 // not do anything if already known in expected state
2607 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2608 itr->second->dependent == dependent && itr->second->disabled == disabled)
2610 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2611 itr->second->state = PLAYERSPELL_UNCHANGED;
2613 return false;
2616 // dependent spell known as not dependent, overwrite state
2617 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2619 itr->second->dependent = dependent;
2620 if (itr->second->state != PLAYERSPELL_NEW)
2621 itr->second->state = PLAYERSPELL_CHANGED;
2622 dependent_set = true;
2625 // update active state for known spell
2626 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2628 itr->second->active = active;
2630 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2631 itr->second->state = PLAYERSPELL_UNCHANGED;
2632 else if(itr->second->state != PLAYERSPELL_NEW)
2633 itr->second->state = PLAYERSPELL_CHANGED;
2635 if(active)
2637 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2638 CastSpell (this,spell_id,true);
2640 else if(IsInWorld())
2642 if(next_active_spell_id)
2644 // update spell ranks in spellbook and action bar
2645 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2646 data << uint16(spell_id);
2647 data << uint16(next_active_spell_id);
2648 GetSession()->SendPacket( &data );
2650 else
2652 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2653 data << uint16(spell_id);
2654 GetSession()->SendPacket(&data);
2658 return active; // learn (show in spell book if active now)
2661 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2663 if(itr->second->state != PLAYERSPELL_NEW)
2664 itr->second->state = PLAYERSPELL_CHANGED;
2665 itr->second->disabled = disabled;
2667 if(disabled)
2668 return false;
2670 disabled_case = true;
2672 else switch(itr->second->state)
2674 case PLAYERSPELL_UNCHANGED: // known saved spell
2675 return false;
2676 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2678 delete itr->second;
2679 m_spells.erase(itr);
2680 state = PLAYERSPELL_CHANGED;
2681 break; // need re-add
2683 default: // known not saved yet spell (new or modified)
2685 // can be in case spell loading but learned at some previous spell loading
2686 if(!IsInWorld() && !learning && !dependent_set)
2687 itr->second->state = PLAYERSPELL_UNCHANGED;
2689 return false;
2694 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2696 // talent: unlearn all other talent ranks (high and low)
2697 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2699 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2701 for(int i=0; i <5; ++i)
2703 // skip learning spell and no rank spell case
2704 uint32 rankSpellId = talentInfo->RankID[i];
2705 if(!rankSpellId || rankSpellId==spell_id)
2706 continue;
2708 removeSpell(rankSpellId);
2712 // non talent spell: learn low ranks (recursive call)
2713 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2715 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2716 addSpell(prev_spell,active,true,true,disabled);
2717 else // at normal learning
2718 learnSpell(prev_spell,true);
2721 PlayerSpell *newspell = new PlayerSpell;
2722 newspell->state = state;
2723 newspell->active = active;
2724 newspell->dependent = dependent;
2725 newspell->disabled = disabled;
2727 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2728 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2730 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2732 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2733 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2734 if(!i_spellInfo) continue;
2736 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2738 if(itr->second->active)
2740 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2742 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2744 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2745 data << uint16(itr->first);
2746 data << uint16(spell_id);
2747 GetSession()->SendPacket( &data );
2750 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2751 itr->second->active = false;
2752 if(itr->second->state != PLAYERSPELL_NEW)
2753 itr->second->state = PLAYERSPELL_CHANGED;
2754 superceded_old = true; // new spell replace old in action bars and spell book.
2756 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2758 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2760 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2761 data << uint16(spell_id);
2762 data << uint16(itr->first);
2763 GetSession()->SendPacket( &data );
2766 // mark new spell as disable (not learned yet for client and will not learned)
2767 newspell->active = false;
2768 if(newspell->state != PLAYERSPELL_NEW)
2769 newspell->state = PLAYERSPELL_CHANGED;
2776 m_spells[spell_id] = newspell;
2778 // return false if spell disabled
2779 if (newspell->disabled)
2780 return false;
2783 uint32 talentCost = GetTalentSpellCost(spell_id);
2785 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2786 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2787 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2789 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2790 CastSpell(this, spell_id, true);
2792 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2793 else if (IsPassiveSpell(spell_id))
2795 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2796 CastSpell(this, spell_id, true);
2798 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2800 CastSpell(this, spell_id, true);
2801 return false;
2804 // update used talent points count
2805 m_usedTalentCount += talentCost;
2807 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2808 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2810 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2811 SetFreePrimaryProffesions(freeProfs-1);
2814 // add dependent skills
2815 uint16 maxskill = GetMaxSkillValueForLevel();
2817 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2819 if(spellLearnSkill)
2821 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2822 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2824 if(skill_value < spellLearnSkill->value)
2825 skill_value = spellLearnSkill->value;
2827 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2829 if(skill_max_value < new_skill_max_value)
2830 skill_max_value = new_skill_max_value;
2832 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2834 else
2836 // not ranked skills
2837 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2838 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2840 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2842 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2843 if(!pSkill)
2844 continue;
2846 if(HasSkill(pSkill->id))
2847 continue;
2849 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2850 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2851 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2853 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2855 case SKILL_RANGE_LANGUAGE:
2856 SetSkill(pSkill->id, 300, 300 );
2857 break;
2858 case SKILL_RANGE_LEVEL:
2859 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2860 break;
2861 case SKILL_RANGE_MONO:
2862 SetSkill(pSkill->id, 1, 1 );
2863 break;
2864 default:
2865 break;
2871 // learn dependent spells
2872 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2873 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2875 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2877 if(!itr->second.autoLearned)
2879 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2880 addSpell(itr->second.spell,itr->second.active,true,true,false);
2881 else // at normal learning
2882 learnSpell(itr->second.spell,true);
2886 if(IsInWorld())
2888 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2889 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2892 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2893 return active && !disabled && !superceded_old;
2896 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2898 bool need_cast = false;
2900 switch(spellInfo->Id)
2902 // some spells not have stance data expacted cast at form change or present
2903 case 5420: need_cast = (m_form == FORM_TREE); break;
2904 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2905 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2906 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2907 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2908 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2909 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2910 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2911 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2912 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2913 // another spells have proper stance data
2914 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2917 //Check CasterAuraStates
2918 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
2921 void Player::learnSpell(uint32 spell_id, bool dependent)
2923 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2925 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2926 bool active = disabled ? itr->second->active : true;
2928 bool learning = addSpell(spell_id,active,true,dependent,false);
2930 // learn all disabled higher ranks (recursive)
2931 if(disabled)
2933 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2934 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2936 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2937 if (iter != m_spells.end() && iter->second->disabled)
2938 learnSpell(i->second,false);
2942 // prevent duplicated entires in spell book, also not send if not in world (loading)
2943 if(!learning || !IsInWorld ())
2944 return;
2946 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2947 data << uint32(spell_id);
2948 GetSession()->SendPacket(&data);
2951 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
2953 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2954 if (itr == m_spells.end())
2955 return;
2957 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2958 return;
2960 // unlearn non talent higher ranks (recursive)
2961 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2962 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2963 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2964 removeSpell(itr2->second,disabled);
2966 bool cur_active = itr->second->active;
2967 bool cur_dependent = itr->second->dependent;
2969 if (disabled)
2971 itr->second->disabled = disabled;
2972 if(itr->second->state != PLAYERSPELL_NEW)
2973 itr->second->state = PLAYERSPELL_CHANGED;
2975 else
2977 if(itr->second->state == PLAYERSPELL_NEW)
2979 delete itr->second;
2980 m_spells.erase(itr);
2982 else
2983 itr->second->state = PLAYERSPELL_REMOVED;
2986 RemoveAurasDueToSpell(spell_id);
2988 // remove pet auras
2989 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2990 RemovePetAura(petSpell);
2992 // free talent points
2993 uint32 talentCosts = GetTalentSpellCost(spell_id);
2994 if(talentCosts > 0)
2996 if(talentCosts < m_usedTalentCount)
2997 m_usedTalentCount -= talentCosts;
2998 else
2999 m_usedTalentCount = 0;
3002 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3003 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3005 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3006 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3007 SetFreePrimaryProffesions(freeProfs);
3010 // remove dependent skill
3011 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3012 if(spellLearnSkill)
3014 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3015 if(!prev_spell) // first rank, remove skill
3016 SetSkill(spellLearnSkill->skill,0,0);
3017 else
3019 // search prev. skill setting by spell ranks chain
3020 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3021 while(!prevSkill && prev_spell)
3023 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3024 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3027 if(!prevSkill) // not found prev skill setting, remove skill
3028 SetSkill(spellLearnSkill->skill,0,0);
3029 else // set to prev. skill setting values
3031 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3032 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3034 if(skill_value > prevSkill->value)
3035 skill_value = prevSkill->value;
3037 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3039 if(skill_max_value > new_skill_max_value)
3040 skill_max_value = new_skill_max_value;
3042 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3047 else
3049 // not ranked skills
3050 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3051 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3053 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3055 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3056 if(!pSkill)
3057 continue;
3059 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3060 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3061 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
3063 // not reset skills for professions and racial abilities
3064 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3065 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3066 continue;
3068 SetSkill(pSkill->id, 0, 0 );
3073 // remove dependent spells
3074 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3075 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3077 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3078 removeSpell(itr2->second.spell, disabled);
3080 // activate lesser rank in spellbook/action bar, and cast it if need
3081 bool prev_activate = false;
3083 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3085 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3087 // if talent then lesser rank also talent and need learn
3088 if(talentCosts)
3089 learnSpell (prev_id,false);
3090 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3091 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3093 // need manually update dependence state (learn spell ignore like attempts)
3094 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3095 if (prev_itr != m_spells.end())
3097 if(prev_itr->second->dependent != cur_dependent)
3099 prev_itr->second->dependent = cur_dependent;
3100 if(prev_itr->second->state != PLAYERSPELL_NEW)
3101 prev_itr->second->state = PLAYERSPELL_CHANGED;
3104 // now re-learn if need re-activate
3105 if(cur_active && !prev_itr->second->active)
3107 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3109 if(update_action_bar_for_low_rank)
3111 // downgrade spell ranks in spellbook and action bar
3112 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3113 data << uint16(spell_id);
3114 data << uint16(prev_id);
3115 GetSession()->SendPacket( &data );
3116 prev_activate = true;
3124 // remove from spell book if not replaced by lesser rank
3125 if(!prev_activate)
3127 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3128 data << uint16(spell_id);
3129 GetSession()->SendPacket(&data);
3133 void Player::RemoveArenaSpellCooldowns()
3135 // remove cooldowns on spells that has < 15 min CD
3136 SpellCooldowns::iterator itr, next;
3137 // iterate spell cooldowns
3138 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3140 next = itr;
3141 ++next;
3142 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3143 // check if spellentry is present and if the cooldown is less than 15 mins
3144 if( entry &&
3145 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3146 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3148 // notify player
3149 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3150 data << uint32(itr->first);
3151 data << GetGUID();
3152 GetSession()->SendPacket(&data);
3153 // remove cooldown
3154 m_spellCooldowns.erase(itr);
3159 void Player::RemoveAllSpellCooldown()
3161 if(!m_spellCooldowns.empty())
3163 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3165 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3166 data << uint32(itr->first);
3167 data << uint64(GetGUID());
3168 GetSession()->SendPacket(&data);
3170 m_spellCooldowns.clear();
3174 void Player::_LoadSpellCooldowns(QueryResult *result)
3176 // some cooldowns can be already set at aura loading...
3178 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3180 if(result)
3182 time_t curTime = time(NULL);
3186 Field *fields = result->Fetch();
3188 uint32 spell_id = fields[0].GetUInt32();
3189 uint32 item_id = fields[1].GetUInt32();
3190 time_t db_time = (time_t)fields[2].GetUInt64();
3192 if(!sSpellStore.LookupEntry(spell_id))
3194 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3195 continue;
3198 // skip outdated cooldown
3199 if(db_time <= curTime)
3200 continue;
3202 AddSpellCooldown(spell_id, item_id, db_time);
3204 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3206 while( result->NextRow() );
3208 delete result;
3212 void Player::_SaveSpellCooldowns()
3214 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3216 time_t curTime = time(NULL);
3217 time_t infTime = curTime + MONTH/2;
3219 // remove outdated and save active
3220 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3222 if(itr->second.end <= curTime)
3223 m_spellCooldowns.erase(itr++);
3224 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3226 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));
3227 ++itr;
3229 else
3230 ++itr;
3234 uint32 Player::resetTalentsCost() const
3236 // The first time reset costs 1 gold
3237 if(m_resetTalentsCost < 1*GOLD)
3238 return 1*GOLD;
3239 // then 5 gold
3240 else if(m_resetTalentsCost < 5*GOLD)
3241 return 5*GOLD;
3242 // After that it increases in increments of 5 gold
3243 else if(m_resetTalentsCost < 10*GOLD)
3244 return 10*GOLD;
3245 else
3247 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3248 if(months > 0)
3250 // This cost will be reduced by a rate of 5 gold per month
3251 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3252 // to a minimum of 10 gold.
3253 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3255 else
3257 // After that it increases in increments of 5 gold
3258 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3259 // until it hits a cap of 50 gold.
3260 if(new_cost > 50*GOLD)
3261 new_cost = 50*GOLD;
3262 return new_cost;
3267 bool Player::resetTalents(bool no_cost)
3269 // not need after this call
3270 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3272 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3273 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3276 uint32 talentPointsForLevel = CalculateTalentsPoints();
3278 if (m_usedTalentCount == 0)
3280 SetFreeTalentPoints(talentPointsForLevel);
3281 return false;
3284 uint32 cost = 0;
3286 if(!no_cost)
3288 cost = resetTalentsCost();
3290 if (GetMoney() < cost)
3292 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3293 return false;
3297 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3299 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3301 if (!talentInfo) continue;
3303 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3305 if(!talentTabInfo)
3306 continue;
3308 // unlearn only talents for character class
3309 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3310 // to prevent unexpected lost normal learned spell skip another class talents
3311 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3312 continue;
3314 for (int j = 0; j < 5; j++)
3316 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3318 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3320 ++itr;
3321 continue;
3324 // remove learned spells (all ranks)
3325 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3327 // unlearn if first rank is talent or learned by talent
3328 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3330 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3331 itr = GetSpellMap().begin();
3332 continue;
3334 else
3335 ++itr;
3340 SetFreeTalentPoints(talentPointsForLevel);
3342 if(!no_cost)
3344 ModifyMoney(-(int32)cost);
3345 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3347 m_resetTalentsCost = cost;
3348 m_resetTalentsTime = time(NULL);
3351 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3352 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3354 if(m_canTitanGrip)
3356 m_canTitanGrip = false;
3357 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3358 AutoUnequipOffhandIfNeed();
3361 return true;
3364 Mail* Player::GetMail(uint32 id)
3366 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3368 if ((*itr)->messageID == id)
3370 return (*itr);
3373 return NULL;
3376 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3378 if(target == this)
3380 Object::_SetCreateBits(updateMask, target);
3382 else
3384 for(uint16 index = 0; index < m_valuesCount; index++)
3386 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3387 updateMask->SetBit(index);
3392 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3394 if(target == this)
3396 Object::_SetUpdateBits(updateMask, target);
3398 else
3400 Object::_SetUpdateBits(updateMask, target);
3401 *updateMask &= updateVisualBits;
3405 void Player::InitVisibleBits()
3407 updateVisualBits.SetCount(PLAYER_END);
3409 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3410 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3411 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3412 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3413 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3414 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3415 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3416 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3417 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3418 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3419 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3420 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3421 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3422 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3423 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3424 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3425 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3426 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3427 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3428 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3429 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3430 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3431 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3432 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3433 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3434 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3435 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3436 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3437 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3438 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3439 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3440 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3441 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3442 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3443 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3444 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3445 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3446 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3447 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3448 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3449 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3450 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3451 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3452 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3453 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3454 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3455 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3456 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3457 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3458 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3459 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3460 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3461 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3462 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3463 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3465 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3466 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3467 updateVisualBits.SetBit(PLAYER_FLAGS);
3468 updateVisualBits.SetBit(PLAYER_GUILDID);
3469 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3470 updateVisualBits.SetBit(PLAYER_BYTES);
3471 updateVisualBits.SetBit(PLAYER_BYTES_2);
3472 updateVisualBits.SetBit(PLAYER_BYTES_3);
3473 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3474 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3476 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3477 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3478 updateVisualBits.SetBit(i);
3480 // Players visible items are not inventory stuff
3481 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3483 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3485 // item creator
3486 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3487 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3489 // item entry
3490 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3492 // item enchantments
3493 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3494 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3496 // random properties
3497 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3498 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3499 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3502 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3505 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3507 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3509 if(m_items[i] == NULL)
3510 continue;
3512 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3515 if(target == this)
3517 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3519 if(m_items[i] == NULL)
3520 continue;
3522 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3524 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3526 if(m_items[i] == NULL)
3527 continue;
3529 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3533 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3536 void Player::DestroyForPlayer( Player *target ) const
3538 Unit::DestroyForPlayer( target );
3540 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3542 if(m_items[i] == NULL)
3543 continue;
3545 m_items[i]->DestroyForPlayer( target );
3548 if(target == this)
3550 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3552 if(m_items[i] == NULL)
3553 continue;
3555 m_items[i]->DestroyForPlayer( target );
3557 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3559 if(m_items[i] == NULL)
3560 continue;
3562 m_items[i]->DestroyForPlayer( target );
3567 bool Player::HasSpell(uint32 spell) const
3569 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3570 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3571 !itr->second->disabled);
3574 bool Player::HasActiveSpell(uint32 spell) const
3576 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3577 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3578 itr->second->active && !itr->second->disabled);
3581 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3583 if (!trainer_spell)
3584 return TRAINER_SPELL_RED;
3586 if (!trainer_spell->learnedSpell)
3587 return TRAINER_SPELL_RED;
3589 // known spell
3590 if(HasSpell(trainer_spell->learnedSpell))
3591 return TRAINER_SPELL_GRAY;
3593 // check race/class requirement
3594 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3595 return TRAINER_SPELL_RED;
3597 // check level requirement
3598 if(getLevel() < trainer_spell->reqLevel)
3599 return TRAINER_SPELL_RED;
3601 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3603 // check prev.rank requirement
3604 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3605 return TRAINER_SPELL_RED;
3607 // check additional spell requirement
3608 if(spell_chain->req && !HasSpell(spell_chain->req))
3609 return TRAINER_SPELL_RED;
3612 // check skill requirement
3613 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3614 return TRAINER_SPELL_RED;
3616 // exist, already checked at loading
3617 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3619 // secondary prof. or not prof. spell
3620 uint32 skill = spell->EffectMiscValue[1];
3622 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3623 return TRAINER_SPELL_GREEN;
3625 // check primary prof. limit
3626 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3627 return TRAINER_SPELL_RED;
3629 return TRAINER_SPELL_GREEN;
3632 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3634 uint32 guid = GUID_LOPART(playerguid);
3636 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3637 // bones will be deleted by corpse/bones deleting thread shortly
3638 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3640 // remove from guild
3641 uint32 guildId = GetGuildIdFromDB(playerguid);
3642 if(guildId != 0)
3644 Guild* guild = objmgr.GetGuildById(guildId);
3645 if(guild)
3646 guild->DelMember(guid);
3649 // remove from arena teams
3650 LeaveAllArenaTeams(playerguid);
3652 // the player was uninvited already on logout so just remove from group
3653 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3654 if(resultGroup)
3656 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3657 delete resultGroup;
3658 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3659 if(group)
3661 RemoveFromGroup(group, playerguid);
3665 // remove signs from petitions (also remove petitions if owner);
3666 RemovePetitionsAndSigns(playerguid, 10);
3668 // return back all mails with COD and Item 0 1 2 3 4 5 6
3669 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);
3670 if(resultMail)
3674 Field *fields = resultMail->Fetch();
3676 uint32 mail_id = fields[0].GetUInt32();
3677 uint16 mailTemplateId= fields[1].GetUInt16();
3678 uint32 sender = fields[2].GetUInt32();
3679 std::string subject = fields[3].GetCppString();
3680 uint32 itemTextId = fields[4].GetUInt32();
3681 uint32 money = fields[5].GetUInt32();
3682 bool has_items = fields[6].GetBool();
3684 //we can return mail now
3685 //so firstly delete the old one
3686 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3688 MailItemsInfo mi;
3689 if(has_items)
3691 // data needs to be at first place for Item::LoadFromDB
3692 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);
3693 if(resultItems)
3697 Field *fields2 = resultItems->Fetch();
3699 uint32 item_guidlow = fields2[1].GetUInt32();
3700 uint32 item_template = fields2[2].GetUInt32();
3702 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3703 if(!itemProto)
3705 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3706 continue;
3709 Item *pItem = NewItemOrBag(itemProto);
3710 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3712 pItem->FSetState(ITEM_REMOVED);
3713 pItem->SaveToDB(); // it also deletes item object !
3714 continue;
3717 mi.AddItem(item_guidlow, item_template, pItem);
3719 while (resultItems->NextRow());
3721 delete resultItems;
3725 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3727 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3729 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3731 while (resultMail->NextRow());
3733 delete resultMail;
3736 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3737 // Get guids of character's pets, will deleted in transaction
3738 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3740 // NOW we can finally clear other DB data related to character
3741 CharacterDatabase.BeginTransaction();
3742 if (resultPets)
3746 Field *fields3 = resultPets->Fetch();
3747 uint32 petguidlow = fields3[0].GetUInt32();
3748 Pet::DeleteFromDB(petguidlow);
3749 } while (resultPets->NextRow());
3750 delete resultPets;
3753 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3754 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3755 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3756 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3757 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3758 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3759 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3760 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3761 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3762 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3763 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3764 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3765 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3766 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3767 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3768 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3769 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3770 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3771 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3772 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3773 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3774 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3775 CharacterDatabase.CommitTransaction();
3777 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3778 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3781 void Player::SetMovement(PlayerMovementType pType)
3783 WorldPacket data;
3784 switch(pType)
3786 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3787 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3788 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3789 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3790 default:
3791 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3792 return;
3794 data.append(GetPackGUID());
3795 data << uint32(0);
3796 GetSession()->SendPacket( &data );
3799 /* Preconditions:
3800 - a resurrectable corpse must not be loaded for the player (only bones)
3801 - the player must be in world
3803 void Player::BuildPlayerRepop()
3805 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3806 data.append(GetPackGUID());
3807 GetSession()->SendPacket(&data);
3809 if(getRace() == RACE_NIGHTELF)
3810 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)
3811 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3813 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3814 // there must be SMSG.STOP_MIRROR_TIMER
3815 // there we must send 888 opcode
3817 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3818 if(GetCorpse())
3820 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3821 assert(false);
3824 // create a corpse and place it at the player's location
3825 CreateCorpse();
3826 Corpse *corpse = GetCorpse();
3827 if(!corpse)
3829 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3830 return;
3832 GetMap()->Add(corpse);
3834 // convert player body to ghost
3835 SetHealth( 1 );
3837 SetMovement(MOVE_WATER_WALK);
3838 if(!GetSession()->isLogingOut())
3839 SetMovement(MOVE_UNROOT);
3841 // BG - remove insignia related
3842 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3844 SendCorpseReclaimDelay();
3846 // to prevent cheating
3847 corpse->ResetGhostTime();
3849 StopMirrorTimers(); //disable timers(bars)
3851 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3853 // set and clear other
3854 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3857 void Player::SendDelayResponse(const uint32 ml_seconds)
3859 //FIXME: is this delay time arg really need? 50msec by default in code
3860 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3861 data << (uint32)time(NULL);
3862 data << (uint32)0;
3863 GetSession()->SendPacket( &data );
3866 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3868 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3869 data << uint32(-1);
3870 data << float(0);
3871 data << float(0);
3872 data << float(0);
3873 GetSession()->SendPacket(&data);
3875 // speed change, land walk
3877 // remove death flag + set aura
3878 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3879 if(getRace() == RACE_NIGHTELF)
3880 RemoveAurasDueToSpell(20584); // speed bonuses
3881 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3883 setDeathState(ALIVE);
3885 SetMovement(MOVE_LAND_WALK);
3886 SetMovement(MOVE_UNROOT);
3888 m_deathTimer = 0;
3890 // set health/powers (0- will be set in caller)
3891 if(restore_percent>0.0f)
3893 SetHealth(uint32(GetMaxHealth()*restore_percent));
3894 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3895 SetPower(POWER_RAGE, 0);
3896 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3899 // trigger update zone for alive state zone updates
3900 UpdateZone(GetZoneId());
3902 // update visibility
3903 ObjectAccessor::UpdateVisibilityForPlayer(this);
3905 if(!applySickness)
3906 return;
3908 //Characters from level 1-10 are not affected by resurrection sickness.
3909 //Characters from level 11-19 will suffer from one minute of sickness
3910 //for each level they are above 10.
3911 //Characters level 20 and up suffer from ten minutes of sickness.
3912 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3914 if(int32(getLevel()) >= startLevel)
3916 // set resurrection sickness
3917 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3919 // not full duration
3920 if(int32(getLevel()) < startLevel+9)
3922 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3924 for(int i =0; i < 3; ++i)
3926 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3928 Aur->SetAuraDuration(delta*IN_MILISECONDS);
3929 Aur->SendAuraUpdate(false);
3936 void Player::KillPlayer()
3938 SetMovement(MOVE_ROOT);
3940 StopMirrorTimers(); //disable timers(bars)
3942 setDeathState(CORPSE);
3943 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3945 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3946 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3948 // 6 minutes until repop at graveyard
3949 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
3951 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3953 // don't create corpse at this moment, player might be falling
3955 // update visibility
3956 ObjectAccessor::UpdateObjectVisibility(this);
3959 void Player::CreateCorpse()
3961 // prevent existence 2 corpse for player
3962 SpawnCorpseBones();
3964 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3966 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3967 SetPvPDeath(false);
3969 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
3971 delete corpse;
3972 return;
3975 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3976 _pb = GetUInt32Value(PLAYER_BYTES);
3977 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3979 uint8 race = (uint8)(_uf);
3980 uint8 skin = (uint8)(_pb);
3981 uint8 face = (uint8)(_pb >> 8);
3982 uint8 hairstyle = (uint8)(_pb >> 16);
3983 uint8 haircolor = (uint8)(_pb >> 24);
3984 uint8 facialhair = (uint8)(_pb2);
3986 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3987 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3989 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3990 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3992 uint32 flags = CORPSE_FLAG_UNK2;
3993 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3994 flags |= CORPSE_FLAG_HIDE_HELM;
3995 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3996 flags |= CORPSE_FLAG_HIDE_CLOAK;
3997 if(InBattleGround())
3998 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3999 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4001 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4003 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4005 uint32 iDisplayID;
4006 uint16 iIventoryType;
4007 uint32 _cfi;
4008 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
4010 if(m_items[i])
4012 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4013 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4015 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4016 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4020 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4021 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4022 assert(entry);
4023 if(entry->map_type != MAP_BATTLEGROUND)
4024 corpse->SaveToDB();
4026 // register for player, but not show
4027 ObjectAccessor::Instance().AddCorpse(corpse);
4030 void Player::SpawnCorpseBones()
4032 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4033 SaveToDB(); // prevent loading as ghost without corpse
4036 Corpse* Player::GetCorpse() const
4038 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4041 void Player::DurabilityLossAll(double percent, bool inventory)
4043 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4044 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4045 DurabilityLoss(pItem,percent);
4047 if(inventory)
4049 // bags not have durability
4050 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4052 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4053 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4054 DurabilityLoss(pItem,percent);
4056 // keys not have durability
4057 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4059 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4060 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4061 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4062 if(Item* pItem = GetItemByPos( i, j ))
4063 DurabilityLoss(pItem,percent);
4067 void Player::DurabilityLoss(Item* item, double percent)
4069 if(!item )
4070 return;
4072 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4074 if(!pMaxDurability)
4075 return;
4077 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4079 if(pDurabilityLoss < 1 )
4080 pDurabilityLoss = 1;
4082 DurabilityPointsLoss(item,pDurabilityLoss);
4085 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4087 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4088 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4089 DurabilityPointsLoss(pItem,points);
4091 if(inventory)
4093 // bags not have durability
4094 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4096 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4097 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4098 DurabilityPointsLoss(pItem,points);
4100 // keys not have durability
4101 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4103 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4104 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4105 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4106 if(Item* pItem = GetItemByPos( i, j ))
4107 DurabilityPointsLoss(pItem,points);
4111 void Player::DurabilityPointsLoss(Item* item, int32 points)
4113 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4114 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4115 int32 pNewDurability = pOldDurability - points;
4117 if (pNewDurability < 0)
4118 pNewDurability = 0;
4119 else if (pNewDurability > pMaxDurability)
4120 pNewDurability = pMaxDurability;
4122 if (pOldDurability != pNewDurability)
4124 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4125 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4126 _ApplyItemMods(item,item->GetSlot(), false);
4128 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4130 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4131 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4132 _ApplyItemMods(item,item->GetSlot(), true);
4134 item->SetState(ITEM_CHANGED, this);
4138 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4140 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4141 DurabilityPointsLoss(pItem,1);
4144 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4146 uint32 TotalCost = 0;
4147 // equipped, backpack, bags itself
4148 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4149 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4151 // bank, buyback and keys not repaired
4153 // items in inventory bags
4154 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4155 for(int i = 0; i < MAX_BAG_SIZE; i++)
4156 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4157 return TotalCost;
4160 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4162 Item* item = GetItemByPos(pos);
4164 uint32 TotalCost = 0;
4165 if(!item)
4166 return TotalCost;
4168 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4169 if(!maxDurability)
4170 return TotalCost;
4172 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4174 if(cost)
4176 uint32 LostDurability = maxDurability - curDurability;
4177 if(LostDurability>0)
4179 ItemPrototype const *ditemProto = item->GetProto();
4181 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4182 if(!dcost)
4184 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4185 return TotalCost;
4188 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4189 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4190 if(!dQualitymodEntry)
4192 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4193 return TotalCost;
4196 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4197 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4199 costs = uint32(costs * discountMod);
4201 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4202 costs = 1;
4204 if (guildBank)
4206 if (GetGuildId()==0)
4208 DEBUG_LOG("You are not member of a guild");
4209 return TotalCost;
4212 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4213 if (!pGuild)
4214 return TotalCost;
4216 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4218 DEBUG_LOG("You do not have rights to withdraw for repairs");
4219 return TotalCost;
4222 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4224 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4225 return TotalCost;
4228 if (pGuild->GetGuildBankMoney() < costs)
4230 DEBUG_LOG("There is not enough money in bank");
4231 return TotalCost;
4234 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4235 TotalCost = costs;
4237 else if (GetMoney() < costs)
4239 DEBUG_LOG("You do not have enough money");
4240 return TotalCost;
4242 else
4243 ModifyMoney( -int32(costs) );
4247 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4248 item->SetState(ITEM_CHANGED, this);
4250 // reapply mods for total broken and repaired item if equipped
4251 if(IsEquipmentPos(pos) && !curDurability)
4252 _ApplyItemMods(item,pos & 255, true);
4253 return TotalCost;
4256 void Player::RepopAtGraveyard()
4258 // note: this can be called also when the player is alive
4259 // for example from WorldSession::HandleMovementOpcodes
4261 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4263 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4264 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4266 ResurrectPlayer(0.5f);
4267 SpawnCorpseBones();
4270 WorldSafeLocsEntry const *ClosestGrave = NULL;
4272 // Special handle for battleground maps
4273 if( BattleGround *bg = GetBattleGround() )
4274 ClosestGrave = bg->GetClosestGraveYard(this);
4275 else
4276 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4278 // stop countdown until repop
4279 m_deathTimer = 0;
4281 // if no grave found, stay at the current location
4282 // and don't show spirit healer location
4283 if(ClosestGrave)
4285 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4286 if(isDead()) // not send if alive, because it used in TeleportTo()
4288 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4289 data << ClosestGrave->map_id;
4290 data << ClosestGrave->x;
4291 data << ClosestGrave->y;
4292 data << ClosestGrave->z;
4293 GetSession()->SendPacket(&data);
4298 void Player::JoinedChannel(Channel *c)
4300 m_channels.push_back(c);
4303 void Player::LeftChannel(Channel *c)
4305 m_channels.remove(c);
4308 void Player::CleanupChannels()
4310 while(!m_channels.empty())
4312 Channel* ch = *m_channels.begin();
4313 m_channels.erase(m_channels.begin()); // remove from player's channel list
4314 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4315 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4316 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4319 sLog.outDebug("Player: channels cleaned up!");
4322 void Player::UpdateLocalChannels(uint32 newZone )
4324 if(m_channels.empty())
4325 return;
4327 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4328 if(!current_zone)
4329 return;
4331 ChannelMgr* cMgr = channelMgr(GetTeam());
4332 if(!cMgr)
4333 return;
4335 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4337 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4339 next = i; ++next;
4341 // skip non built-in channels
4342 if(!(*i)->IsConstant())
4343 continue;
4345 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4346 if(!ch)
4347 continue;
4349 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4350 continue;
4352 // new channel
4353 char new_channel_name_buf[100];
4354 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4355 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4357 if((*i)!=new_channel)
4359 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4361 // leave old channel
4362 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4363 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4364 LeftChannel(*i); // remove from player's channel list
4365 cMgr->LeftChannel(name); // delete if empty
4368 sLog.outDebug("Player: channels cleaned up!");
4371 void Player::LeaveLFGChannel()
4373 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4375 if((*i)->IsLFG())
4377 (*i)->Leave(GetGUID());
4378 break;
4383 void Player::UpdateDefense()
4385 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4387 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4389 // update dependent from defense skill part
4390 UpdateDefenseBonusesMod();
4394 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4396 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4398 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4399 return;
4402 float val = 1.0f;
4404 switch(modType)
4406 case FLAT_MOD:
4407 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4408 break;
4409 case PCT_MOD:
4410 if(amount <= -100.0f)
4411 amount = -200.0f;
4413 val = (100.0f + amount) / 100.0f;
4414 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4415 break;
4418 if(!CanModifyStats())
4419 return;
4421 switch(modGroup)
4423 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4424 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4425 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4426 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4427 default: break;
4431 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4433 if(modGroup >= BASEMOD_END || modType > MOD_END)
4435 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4436 return 0.0f;
4439 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4440 return 0.0f;
4442 return m_auraBaseMod[modGroup][modType];
4445 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4447 if(modGroup >= BASEMOD_END)
4449 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4450 return 0.0f;
4453 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4454 return 0.0f;
4456 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4459 uint32 Player::GetShieldBlockValue() const
4461 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4463 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH) * 0.5f - 10;
4465 value = (value < 0) ? 0 : value;
4467 return uint32(value);
4470 float Player::GetMeleeCritFromAgility()
4472 uint32 level = getLevel();
4473 uint32 pclass = getClass();
4475 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4477 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4478 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4479 if (critBase==NULL || critRatio==NULL)
4480 return 0.0f;
4482 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4483 return crit*100.0f;
4486 float Player::GetDodgeFromAgility()
4488 // Table for base dodge values
4489 float dodge_base[MAX_CLASSES] = {
4490 0.0075f, // Warrior
4491 0.00652f, // Paladin
4492 -0.0545f, // Hunter
4493 -0.0059f, // Rogue
4494 0.03183f, // Priest
4495 0.0114f, // DK
4496 0.0167f, // Shaman
4497 0.034575f, // Mage
4498 0.02011f, // Warlock
4499 0.0f, // ??
4500 -0.0187f // Druid
4502 // Crit/agility to dodge/agility coefficient multipliers
4503 float crit_to_dodge[MAX_CLASSES] = {
4504 1.1f, // Warrior
4505 1.0f, // Paladin
4506 1.6f, // Hunter
4507 2.0f, // Rogue
4508 1.0f, // Priest
4509 1.0f, // DK?
4510 1.0f, // Shaman
4511 1.0f, // Mage
4512 1.0f, // Warlock
4513 0.0f, // ??
4514 1.7f // Druid
4517 uint32 level = getLevel();
4518 uint32 pclass = getClass();
4520 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4522 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4523 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4524 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4525 return 0.0f;
4527 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4528 return dodge*100.0f;
4531 float Player::GetSpellCritFromIntellect()
4533 uint32 level = getLevel();
4534 uint32 pclass = getClass();
4536 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4538 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4539 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4540 if (critBase==NULL || critRatio==NULL)
4541 return 0.0f;
4543 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4544 return crit*100.0f;
4547 float Player::GetRatingCoefficient(CombatRating cr) const
4549 uint32 level = getLevel();
4551 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4553 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4554 if (Rating == NULL)
4555 return 1.0f; // By default use minimum coefficient (not must be called)
4557 return Rating->ratio;
4560 float Player::GetRatingBonusValue(CombatRating cr) const
4562 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4565 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4567 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4568 if (melee>25.0f) melee = 25.0f;
4569 return uint32 (melee * damage /100.0f);
4572 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4574 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4575 if (ranged>25.0f) ranged=25.0f;
4576 return uint32 (ranged * damage /100.0f);
4579 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4581 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4582 // In wow script resilience limited to 25%
4583 if (spell>25.0f)
4584 spell = 25.0f;
4585 return uint32 (spell * damage / 100.0f);
4588 uint32 Player::GetDotDamageReduction(uint32 damage) const
4590 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4591 // Dot resilience not limited (limit it by 100%)
4592 if (spellDot > 100.0f)
4593 spellDot = 100.0f;
4594 return uint32 (spellDot * damage / 100.0f);
4597 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4599 switch (attType)
4601 case BASE_ATTACK:
4602 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4603 case OFF_ATTACK:
4604 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4605 default:
4606 break;
4608 return 0.0f;
4611 float Player::OCTRegenHPPerSpirit()
4613 uint32 level = getLevel();
4614 uint32 pclass = getClass();
4616 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4618 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4619 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4620 if (baseRatio==NULL || moreRatio==NULL)
4621 return 0.0f;
4623 // Formula from PaperDollFrame script
4624 float spirit = GetStat(STAT_SPIRIT);
4625 float baseSpirit = spirit;
4626 if (baseSpirit>50) baseSpirit = 50;
4627 float moreSpirit = spirit - baseSpirit;
4628 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4629 return regen;
4632 float Player::OCTRegenMPPerSpirit()
4634 uint32 level = getLevel();
4635 uint32 pclass = getClass();
4637 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4639 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4640 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4641 if (moreRatio==NULL)
4642 return 0.0f;
4644 // Formula get from PaperDollFrame script
4645 float spirit = GetStat(STAT_SPIRIT);
4646 float regen = spirit * moreRatio->ratio;
4647 return regen;
4650 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4652 m_baseRatingValue[cr]+=(apply ? value : -value);
4654 int32 amount = uint32(m_baseRatingValue[cr]);
4655 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4656 // stat used stored in miscValueB for this aura
4657 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4658 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4659 if ((*i)->GetMiscValue() & (1<<cr))
4660 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4661 if (amount < 0)
4662 amount = 0;
4663 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4665 float RatingCoeffecient = GetRatingCoefficient(cr);
4666 float RatingChange = 0.0f;
4668 bool affectStats = CanModifyStats();
4670 switch (cr)
4672 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4673 case CR_DEFENSE_SKILL:
4674 UpdateDefenseBonusesMod();
4675 break;
4676 case CR_DODGE:
4677 UpdateDodgePercentage();
4678 break;
4679 case CR_PARRY:
4680 UpdateParryPercentage();
4681 break;
4682 case CR_BLOCK:
4683 UpdateBlockPercentage();
4684 break;
4685 case CR_HIT_MELEE:
4686 UpdateMeleeHitChances();
4687 break;
4688 case CR_HIT_RANGED:
4689 UpdateRangedHitChances();
4690 break;
4691 case CR_HIT_SPELL:
4692 UpdateSpellHitChances();
4693 break;
4694 case CR_CRIT_MELEE:
4695 if(affectStats)
4697 UpdateCritPercentage(BASE_ATTACK);
4698 UpdateCritPercentage(OFF_ATTACK);
4700 break;
4701 case CR_CRIT_RANGED:
4702 if(affectStats)
4703 UpdateCritPercentage(RANGED_ATTACK);
4704 break;
4705 case CR_CRIT_SPELL:
4706 if(affectStats)
4707 UpdateAllSpellCritChances();
4708 break;
4709 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4710 case CR_HIT_TAKEN_RANGED:
4711 break;
4712 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4713 break;
4714 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4715 case CR_CRIT_TAKEN_RANGED:
4716 break;
4717 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4718 break;
4719 case CR_HASTE_MELEE:
4720 RatingChange = value / RatingCoeffecient;
4721 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4722 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4723 break;
4724 case CR_HASTE_RANGED:
4725 RatingChange = value / RatingCoeffecient;
4726 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4727 break;
4728 case CR_HASTE_SPELL:
4729 RatingChange = value / RatingCoeffecient;
4730 ApplyCastTimePercentMod(RatingChange,apply);
4731 break;
4732 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4733 case CR_WEAPON_SKILL_OFFHAND:
4734 case CR_WEAPON_SKILL_RANGED:
4735 break;
4736 case CR_EXPERTISE:
4737 if(affectStats)
4739 UpdateExpertise(BASE_ATTACK);
4740 UpdateExpertise(OFF_ATTACK);
4742 break;
4746 void Player::SetRegularAttackTime()
4748 for(int i = 0; i < MAX_ATTACK; ++i)
4750 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4751 if(tmpitem && !tmpitem->IsBroken())
4753 ItemPrototype const *proto = tmpitem->GetProto();
4754 if(proto->Delay)
4755 SetAttackTime(WeaponAttackType(i), proto->Delay);
4756 else
4757 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4762 //skill+step, checking for max value
4763 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4765 if(!skill_id)
4766 return false;
4768 uint16 i=0;
4769 for (; i < PLAYER_MAX_SKILLS; i++)
4770 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4771 break;
4773 if(i>=PLAYER_MAX_SKILLS)
4774 return false;
4776 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4777 uint32 value = SKILL_VALUE(data);
4778 uint32 max = SKILL_MAX(data);
4780 if ((!max) || (!value) || (value >= max))
4781 return false;
4783 if (value*512 < max*urand(0,512))
4785 uint32 new_value = value+step;
4786 if(new_value > max)
4787 new_value = max;
4789 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4790 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4791 return true;
4794 return false;
4797 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4799 if ( SkillValue >= GrayLevel )
4800 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4801 if ( SkillValue >= GreenLevel )
4802 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4803 if ( SkillValue >= YellowLevel )
4804 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4805 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4808 bool Player::UpdateCraftSkill(uint32 spellid)
4810 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4812 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4813 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4815 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4817 if(_spell_idx->second->skillId)
4819 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4821 // Alchemy Discoveries here
4822 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4823 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4825 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4826 learnSpell(discoveredSpell,false);
4829 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4831 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4832 _spell_idx->second->max_value,
4833 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4834 _spell_idx->second->min_value),
4835 craft_skill_gain);
4838 return false;
4841 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4843 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4845 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4847 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4848 switch (SkillId)
4850 case SKILL_HERBALISM:
4851 case SKILL_LOCKPICKING:
4852 case SKILL_JEWELCRAFTING:
4853 case SKILL_INSCRIPTION:
4854 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4855 case SKILL_SKINNING:
4856 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4857 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4858 else
4859 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4860 case SKILL_MINING:
4861 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4862 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4863 else
4864 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4866 return false;
4869 bool Player::UpdateFishingSkill()
4871 sLog.outDebug("UpdateFishingSkill");
4873 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4875 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4877 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4879 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4882 // levels sync. with spell requirement for skill levels to learn
4883 // bonus abilities in sSkillLineAbilityStore
4884 // Used only to avoid scan DBC at each skill grow
4885 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4887 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4889 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4890 if ( !SkillId )
4891 return false;
4893 if(Chance <= 0) // speedup in 0 chance case
4895 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4896 return false;
4899 uint16 i=0;
4900 for (; i < PLAYER_MAX_SKILLS; i++)
4901 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4902 if ( i >= PLAYER_MAX_SKILLS )
4903 return false;
4905 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4906 uint16 SkillValue = SKILL_VALUE(data);
4907 uint16 MaxValue = SKILL_MAX(data);
4909 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4910 return false;
4912 int32 Roll = irand(1,1000);
4914 if ( Roll <= Chance )
4916 uint32 new_value = SkillValue+step;
4917 if(new_value > MaxValue)
4918 new_value = MaxValue;
4920 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4921 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4923 if((SkillValue < *bsl && new_value >= *bsl))
4925 learnSkillRewardedSpells( SkillId, new_value);
4926 break;
4929 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4930 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4931 return true;
4934 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4935 return false;
4938 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4940 // no skill gain in pvp
4941 Unit *pVictim = getVictim();
4942 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4943 return;
4945 if(IsInFeralForm())
4946 return; // always maximized SKILL_FERAL_COMBAT in fact
4948 if(m_form == FORM_TREE)
4949 return; // use weapon but not skill up
4951 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4953 switch(attType)
4955 case BASE_ATTACK:
4957 Item *tmpitem = GetWeaponForAttack(attType,true);
4959 if (!tmpitem)
4960 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4961 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4962 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4963 break;
4965 case OFF_ATTACK:
4966 case RANGED_ATTACK:
4968 Item *tmpitem = GetWeaponForAttack(attType,true);
4969 if (tmpitem)
4970 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4971 break;
4974 UpdateAllCritPercentages();
4977 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
4979 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4980 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4981 uint32 moblevel = pVictim->getLevelForTarget(this);
4982 if(moblevel < greylevel)
4983 return;
4985 if (moblevel > plevel + 5)
4986 moblevel = plevel + 5;
4988 uint32 lvldif = moblevel - greylevel;
4989 if(lvldif < 3)
4990 lvldif = 3;
4992 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4993 if(skilldif <= 0)
4994 return;
4996 float chance = float(3 * lvldif * skilldif) / plevel;
4997 if(!defence)
4999 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5000 chance *= 0.1f * GetStat(STAT_INTELLECT);
5003 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5005 if(roll_chance_f(chance))
5007 if(defence)
5008 UpdateDefense();
5009 else
5010 UpdateWeaponSkill(attType);
5012 else
5013 return;
5016 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5018 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5019 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5021 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5022 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5023 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5025 if(talent) // permanent bonus stored in high part
5026 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5027 else // temporary/item bonus stored in low part
5028 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5029 return;
5033 void Player::UpdateSkillsForLevel()
5035 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5036 uint32 maxSkill = GetMaxSkillValueForLevel();
5038 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5040 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5041 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5043 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5045 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5046 if(!pSkill)
5047 continue;
5049 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5050 continue;
5052 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5053 uint32 max = SKILL_MAX(data);
5054 uint32 val = SKILL_VALUE(data);
5056 /// update only level dependent max skill values
5057 if(max!=1)
5059 /// miximize skill always
5060 if(alwaysMaxSkill)
5061 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5062 /// update max skill value if current max skill not maximized
5063 else if(max != maxconfskill)
5064 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5069 void Player::UpdateSkillsToMaxSkillsForLevel()
5071 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5072 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5074 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5075 if( IsProfessionOrRidingSkill(pskill))
5076 continue;
5077 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5079 uint32 max = SKILL_MAX(data);
5081 if(max > 1)
5082 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5084 if(pskill == SKILL_DEFENSE)
5085 UpdateDefenseBonusesMod();
5089 // This functions sets a skill line value (and adds if doesn't exist yet)
5090 // To "remove" a skill line, set it's values to zero
5091 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5093 if(!id)
5094 return;
5096 uint16 i=0;
5097 for (; i < PLAYER_MAX_SKILLS; i++)
5098 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5100 if(i<PLAYER_MAX_SKILLS) //has skill
5102 if(currVal)
5104 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5105 learnSkillRewardedSpells(id, currVal);
5106 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5108 else //remove
5110 // clear skill fields
5111 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5112 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5113 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5115 // remove all spells that related to this skill
5116 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5117 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5118 if (pAbility->skillId==id)
5119 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5122 else if(currVal) //add
5124 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5125 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5127 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5128 if(!pSkill)
5130 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5131 return;
5133 // enable unlearn button for primary professions only
5134 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5135 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5136 else
5137 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5138 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5139 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
5141 // apply skill bonuses
5142 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5144 // temporary bonuses
5145 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5146 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5147 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5148 (*i)->ApplyModifier(true);
5150 // permanent bonuses
5151 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5152 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5153 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5154 (*i)->ApplyModifier(true);
5156 // Learn all spells for skill
5157 learnSkillRewardedSpells(id, currVal);
5158 return;
5163 bool Player::HasSkill(uint32 skill) const
5165 if(!skill)return false;
5166 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5168 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5170 return true;
5173 return false;
5176 uint16 Player::GetSkillValue(uint32 skill) const
5178 if(!skill)
5179 return 0;
5181 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5183 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5185 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5187 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5188 result += SKILL_TEMP_BONUS(bonus);
5189 result += SKILL_PERM_BONUS(bonus);
5190 return result < 0 ? 0 : result;
5193 return 0;
5196 uint16 Player::GetMaxSkillValue(uint32 skill) const
5198 if(!skill)return 0;
5199 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5201 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5203 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5205 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5206 result += SKILL_TEMP_BONUS(bonus);
5207 result += SKILL_PERM_BONUS(bonus);
5208 return result < 0 ? 0 : result;
5211 return 0;
5214 uint16 Player::GetPureMaxSkillValue(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_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5224 return 0;
5227 uint16 Player::GetBaseSkillValue(uint32 skill) const
5229 if(!skill)return 0;
5230 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5232 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5234 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5235 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5236 return result < 0 ? 0 : result;
5239 return 0;
5242 uint16 Player::GetPureSkillValue(uint32 skill) const
5244 if(!skill)return 0;
5245 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5247 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5249 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5252 return 0;
5255 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5257 if(!skill)
5258 return 0;
5260 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5262 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5264 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5268 return 0;
5271 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5273 if(!skill)
5274 return 0;
5276 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5278 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5280 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5284 return 0;
5287 void Player::SendInitialActionButtons()
5289 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5291 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5292 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5294 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5295 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5297 data << uint16(itr->second.action);
5298 data << uint8(itr->second.misc);
5299 data << uint8(itr->second.type);
5301 else
5303 data << uint32(0);
5307 GetSession()->SendPacket( &data );
5308 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5311 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5313 if(button >= MAX_ACTION_BUTTONS)
5315 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5316 return;
5319 // check cheating with adding non-known spells to action bar
5320 if(type==ACTION_BUTTON_SPELL)
5322 if(!sSpellStore.LookupEntry(action))
5324 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5325 return;
5328 if(!HasSpell(action))
5330 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5331 return;
5335 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5337 if (buttonItr==m_actionButtons.end())
5338 { // just add new button
5339 m_actionButtons[button] = ActionButton(action,type,misc);
5341 else
5342 { // change state of current button
5343 ActionButtonUpdateState uState = buttonItr->second.uState;
5344 buttonItr->second = ActionButton(action,type,misc);
5345 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5348 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5351 void Player::removeActionButton(uint8 button)
5353 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5354 if (buttonItr==m_actionButtons.end())
5355 return;
5357 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5358 m_actionButtons.erase(buttonItr); // new and not saved
5359 else
5360 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5362 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5365 void Player::SetDontMove(bool dontMove)
5367 m_dontMove = dontMove;
5370 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5372 // prevent crash when a bad coord is sent by the client
5373 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5375 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5376 return false;
5379 Map *m = GetMap();
5381 const float old_x = GetPositionX();
5382 const float old_y = GetPositionY();
5383 const float old_z = GetPositionZ();
5384 const float old_r = GetOrientation();
5386 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5388 if (teleport || old_x != x || old_y != y || old_z != z)
5389 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5390 else
5391 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5393 // move and update visible state if need
5394 m->PlayerRelocation(this, x, y, z, orientation);
5396 // reread after Map::Relocation
5397 m = GetMap();
5398 x = GetPositionX();
5399 y = GetPositionY();
5400 z = GetPositionZ();
5402 // group update
5403 if(GetGroup() && (old_x != x || old_y != y))
5404 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5407 // code block for underwater state update
5408 UpdateUnderwaterState(m, x, y, z);
5410 CheckExploreSystem();
5412 return true;
5415 void Player::SaveRecallPosition()
5417 m_recallMap = GetMapId();
5418 m_recallX = GetPositionX();
5419 m_recallY = GetPositionY();
5420 m_recallZ = GetPositionZ();
5421 m_recallO = GetOrientation();
5424 void Player::SendMessageToSet(WorldPacket *data, bool self)
5426 GetMap()->MessageBroadcast(this, data, self);
5429 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5431 GetMap()->MessageDistBroadcast(this, data, dist, self);
5434 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5436 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5439 void Player::SendDirectMessage(WorldPacket *data)
5441 GetSession()->SendPacket(data);
5444 void Player::CheckExploreSystem()
5446 if (!isAlive())
5447 return;
5449 if (isInFlight())
5450 return;
5452 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5453 if(areaFlag==0xffff)
5454 return;
5455 int offset = areaFlag / 32;
5457 if(offset >= 128)
5459 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);
5460 return;
5463 uint32 val = (uint32)(1 << (areaFlag % 32));
5464 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5466 if( !(currFields & val) )
5468 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5470 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5472 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5473 if(!p)
5475 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5477 else if(p->area_level > 0)
5479 uint32 area = p->ID;
5480 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5482 SendExplorationExperience(area,0);
5484 else
5486 int32 diff = int32(getLevel()) - p->area_level;
5487 uint32 XP = 0;
5488 if (diff < -5)
5490 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5492 else if (diff > 5)
5494 int32 exploration_percent = (100-((diff-5)*5));
5495 if (exploration_percent > 100)
5496 exploration_percent = 100;
5497 else if (exploration_percent < 0)
5498 exploration_percent = 0;
5500 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5502 else
5504 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5507 GiveXP( XP, NULL );
5508 SendExplorationExperience(area,XP);
5510 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5515 uint32 Player::TeamForRace(uint8 race)
5517 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5518 if(!rEntry)
5520 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5521 return ALLIANCE;
5524 switch(rEntry->TeamID)
5526 case 7: return ALLIANCE;
5527 case 1: return HORDE;
5530 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5531 return ALLIANCE;
5534 uint32 Player::getFactionForRace(uint8 race)
5536 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5537 if(!rEntry)
5539 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5540 return 0;
5543 return rEntry->FactionID;
5546 void Player::setFactionForRace(uint8 race)
5548 m_team = TeamForRace(race);
5549 setFaction( getFactionForRace(race) );
5552 void Player::UpdateReputation() const
5554 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5556 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5558 SendFactionState(&(itr->second));
5562 void Player::SendFactionState(FactionState const* faction) const
5564 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5566 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5567 data << (float) 0; // unk 2.4.0
5568 data << (uint8) 0; // wotlk 8634
5569 data << (uint32) 1; // count
5570 // for
5571 data << (uint32) faction->ReputationListID;
5572 data << (uint32) faction->Standing;
5573 // end for
5574 GetSession()->SendPacket(&data);
5578 void Player::SendInitialReputations()
5580 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5581 data << uint32 (0x00000080);
5583 RepListID a = 0;
5585 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5587 // fill in absent fields
5588 for (; a != itr->first; a++)
5590 data << uint8 (0x00);
5591 data << uint32 (0x00000000);
5594 // fill in encountered data
5595 data << uint8 (itr->second.Flags);
5596 data << uint32 (itr->second.Standing);
5598 ++a;
5601 // fill in absent fields
5602 for (; a != 128; a++)
5604 data << uint8 (0x00);
5605 data << uint32 (0x00000000);
5608 GetSession()->SendPacket(&data);
5611 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5613 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5614 if (itr != m_factions.end())
5615 return &itr->second;
5617 return NULL;
5620 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5622 // not allow declare war to own faction
5623 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5624 return;
5626 // already set
5627 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5628 return;
5630 if( atWar )
5631 faction->Flags |= FACTION_FLAG_AT_WAR;
5632 else
5633 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5635 faction->Changed = true;
5638 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5640 // always invisible or hidden faction can't be inactive
5641 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5642 return;
5644 // already set
5645 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5646 return;
5648 if(inactive)
5649 faction->Flags |= FACTION_FLAG_INACTIVE;
5650 else
5651 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5653 faction->Changed = true;
5656 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5658 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5660 if(!factionTemplateEntry)
5661 return;
5663 if(factionTemplateEntry->faction)
5664 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5667 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5669 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5670 if(!factionEntry)
5671 return;
5673 if(factionEntry->reputationListID < 0)
5674 return;
5676 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5677 if (itr == m_factions.end())
5678 return;
5680 SetFactionVisible(&itr->second);
5683 void Player::SetFactionVisible(FactionState* faction)
5685 // always invisible or hidden faction can't be make visible
5686 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5687 return;
5689 // already set
5690 if(faction->Flags & FACTION_FLAG_VISIBLE)
5691 return;
5693 faction->Flags |= FACTION_FLAG_VISIBLE;
5694 faction->Changed = true;
5696 if(!m_session->PlayerLoading())
5698 // make faction visible in reputation list at client
5699 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5700 data << faction->ReputationListID;
5701 GetSession()->SendPacket(&data);
5705 void Player::SetInitialFactions()
5707 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5709 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5711 if( factionEntry && (factionEntry->reputationListID >= 0))
5713 FactionState newFaction;
5714 newFaction.ID = factionEntry->ID;
5715 newFaction.ReputationListID = factionEntry->reputationListID;
5716 newFaction.Standing = 0;
5717 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5718 newFaction.Changed = true;
5720 m_factions[newFaction.ReputationListID] = newFaction;
5725 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5727 if (!factionEntry)
5728 return 0;
5730 uint32 raceMask = getRaceMask();
5731 uint32 classMask = getClassMask();
5732 for (int i=0; i < 4; i++)
5734 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5735 (factionEntry->BaseRepClassMask[i]==0 ||
5736 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5737 return factionEntry->ReputationFlags[i];
5739 return 0;
5742 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5744 if (!factionEntry)
5745 return 0;
5747 uint32 raceMask = getRaceMask();
5748 uint32 classMask = getClassMask();
5749 for (int i=0; i < 4; i++)
5751 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5752 (factionEntry->BaseRepClassMask[i]==0 ||
5753 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5754 return factionEntry->BaseRepValue[i];
5757 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5758 return 0;
5761 int32 Player::GetReputation(uint32 faction_id) const
5763 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5765 if (!factionEntry)
5767 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5768 return 0;
5771 return GetReputation(factionEntry);
5774 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5776 // Faction without recorded reputation. Just ignore.
5777 if(!factionEntry)
5778 return 0;
5780 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5781 if (itr != m_factions.end())
5782 return GetBaseReputation(factionEntry) + itr->second.Standing;
5784 return 0;
5787 ReputationRank Player::GetReputationRank(uint32 faction) const
5789 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5790 if(!factionEntry)
5791 return MIN_REPUTATION_RANK;
5793 return GetReputationRank(factionEntry);
5796 ReputationRank Player::ReputationToRank(int32 standing) const
5798 int32 Limit = Reputation_Cap + 1;
5799 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5801 Limit -= ReputationRank_Length[i];
5802 if (standing >= Limit )
5803 return ReputationRank(i);
5805 return MIN_REPUTATION_RANK;
5808 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5810 int32 Reputation = GetReputation(factionEntry);
5811 return ReputationToRank(Reputation);
5814 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5816 int32 Reputation = GetBaseReputation(factionEntry);
5817 return ReputationToRank(Reputation);
5820 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5822 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5824 if(!factionTemplateEntry)
5826 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5827 return false;
5830 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5832 // Faction without recorded reputation. Just ignore.
5833 if(!factionEntry)
5834 return false;
5836 return ModifyFactionReputation(factionEntry, DeltaReputation);
5839 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5841 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5842 if (flist)
5844 bool res = false;
5845 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5847 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5848 if(factionEntryCalc)
5849 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5851 return res;
5853 else
5854 return ModifyOneFactionReputation(factionEntry, standing);
5857 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5859 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5860 if (itr != m_factions.end())
5862 int32 BaseRep = GetBaseReputation(factionEntry);
5863 int32 new_rep = BaseRep + itr->second.Standing + standing;
5865 if (new_rep > Reputation_Cap)
5866 new_rep = Reputation_Cap;
5867 else
5868 if (new_rep < Reputation_Bottom)
5869 new_rep = Reputation_Bottom;
5871 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5872 SetFactionAtWar(&itr->second,true);
5874 itr->second.Standing = new_rep - BaseRep;
5875 itr->second.Changed = true;
5877 SetFactionVisible(&itr->second);
5879 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
5881 if(uint32 questid = GetQuestSlotQuestId(i))
5883 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5884 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5886 QuestStatusData& q_status = mQuestStatus[questid];
5887 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5889 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5890 if ( CanCompleteQuest( questid ) )
5891 CompleteQuest( questid );
5893 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5895 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5896 IncompleteQuest( questid );
5901 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5902 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5903 SendFactionState(&(itr->second));
5905 return true;
5907 return false;
5910 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5912 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5914 if(!factionTemplateEntry)
5916 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5917 return false;
5920 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5922 // Faction without recorded reputation. Just ignore.
5923 if(!factionEntry)
5924 return false;
5926 return SetFactionReputation(factionEntry, standing);
5929 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5931 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5932 if (flist)
5934 bool res = false;
5935 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5937 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5938 if(factionEntryCalc)
5939 res = SetOneFactionReputation(factionEntryCalc, standing);
5941 return res;
5943 else
5944 return SetOneFactionReputation(factionEntry, standing);
5947 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5949 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5950 if (itr != m_factions.end())
5952 if (standing > Reputation_Cap)
5953 standing = Reputation_Cap;
5954 else
5955 if (standing < Reputation_Bottom)
5956 standing = Reputation_Bottom;
5958 int32 BaseRep = GetBaseReputation(factionEntry);
5959 itr->second.Standing = standing - BaseRep;
5960 itr->second.Changed = true;
5962 SetFactionVisible(&itr->second);
5964 if(ReputationToRank(standing) <= REP_HOSTILE)
5965 SetFactionAtWar(&itr->second,true);
5967 SendFactionState(&(itr->second));
5968 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5969 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5970 return true;
5972 return false;
5975 //Calculate total reputation percent player gain with quest/creature level
5976 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5978 // for grey creature kill received 20%, in other case 100.
5979 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5981 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5983 percent += rep > 0 ? repMod : -repMod;
5985 if(percent <=0)
5986 return 0;
5988 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5991 //Calculates how many reputation points player gains in victim's enemy factions
5992 void Player::RewardReputation(Unit *pVictim, float rate)
5994 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5995 return;
5997 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5999 if(!Rep)
6000 return;
6002 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6004 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
6005 donerep1 = int32(donerep1*rate);
6006 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6007 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
6008 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6009 ModifyFactionReputation(factionEntry1, donerep1);
6011 // Wiki: Team factions value divided by 2
6012 if(Rep->is_teamaward1)
6014 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6015 if(team1_factionEntry)
6016 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
6020 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6022 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
6023 donerep2 = int32(donerep2*rate);
6024 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6025 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
6026 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6027 ModifyFactionReputation(factionEntry2, donerep2);
6029 // Wiki: Team factions value divided by 2
6030 if(Rep->is_teamaward2)
6032 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6033 if(team2_factionEntry)
6034 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
6039 //Calculate how many reputation points player gain with the quest
6040 void Player::RewardReputation(Quest const *pQuest)
6042 // quest reputation reward/loss
6043 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6045 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
6047 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
6048 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6049 if(factionEntry)
6050 ModifyFactionReputation(factionEntry, rep);
6054 // TODO: implement reputation spillover
6057 void Player::UpdateArenaFields(void)
6059 /* arena calcs go here */
6062 void Player::UpdateHonorFields()
6064 /// called when rewarding honor and at each save
6065 uint64 now = time(NULL);
6066 uint64 today = uint64(time(NULL) / DAY) * DAY;
6068 if(m_lastHonorUpdateTime < today)
6070 uint64 yesterday = today - DAY;
6072 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6074 // update yesterday's contribution
6075 if(m_lastHonorUpdateTime >= yesterday )
6077 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6079 // this is the first update today, reset today's contribution
6080 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6081 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6083 else
6085 // no honor/kills yesterday or today, reset
6086 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6087 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6091 m_lastHonorUpdateTime = now;
6094 ///Calculate the amount of honor gained based on the victim
6095 ///and the size of the group for which the honor is divided
6096 ///An exact honor value can also be given (overriding the calcs)
6097 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6099 // do not reward honor in arenas, but enable onkill spellproc
6100 if(InArena())
6102 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6103 return false;
6105 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6106 return false;
6108 return true;
6111 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6112 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6113 return false;
6115 uint64 victim_guid = 0;
6116 uint32 victim_rank = 0;
6118 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6119 UpdateHonorFields();
6121 if(honor <= 0)
6123 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6124 return false;
6126 victim_guid = uVictim->GetGUID();
6128 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6130 Player *pVictim = (Player *)uVictim;
6132 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6133 return false;
6135 float f = 1; //need for total kills (?? need more info)
6136 uint32 k_grey = 0;
6137 uint32 k_level = getLevel();
6138 uint32 v_level = pVictim->getLevel();
6141 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6142 // [0] Just name
6143 // [1..14] Alliance honor titles and player name
6144 // [15..28] Horde honor titles and player name
6145 // [29..38] Other title and player name
6146 // [39+] Nothing
6147 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6148 // Get Killer titles, CharTitlesEntry::bit_index
6149 // Ranks:
6150 // title[1..14] -> rank[5..18]
6151 // title[15..28] -> rank[5..18]
6152 // title[other] -> 0
6153 if (victim_title == 0)
6154 victim_guid = 0; // Don't show HK: <rank> message, only log.
6155 else if (victim_title < 15)
6156 victim_rank = victim_title + 4;
6157 else if (victim_title < 29)
6158 victim_rank = victim_title - 14 + 4;
6159 else
6160 victim_guid = 0; // Don't show HK: <rank> message, only log.
6163 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6165 if(v_level<=k_grey)
6166 return false;
6168 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6170 int32 v_rank =1; //need more info
6172 honor = ((f * diff_level * (190 + v_rank*10))/6);
6173 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6175 // count the number of playerkills in one day
6176 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6177 // and those in a lifetime
6178 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6180 else
6182 Creature *cVictim = (Creature *)uVictim;
6184 if (!cVictim->isRacialLeader())
6185 return false;
6187 honor = 100; // ??? need more info
6188 victim_rank = 19; // HK: Leader
6192 if (uVictim != NULL)
6194 honor *= sWorld.getRate(RATE_HONOR);
6196 if(groupsize > 1)
6197 honor /= groupsize;
6199 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6202 // honor - for show honor points in log
6203 // victim_guid - for show victim name in log
6204 // victim_rank [1..4] HK: <dishonored rank>
6205 // victim_rank [5..19] HK: <alliance\horde rank>
6206 // victim_rank [0,20+] HK: <>
6207 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6208 data << (uint32) honor;
6209 data << (uint64) victim_guid;
6210 data << (uint32) victim_rank;
6212 GetSession()->SendPacket(&data);
6214 // add honor points
6215 ModifyHonorPoints(int32(honor));
6217 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6218 return true;
6221 void Player::ModifyHonorPoints( int32 value )
6223 if(value < 0)
6225 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6226 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6227 else
6228 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6230 else
6231 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6234 void Player::ModifyArenaPoints( int32 value )
6236 if(value < 0)
6238 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6239 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6240 else
6241 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6243 else
6244 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6247 uint32 Player::GetGuildIdFromDB(uint64 guid)
6249 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6250 if(!result)
6251 return 0;
6253 uint32 id = result->Fetch()[0].GetUInt32();
6254 delete result;
6255 return id;
6258 uint32 Player::GetRankFromDB(uint64 guid)
6260 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6261 if( result )
6263 uint32 v = result->Fetch()[0].GetUInt32();
6264 delete result;
6265 return v;
6267 else
6268 return 0;
6271 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6273 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);
6274 if(!result)
6275 return 0;
6277 uint32 id = (*result)[0].GetUInt32();
6278 delete result;
6279 return id;
6282 uint32 Player::GetZoneIdFromDB(uint64 guid)
6284 uint32 guidLow = GUID_LOPART(guid);
6285 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6286 if (!result)
6287 return 0;
6288 Field* fields = result->Fetch();
6289 uint32 zone = fields[0].GetUInt32();
6290 delete result;
6292 if (!zone)
6294 // stored zone is zero, use generic and slow zone detection
6295 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6296 if( !result )
6297 return 0;
6298 fields = result->Fetch();
6299 uint32 map = fields[0].GetUInt32();
6300 float posx = fields[1].GetFloat();
6301 float posy = fields[2].GetFloat();
6302 float posz = fields[3].GetFloat();
6303 delete result;
6305 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6307 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6310 return zone;
6313 void Player::UpdateArea(uint32 newArea)
6315 // FFA_PVP flags are area and not zone id dependent
6316 // so apply them accordingly
6317 m_areaUpdateId = newArea;
6319 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6321 if(area && (area->flags & AREA_FLAG_ARENA))
6323 if(!isGameMaster())
6324 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6326 else
6328 // remove ffa flag only if not ffapvp realm
6329 // removal in sanctuaries and capitals is handled in zone update
6330 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6331 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6334 UpdateAreaDependentAuras(newArea);
6337 void Player::UpdateZone(uint32 newZone)
6339 m_zoneUpdateId = newZone;
6340 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6342 // zone changed, so area changed as well, update it
6343 UpdateArea(GetAreaId());
6345 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6346 if(!zone)
6347 return;
6349 if (sWorld.getConfig(CONFIG_WEATHER))
6351 Weather *wth = sWorld.FindWeather(zone->ID);
6352 if(wth)
6354 wth->SendWeatherUpdateToPlayer(this);
6356 else
6358 if(!sWorld.AddWeather(zone->ID))
6360 // send fine weather packet to remove old zone's weather
6361 Weather::SendFineWeatherUpdateToPlayer(this);
6366 pvpInfo.inHostileArea =
6367 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6368 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6369 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6370 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6372 if(pvpInfo.inHostileArea) // in hostile area
6374 if(!IsPvP() || pvpInfo.endTimer != 0)
6375 UpdatePvP(true, true);
6377 else // in friendly area
6379 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6380 pvpInfo.endTimer = time(0); // start toggle-off
6383 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6385 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6386 if(sWorld.IsFFAPvPRealm())
6387 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6389 else
6391 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6394 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6396 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6397 SetRestType(REST_TYPE_IN_CITY);
6398 InnEnter(time(0),GetMapId(),0,0,0);
6400 if(sWorld.IsFFAPvPRealm())
6401 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6403 else // anywhere else
6405 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6407 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6409 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6411 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6412 SetRestType(REST_TYPE_NO);
6414 if(sWorld.IsFFAPvPRealm())
6415 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6418 else // not in tavern (leave city then)
6420 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6421 SetRestType(REST_TYPE_NO);
6423 // Set player to FFA PVP when not in rested environment.
6424 if(sWorld.IsFFAPvPRealm())
6425 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6430 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6431 // if player resurrected at teleport this will be applied in resurrect code
6432 if(isAlive())
6433 DestroyZoneLimitedItem( true, newZone );
6435 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6436 AutoUnequipOffhandIfNeed();
6438 // recent client version not send leave/join channel packets for built-in local channels
6439 UpdateLocalChannels( newZone );
6441 // group update
6442 if(GetGroup())
6443 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6445 UpdateZoneDependentAuras(newZone);
6448 //If players are too far way of duel flag... then player loose the duel
6449 void Player::CheckDuelDistance(time_t currTime)
6451 if(!duel)
6452 return;
6454 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6455 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6456 if(!obj)
6457 return;
6459 if(duel->outOfBound == 0)
6461 if(!IsWithinDistInMap(obj, 50))
6463 duel->outOfBound = currTime;
6465 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6466 GetSession()->SendPacket(&data);
6469 else
6471 if(IsWithinDistInMap(obj, 40))
6473 duel->outOfBound = 0;
6475 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6476 GetSession()->SendPacket(&data);
6478 else if(currTime >= (duel->outOfBound+10))
6480 DuelComplete(DUEL_FLED);
6485 void Player::DuelComplete(DuelCompleteType type)
6487 // duel not requested
6488 if(!duel)
6489 return;
6491 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6492 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6493 GetSession()->SendPacket(&data);
6494 duel->opponent->GetSession()->SendPacket(&data);
6496 if(type != DUEL_INTERUPTED)
6498 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6499 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6500 data << duel->opponent->GetName();
6501 data << GetName();
6502 SendMessageToSet(&data,true);
6505 // cool-down duel spell
6506 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6508 data<<GetGUID();
6509 data<<uint8(0x0);
6511 data<<(uint32)7266;
6512 data<<uint32(0x0);
6513 GetSession()->SendPacket(&data);
6514 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6515 data<<duel->opponent->GetGUID();
6516 data<<uint8(0x0);
6517 data<<(uint32)7266;
6518 data<<uint32(0x0);
6519 duel->opponent->GetSession()->SendPacket(&data);*/
6521 //Remove Duel Flag object
6522 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6523 if(obj)
6524 duel->initiator->RemoveGameObject(obj,true);
6526 /* remove auras */
6527 std::vector<uint32> auras2remove;
6528 AuraMap const& vAuras = duel->opponent->GetAuras();
6529 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6531 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6532 auras2remove.push_back(i->second->GetId());
6535 for(size_t i=0; i<auras2remove.size(); i++)
6536 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6538 auras2remove.clear();
6539 AuraMap const& auras = GetAuras();
6540 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6542 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6543 auras2remove.push_back(i->second->GetId());
6545 for(size_t i=0; i<auras2remove.size(); i++)
6546 RemoveAurasDueToSpell(auras2remove[i]);
6548 // cleanup combo points
6549 if(GetComboTarget()==duel->opponent->GetGUID())
6550 ClearComboPoints();
6551 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6552 ClearComboPoints();
6554 if(duel->opponent->GetComboTarget()==GetGUID())
6555 duel->opponent->ClearComboPoints();
6556 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6557 duel->opponent->ClearComboPoints();
6559 //cleanups
6560 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6561 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6562 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6563 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6565 delete duel->opponent->duel;
6566 duel->opponent->duel = NULL;
6567 delete duel;
6568 duel = NULL;
6571 //---------------------------------------------------------//
6573 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6575 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6576 return;
6578 // not apply/remove mods for broken item
6579 if(item->IsBroken())
6580 return;
6582 ItemPrototype const *proto = item->GetProto();
6584 if(!proto)
6585 return;
6587 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6589 uint32 attacktype = Player::GetAttackBySlot(slot);
6590 if(attacktype < MAX_ATTACK)
6591 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6593 _ApplyItemBonuses(proto,slot,apply);
6595 if( slot==EQUIPMENT_SLOT_RANGED )
6596 _ApplyAmmoBonuses();
6598 ApplyItemEquipSpell(item,apply);
6599 ApplyEnchantment(item, apply);
6601 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6602 CorrectMetaGemEnchants(slot, apply);
6604 sLog.outDebug("_ApplyItemMods complete.");
6607 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6609 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6610 return;
6612 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6614 uint32 statType = 0;
6615 int32 val = 0;
6617 if(proto->ScalingStatDistribution)
6619 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6621 statType = ssd->StatMod[i];
6623 if(uint32 modifier = ssd->Modifier[i])
6625 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6626 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6628 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6629 val = (multiplier * modifier) / 10000;
6634 else
6636 statType = proto->ItemStat[i].ItemStatType;
6637 val = proto->ItemStat[i].ItemStatValue;
6640 if(val == 0)
6641 continue;
6643 switch (statType)
6645 case ITEM_MOD_MANA:
6646 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6647 break;
6648 case ITEM_MOD_HEALTH: // modify HP
6649 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6650 break;
6651 case ITEM_MOD_AGILITY: // modify agility
6652 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6653 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6654 break;
6655 case ITEM_MOD_STRENGTH: //modify strength
6656 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6657 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6658 break;
6659 case ITEM_MOD_INTELLECT: //modify intellect
6660 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6661 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6662 break;
6663 case ITEM_MOD_SPIRIT: //modify spirit
6664 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6665 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6666 break;
6667 case ITEM_MOD_STAMINA: //modify stamina
6668 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6669 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6670 break;
6671 case ITEM_MOD_DEFENSE_SKILL_RATING:
6672 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6673 break;
6674 case ITEM_MOD_DODGE_RATING:
6675 ApplyRatingMod(CR_DODGE, int32(val), apply);
6676 break;
6677 case ITEM_MOD_PARRY_RATING:
6678 ApplyRatingMod(CR_PARRY, int32(val), apply);
6679 break;
6680 case ITEM_MOD_BLOCK_RATING:
6681 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6682 break;
6683 case ITEM_MOD_HIT_MELEE_RATING:
6684 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6685 break;
6686 case ITEM_MOD_HIT_RANGED_RATING:
6687 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6688 break;
6689 case ITEM_MOD_HIT_SPELL_RATING:
6690 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6691 break;
6692 case ITEM_MOD_CRIT_MELEE_RATING:
6693 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6694 break;
6695 case ITEM_MOD_CRIT_RANGED_RATING:
6696 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6697 break;
6698 case ITEM_MOD_CRIT_SPELL_RATING:
6699 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6700 break;
6701 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6702 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6703 break;
6704 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6705 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6706 break;
6707 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6708 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6709 break;
6710 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6711 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6712 break;
6713 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6714 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6715 break;
6716 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6717 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6718 break;
6719 case ITEM_MOD_HASTE_MELEE_RATING:
6720 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6721 break;
6722 case ITEM_MOD_HASTE_RANGED_RATING:
6723 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6724 break;
6725 case ITEM_MOD_HASTE_SPELL_RATING:
6726 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6727 break;
6728 case ITEM_MOD_HIT_RATING:
6729 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6730 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6731 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6732 break;
6733 case ITEM_MOD_CRIT_RATING:
6734 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6735 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6736 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6737 break;
6738 case ITEM_MOD_HIT_TAKEN_RATING:
6739 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6740 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6741 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6742 break;
6743 case ITEM_MOD_CRIT_TAKEN_RATING:
6744 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6745 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6746 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6747 break;
6748 case ITEM_MOD_RESILIENCE_RATING:
6749 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6750 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6751 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6752 break;
6753 case ITEM_MOD_HASTE_RATING:
6754 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6755 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6756 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6757 break;
6758 case ITEM_MOD_EXPERTISE_RATING:
6759 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6760 break;
6761 case ITEM_MOD_ATTACK_POWER:
6762 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6763 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6764 break;
6765 case ITEM_MOD_RANGED_ATTACK_POWER:
6766 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6767 break;
6768 case ITEM_MOD_FERAL_ATTACK_POWER:
6769 ApplyFeralAPBonus(int32(val), apply);
6770 break;
6771 case ITEM_MOD_SPELL_HEALING_DONE:
6772 ApplySpellHealingBonus(int32(val), apply);
6773 break;
6774 case ITEM_MOD_SPELL_DAMAGE_DONE:
6775 ApplySpellDamageBonus(int32(val), apply);
6776 break;
6777 case ITEM_MOD_MANA_REGENERATION:
6778 ApplyManaRegenBonus(int32(val), apply);
6779 break;
6780 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6781 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6782 break;
6783 case ITEM_MOD_SPELL_POWER:
6784 ApplySpellHealingBonus(int32(val), apply);
6785 ApplySpellDamageBonus(int32(val), apply);
6786 break;
6790 if (proto->Armor)
6791 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6793 if (proto->Block)
6794 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6796 if (proto->HolyRes)
6797 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6799 if (proto->FireRes)
6800 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6802 if (proto->NatureRes)
6803 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6805 if (proto->FrostRes)
6806 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6808 if (proto->ShadowRes)
6809 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6811 if (proto->ArcaneRes)
6812 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6814 WeaponAttackType attType = BASE_ATTACK;
6815 float damage = 0.0f;
6817 if( slot == EQUIPMENT_SLOT_RANGED && (
6818 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6819 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6821 attType = RANGED_ATTACK;
6823 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6825 attType = OFF_ATTACK;
6828 if (proto->Damage[0].DamageMin > 0 )
6830 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6831 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6832 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6835 if (proto->Damage[0].DamageMax > 0 )
6837 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6838 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6841 // Druids get feral AP bonus from weapon dps
6842 if(getClass() == CLASS_DRUID)
6844 int32 feral_bonus = proto->getFeralBonus();
6845 if (feral_bonus > 0)
6846 ApplyFeralAPBonus(feral_bonus, apply);
6849 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6850 return;
6852 if (proto->Delay)
6854 if(slot == EQUIPMENT_SLOT_RANGED)
6855 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6856 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6857 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6858 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6859 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6862 if(CanModifyStats() && (damage || proto->Delay))
6863 UpdateDamagePhysical(attType);
6866 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6868 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6869 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6870 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6872 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6873 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6874 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6876 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6877 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6878 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6881 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6883 // generic not weapon specific case processes in aura code
6884 if(aura->GetSpellProto()->EquippedItemClass == -1)
6885 return;
6887 BaseModGroup mod = BASEMOD_END;
6888 switch(attackType)
6890 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6891 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6892 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6893 default: return;
6896 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6898 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6902 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6904 // ignore spell mods for not wands
6905 Modifier const* modifier = aura->GetModifier();
6906 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6907 return;
6909 // generic not weapon specific case processes in aura code
6910 if(aura->GetSpellProto()->EquippedItemClass == -1)
6911 return;
6913 UnitMods unitMod = UNIT_MOD_END;
6914 switch(attackType)
6916 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6917 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6918 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6919 default: return;
6922 UnitModifierType unitModType = TOTAL_VALUE;
6923 switch(modifier->m_auraname)
6925 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6926 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6927 default: return;
6930 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6932 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6936 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6938 if(!item)
6939 return;
6941 ItemPrototype const *proto = item->GetProto();
6942 if(!proto)
6943 return;
6945 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6947 _Spell const& spellData = proto->Spells[i];
6949 // no spell
6950 if(!spellData.SpellId )
6951 continue;
6953 // wrong triggering type
6954 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6955 continue;
6957 // check if it is valid spell
6958 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6959 if(!spellproto)
6960 continue;
6962 ApplyEquipSpell(spellproto,item,apply,form_change);
6966 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6968 if(apply)
6970 // Cannot be used in this stance/form
6971 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6972 return;
6974 if(form_change) // check aura active state from other form
6976 bool found = false;
6977 for (int k=0; k < 3; ++k)
6979 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6980 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6982 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6984 found = true;
6985 break;
6988 if(found)
6989 break;
6992 if(found) // and skip re-cast already active aura at form change
6993 return;
6996 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6998 CastSpell(this,spellInfo,true,item);
7000 else
7002 if(form_change) // check aura compatibility
7004 // Cannot be used in this stance/form
7005 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
7006 return; // and remove only not compatible at form change
7009 if(item)
7010 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7011 else
7012 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7016 void Player::UpdateEquipSpellsAtFormChange()
7018 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7020 if(m_items[i] && !m_items[i]->IsBroken())
7022 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7023 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7027 // item set bonuses not dependent from item broken state
7028 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7030 ItemSetEffect* eff = ItemSetEff[setindex];
7031 if(!eff)
7032 continue;
7034 for(uint32 y=0;y<8; ++y)
7036 SpellEntry const* spellInfo = eff->spells[y];
7037 if(!spellInfo)
7038 continue;
7040 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7041 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7046 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
7048 if(!item || item->IsBroken())
7049 return;
7051 ItemPrototype const *proto = item->GetProto();
7052 if(!proto)
7053 return;
7055 if (!Target || Target == this )
7056 return;
7058 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7060 _Spell const& spellData = proto->Spells[i];
7062 // no spell
7063 if(!spellData.SpellId )
7064 continue;
7066 // wrong triggering type
7067 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7068 continue;
7070 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7071 if(!spellInfo)
7073 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7074 continue;
7077 // not allow proc extra attack spell at extra attack
7078 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7079 return;
7081 float chance = spellInfo->procChance;
7083 if(spellData.SpellPPMRate)
7085 uint32 WeaponSpeed = GetAttackTime(attType);
7086 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7088 else if(chance > 100.0f)
7090 chance = GetWeaponProcChance();
7093 if (roll_chance_f(chance))
7094 CastSpell(Target, spellInfo->Id, true, item);
7097 // item combat enchantments
7098 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7100 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7101 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7102 if(!pEnchant) continue;
7103 for (int s=0;s<3;s++)
7105 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7106 continue;
7108 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7109 if (!spellInfo)
7111 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7112 continue;
7115 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7116 if (roll_chance_f(chance))
7118 if(IsPositiveSpell(pEnchant->spellid[s]))
7119 CastSpell(this, pEnchant->spellid[s], true, item);
7120 else
7121 CastSpell(Target, pEnchant->spellid[s], true, item);
7127 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7129 ItemPrototype const* proto = item->GetProto();
7130 // special learning case
7131 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7133 uint32 learn_spell_id = proto->Spells[0].SpellId;
7134 uint32 learning_spell_id = proto->Spells[1].SpellId;
7136 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7137 if(!spellInfo)
7139 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7140 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7141 return;
7144 Spell *spell = new Spell(this, spellInfo, false);
7145 spell->m_CastItem = item;
7146 spell->m_cast_count = cast_count; //set count of casts
7147 spell->m_currentBasePoints[0] = learning_spell_id;
7148 spell->prepare(&targets);
7149 return;
7152 // use triggered flag only for items with many spell casts and for not first cast
7153 int count = 0;
7155 // item spells casted at use
7156 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7158 _Spell const& spellData = proto->Spells[i];
7160 // no spell
7161 if(!spellData.SpellId)
7162 continue;
7164 // wrong triggering type
7165 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7166 continue;
7168 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7169 if(!spellInfo)
7171 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7172 continue;
7175 Spell *spell = new Spell(this, spellInfo, (count > 0));
7176 spell->m_CastItem = item;
7177 spell->m_cast_count = cast_count; // set count of casts
7178 spell->m_glyphIndex = glyphIndex; // glyph index
7179 spell->prepare(&targets);
7181 ++count;
7184 // Item enchantments spells casted at use
7185 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7187 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7188 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7189 if(!pEnchant) continue;
7190 for (int s=0;s<3;s++)
7192 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7193 continue;
7195 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7196 if (!spellInfo)
7198 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7199 continue;
7202 Spell *spell = new Spell(this, spellInfo, (count > 0));
7203 spell->m_CastItem = item;
7204 spell->m_cast_count = cast_count; // set count of casts
7205 spell->m_glyphIndex = glyphIndex; // glyph index
7206 spell->prepare(&targets);
7208 ++count;
7213 void Player::_RemoveAllItemMods()
7215 sLog.outDebug("_RemoveAllItemMods start.");
7217 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7219 if(m_items[i])
7221 ItemPrototype const *proto = m_items[i]->GetProto();
7222 if(!proto)
7223 continue;
7225 // item set bonuses not dependent from item broken state
7226 if(proto->ItemSet)
7227 RemoveItemsSetItem(this,proto);
7229 if(m_items[i]->IsBroken())
7230 continue;
7232 ApplyItemEquipSpell(m_items[i],false);
7233 ApplyEnchantment(m_items[i], false);
7237 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7239 if(m_items[i])
7241 if(m_items[i]->IsBroken())
7242 continue;
7243 ItemPrototype const *proto = m_items[i]->GetProto();
7244 if(!proto)
7245 continue;
7247 uint32 attacktype = Player::GetAttackBySlot(i);
7248 if(attacktype < MAX_ATTACK)
7249 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7251 _ApplyItemBonuses(proto,i, false);
7253 if( i == EQUIPMENT_SLOT_RANGED )
7254 _ApplyAmmoBonuses();
7258 sLog.outDebug("_RemoveAllItemMods complete.");
7261 void Player::_ApplyAllItemMods()
7263 sLog.outDebug("_ApplyAllItemMods start.");
7265 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7267 if(m_items[i])
7269 if(m_items[i]->IsBroken())
7270 continue;
7272 ItemPrototype const *proto = m_items[i]->GetProto();
7273 if(!proto)
7274 continue;
7276 uint32 attacktype = Player::GetAttackBySlot(i);
7277 if(attacktype < MAX_ATTACK)
7278 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7280 _ApplyItemBonuses(proto,i, true);
7282 if( i == EQUIPMENT_SLOT_RANGED )
7283 _ApplyAmmoBonuses();
7287 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7289 if(m_items[i])
7291 ItemPrototype const *proto = m_items[i]->GetProto();
7292 if(!proto)
7293 continue;
7295 // item set bonuses not dependent from item broken state
7296 if(proto->ItemSet)
7297 AddItemsSetItem(this,m_items[i]);
7299 if(m_items[i]->IsBroken())
7300 continue;
7302 ApplyItemEquipSpell(m_items[i],true);
7303 ApplyEnchantment(m_items[i], true);
7307 sLog.outDebug("_ApplyAllItemMods complete.");
7310 void Player::_ApplyAmmoBonuses()
7312 // check ammo
7313 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7314 if(!ammo_id)
7315 return;
7317 float currentAmmoDPS;
7319 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7320 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7321 currentAmmoDPS = 0.0f;
7322 else
7323 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7325 if(currentAmmoDPS == GetAmmoDPS())
7326 return;
7328 m_ammoDPS = currentAmmoDPS;
7330 if(CanModifyStats())
7331 UpdateDamagePhysical(RANGED_ATTACK);
7334 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7336 if(!ammo_proto)
7337 return false;
7339 // check ranged weapon
7340 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7341 if(!weapon || weapon->IsBroken() )
7342 return false;
7344 ItemPrototype const* weapon_proto = weapon->GetProto();
7345 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7346 return false;
7348 // check ammo ws. weapon compatibility
7349 switch(weapon_proto->SubClass)
7351 case ITEM_SUBCLASS_WEAPON_BOW:
7352 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7353 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7354 return false;
7355 break;
7356 case ITEM_SUBCLASS_WEAPON_GUN:
7357 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7358 return false;
7359 break;
7360 default:
7361 return false;
7364 return true;
7367 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7368 Called by remove insignia spell effect */
7369 void Player::RemovedInsignia(Player* looterPlr)
7371 if (!GetBattleGroundId())
7372 return;
7374 // If not released spirit, do it !
7375 if(m_deathTimer > 0)
7377 m_deathTimer = 0;
7378 BuildPlayerRepop();
7379 RepopAtGraveyard();
7382 Corpse *corpse = GetCorpse();
7383 if (!corpse)
7384 return;
7386 // We have to convert player corpse to bones, not to be able to resurrect there
7387 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7388 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7389 if (!bones)
7390 return;
7392 // Now we must make bones lootable, and send player loot
7393 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7395 // We store the level of our player in the gold field
7396 // We retrieve this information at Player::SendLoot()
7397 bones->loot.gold = getLevel();
7398 bones->lootRecipient = looterPlr;
7399 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7402 /*Loot type MUST be
7403 1-corpse, go
7404 2-skinning
7405 3-Fishing
7408 void Player::SendLootRelease( uint64 guid )
7410 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7411 data << uint64(guid) << uint8(1);
7412 SendDirectMessage( &data );
7415 void Player::SendLoot(uint64 guid, LootType loot_type)
7417 Loot *loot = 0;
7418 PermissionTypes permission = ALL_PERMISSION;
7420 sLog.outDebug("Player::SendLoot");
7421 if (IS_GAMEOBJECT_GUID(guid))
7423 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7424 GameObject *go =
7425 ObjectAccessor::GetGameObject(*this, guid);
7427 // not check distance for GO in case owned GO (fishing bobber case, for example)
7428 // And permit out of range GO with no owner in case fishing hole
7429 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7431 SendLootRelease(guid);
7432 return;
7435 loot = &go->loot;
7437 if(go->getLootState() == GO_READY)
7439 uint32 lootid = go->GetLootId();
7441 if(lootid)
7443 sLog.outDebug(" if(lootid)");
7444 loot->clear();
7445 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7448 if(loot_type == LOOT_FISHING)
7449 go->getFishLoot(loot,this);
7451 go->SetLootState(GO_ACTIVATED);
7454 else if (IS_ITEM_GUID(guid))
7456 Item *item = GetItemByGuid( guid );
7458 if (!item)
7460 SendLootRelease(guid);
7461 return;
7464 if(loot_type == LOOT_DISENCHANTING)
7466 loot = &item->loot;
7468 if(!item->m_lootGenerated)
7470 item->m_lootGenerated = true;
7471 loot->clear();
7472 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7475 else if(loot_type == LOOT_PROSPECTING)
7477 loot = &item->loot;
7479 if(!item->m_lootGenerated)
7481 item->m_lootGenerated = true;
7482 loot->clear();
7483 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7486 else if(loot_type == LOOT_MILLING)
7488 loot = &item->loot;
7490 if(!item->m_lootGenerated)
7492 item->m_lootGenerated = true;
7493 loot->clear();
7494 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7497 else
7499 loot = &item->loot;
7501 if(!item->m_lootGenerated)
7503 item->m_lootGenerated = true;
7504 loot->clear();
7505 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7507 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7511 else if (IS_CORPSE_GUID(guid)) // remove insignia
7513 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7515 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7517 SendLootRelease(guid);
7518 return;
7521 loot = &bones->loot;
7523 if (!bones->lootForBody)
7525 bones->lootForBody = true;
7526 uint32 pLevel = bones->loot.gold;
7527 bones->loot.clear();
7528 // It may need a better formula
7529 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7530 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7533 if (bones->lootRecipient != this)
7534 permission = NONE_PERMISSION;
7536 else
7538 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7540 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7541 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7543 SendLootRelease(guid);
7544 return;
7547 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7549 SendLootRelease(guid);
7550 return;
7553 loot = &creature->loot;
7555 if(loot_type == LOOT_PICKPOCKETING)
7557 if ( !creature->lootForPickPocketed )
7559 creature->lootForPickPocketed = true;
7560 loot->clear();
7562 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7563 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7565 // Generate extra money for pick pocket loot
7566 const uint32 a = urand(0, creature->getLevel()/2);
7567 const uint32 b = urand(0, getLevel()/2);
7568 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7571 else
7573 // the player whose group may loot the corpse
7574 Player *recipient = creature->GetLootRecipient();
7575 if (!recipient)
7577 creature->SetLootRecipient(this);
7578 recipient = this;
7581 if (creature->lootForPickPocketed)
7583 creature->lootForPickPocketed = false;
7584 loot->clear();
7587 if(!creature->lootForBody)
7589 creature->lootForBody = true;
7590 loot->clear();
7592 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7593 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7595 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7597 if(Group* group = recipient->GetGroup())
7599 group->UpdateLooterGuid(creature,true);
7601 switch (group->GetLootMethod())
7603 case GROUP_LOOT:
7604 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7605 group->GroupLoot(recipient->GetGUID(), loot, creature);
7606 break;
7607 case NEED_BEFORE_GREED:
7608 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7609 break;
7610 case MASTER_LOOT:
7611 group->MasterLoot(recipient->GetGUID(), loot, creature);
7612 break;
7613 default:
7614 break;
7619 // possible only if creature->lootForBody && loot->empty() at spell cast check
7620 if (loot_type == LOOT_SKINNING)
7622 loot->clear();
7623 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7625 // set group rights only for loot_type != LOOT_SKINNING
7626 else
7628 if(Group* group = GetGroup())
7630 if( group == recipient->GetGroup() )
7632 if(group->GetLootMethod() == FREE_FOR_ALL)
7633 permission = ALL_PERMISSION;
7634 else if(group->GetLooterGuid() == GetGUID())
7636 if(group->GetLootMethod() == MASTER_LOOT)
7637 permission = MASTER_PERMISSION;
7638 else
7639 permission = ALL_PERMISSION;
7641 else
7642 permission = GROUP_PERMISSION;
7644 else
7645 permission = NONE_PERMISSION;
7647 else if(recipient == this)
7648 permission = ALL_PERMISSION;
7649 else
7650 permission = NONE_PERMISSION;
7655 SetLootGUID(guid);
7657 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7658 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7659 loot_type = LOOT_SKINNING;
7661 if(loot_type == LOOT_FISHINGHOLE)
7662 loot_type = LOOT_FISHING;
7664 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7666 data << uint64(guid);
7667 data << uint8(loot_type);
7668 data << LootView(*loot, this, permission);
7670 SendDirectMessage(&data);
7672 // add 'this' player as one of the players that are looting 'loot'
7673 if (permission != NONE_PERMISSION)
7674 loot->AddLooter(GetGUID());
7676 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7677 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7680 void Player::SendNotifyLootMoneyRemoved()
7682 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7683 GetSession()->SendPacket( &data );
7686 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7688 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7689 data << uint8(lootSlot);
7690 GetSession()->SendPacket( &data );
7693 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7695 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7696 data << Field;
7697 data << Value;
7698 GetSession()->SendPacket(&data);
7701 void Player::SendInitWorldStates()
7703 // data depends on zoneid/mapid...
7704 BattleGround* bg = GetBattleGround();
7705 uint16 NumberOfFields = 0;
7706 uint32 mapid = GetMapId();
7707 uint32 zoneid = GetZoneId();
7708 uint32 areaid = GetAreaId();
7709 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7710 // may be exist better way to do this...
7711 switch(zoneid)
7713 case 0:
7714 case 1:
7715 case 4:
7716 case 8:
7717 case 10:
7718 case 11:
7719 case 12:
7720 case 36:
7721 case 38:
7722 case 40:
7723 case 41:
7724 case 51:
7725 case 267:
7726 case 1519:
7727 case 1537:
7728 case 2257:
7729 case 2918:
7730 NumberOfFields = 8;
7731 break;
7732 case 139:
7733 NumberOfFields = 41;
7734 break;
7735 case 1377:
7736 NumberOfFields = 15;
7737 break;
7738 case 2597:
7739 NumberOfFields = 83;
7740 break;
7741 case 3277:
7742 NumberOfFields = 16;
7743 break;
7744 case 3358:
7745 case 3820:
7746 NumberOfFields = 40;
7747 break;
7748 case 3483:
7749 NumberOfFields = 27;
7750 break;
7751 case 3518:
7752 NumberOfFields = 39;
7753 break;
7754 case 3519:
7755 NumberOfFields = 38;
7756 break;
7757 case 3521:
7758 NumberOfFields = 37;
7759 break;
7760 case 3698:
7761 case 3702:
7762 case 3968:
7763 NumberOfFields = 11;
7764 break;
7765 case 3703:
7766 NumberOfFields = 11;
7767 break;
7768 default:
7769 NumberOfFields = 12;
7770 break;
7773 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7774 data << uint32(mapid); // mapid
7775 data << uint32(zoneid); // zone id
7776 data << uint32(areaid); // area id, new 2.1.0
7777 data << uint16(NumberOfFields); // count of uint64 blocks
7778 data << uint32(0x8d8) << uint32(0x0); // 1
7779 data << uint32(0x8d7) << uint32(0x0); // 2
7780 data << uint32(0x8d6) << uint32(0x0); // 3
7781 data << uint32(0x8d5) << uint32(0x0); // 4
7782 data << uint32(0x8d4) << uint32(0x0); // 5
7783 data << uint32(0x8d3) << uint32(0x0); // 6
7784 // 7 1 - Arena season in progress, 0 - end of season
7785 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7786 // 8 Arena season id
7787 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7788 if(mapid == 530) // Outland
7790 data << uint32(0x9bf) << uint32(0x0); // 7
7791 data << uint32(0x9bd) << uint32(0xF); // 8
7792 data << uint32(0x9bb) << uint32(0xF); // 9
7794 switch(zoneid)
7796 case 1:
7797 case 11:
7798 case 12:
7799 case 38:
7800 case 40:
7801 case 51:
7802 case 1519:
7803 case 1537:
7804 case 2257:
7805 break;
7806 case 2597: // AV
7807 data << uint32(0x7ae) << uint32(0x1); // 7
7808 data << uint32(0x532) << uint32(0x1); // 8
7809 data << uint32(0x531) << uint32(0x0); // 9
7810 data << uint32(0x52e) << uint32(0x0); // 10
7811 data << uint32(0x571) << uint32(0x0); // 11
7812 data << uint32(0x570) << uint32(0x0); // 12
7813 data << uint32(0x567) << uint32(0x1); // 13
7814 data << uint32(0x566) << uint32(0x1); // 14
7815 data << uint32(0x550) << uint32(0x1); // 15
7816 data << uint32(0x544) << uint32(0x0); // 16
7817 data << uint32(0x536) << uint32(0x0); // 17
7818 data << uint32(0x535) << uint32(0x1); // 18
7819 data << uint32(0x518) << uint32(0x0); // 19
7820 data << uint32(0x517) << uint32(0x0); // 20
7821 data << uint32(0x574) << uint32(0x0); // 21
7822 data << uint32(0x573) << uint32(0x0); // 22
7823 data << uint32(0x572) << uint32(0x0); // 23
7824 data << uint32(0x56f) << uint32(0x0); // 24
7825 data << uint32(0x56e) << uint32(0x0); // 25
7826 data << uint32(0x56d) << uint32(0x0); // 26
7827 data << uint32(0x56c) << uint32(0x0); // 27
7828 data << uint32(0x56b) << uint32(0x0); // 28
7829 data << uint32(0x56a) << uint32(0x1); // 29
7830 data << uint32(0x569) << uint32(0x1); // 30
7831 data << uint32(0x568) << uint32(0x1); // 13
7832 data << uint32(0x565) << uint32(0x0); // 32
7833 data << uint32(0x564) << uint32(0x0); // 33
7834 data << uint32(0x563) << uint32(0x0); // 34
7835 data << uint32(0x562) << uint32(0x0); // 35
7836 data << uint32(0x561) << uint32(0x0); // 36
7837 data << uint32(0x560) << uint32(0x0); // 37
7838 data << uint32(0x55f) << uint32(0x0); // 38
7839 data << uint32(0x55e) << uint32(0x0); // 39
7840 data << uint32(0x55d) << uint32(0x0); // 40
7841 data << uint32(0x3c6) << uint32(0x4); // 41
7842 data << uint32(0x3c4) << uint32(0x6); // 42
7843 data << uint32(0x3c2) << uint32(0x4); // 43
7844 data << uint32(0x516) << uint32(0x1); // 44
7845 data << uint32(0x515) << uint32(0x0); // 45
7846 data << uint32(0x3b6) << uint32(0x6); // 46
7847 data << uint32(0x55c) << uint32(0x0); // 47
7848 data << uint32(0x55b) << uint32(0x0); // 48
7849 data << uint32(0x55a) << uint32(0x0); // 49
7850 data << uint32(0x559) << uint32(0x0); // 50
7851 data << uint32(0x558) << uint32(0x0); // 51
7852 data << uint32(0x557) << uint32(0x0); // 52
7853 data << uint32(0x556) << uint32(0x0); // 53
7854 data << uint32(0x555) << uint32(0x0); // 54
7855 data << uint32(0x554) << uint32(0x1); // 55
7856 data << uint32(0x553) << uint32(0x1); // 56
7857 data << uint32(0x552) << uint32(0x1); // 57
7858 data << uint32(0x551) << uint32(0x1); // 58
7859 data << uint32(0x54f) << uint32(0x0); // 59
7860 data << uint32(0x54e) << uint32(0x0); // 60
7861 data << uint32(0x54d) << uint32(0x1); // 61
7862 data << uint32(0x54c) << uint32(0x0); // 62
7863 data << uint32(0x54b) << uint32(0x0); // 63
7864 data << uint32(0x545) << uint32(0x0); // 64
7865 data << uint32(0x543) << uint32(0x1); // 65
7866 data << uint32(0x542) << uint32(0x0); // 66
7867 data << uint32(0x540) << uint32(0x0); // 67
7868 data << uint32(0x53f) << uint32(0x0); // 68
7869 data << uint32(0x53e) << uint32(0x0); // 69
7870 data << uint32(0x53d) << uint32(0x0); // 70
7871 data << uint32(0x53c) << uint32(0x0); // 71
7872 data << uint32(0x53b) << uint32(0x0); // 72
7873 data << uint32(0x53a) << uint32(0x1); // 73
7874 data << uint32(0x539) << uint32(0x0); // 74
7875 data << uint32(0x538) << uint32(0x0); // 75
7876 data << uint32(0x537) << uint32(0x0); // 76
7877 data << uint32(0x534) << uint32(0x0); // 77
7878 data << uint32(0x533) << uint32(0x0); // 78
7879 data << uint32(0x530) << uint32(0x0); // 79
7880 data << uint32(0x52f) << uint32(0x0); // 80
7881 data << uint32(0x52d) << uint32(0x1); // 81
7882 break;
7883 case 3277: // WS
7884 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7885 bg->FillInitialWorldStates(data);
7886 else
7888 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7889 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7890 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7891 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7892 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7893 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7894 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7895 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7897 break;
7898 case 3358: // AB
7899 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7900 bg->FillInitialWorldStates(data);
7901 else
7903 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7904 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7905 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7906 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7907 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7908 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7909 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7910 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7911 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7912 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7913 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7914 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7915 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7916 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7917 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7918 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7919 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7920 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7921 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7922 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7923 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7924 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7925 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7926 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7927 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7928 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7929 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7930 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7931 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7932 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7933 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7934 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7936 break;
7937 case 3820: // EY
7938 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7939 bg->FillInitialWorldStates(data);
7940 else
7942 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7943 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7944 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7945 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7946 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7947 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7948 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7949 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7950 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7951 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7952 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7953 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7954 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7955 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7956 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7957 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7958 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7959 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7960 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7961 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7962 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7963 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7964 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7965 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7966 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7967 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7968 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7969 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7970 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7971 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7972 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7973 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7974 // and some more ... unknown
7976 break;
7977 case 3483: // Hellfire Peninsula
7978 data << uint32(0x9ba) << uint32(0x1); // 10
7979 data << uint32(0x9b9) << uint32(0x1); // 11
7980 data << uint32(0x9b5) << uint32(0x0); // 12
7981 data << uint32(0x9b4) << uint32(0x1); // 13
7982 data << uint32(0x9b3) << uint32(0x0); // 14
7983 data << uint32(0x9b2) << uint32(0x0); // 15
7984 data << uint32(0x9b1) << uint32(0x1); // 16
7985 data << uint32(0x9b0) << uint32(0x0); // 17
7986 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7987 data << uint32(0x9ac) << uint32(0x0); // 19
7988 data << uint32(0x9a8) << uint32(0x0); // 20
7989 data << uint32(0x9a7) << uint32(0x0); // 21
7990 data << uint32(0x9a6) << uint32(0x1); // 22
7991 break;
7992 case 3519: // Terokkar Forest
7993 data << uint32(0xa41) << uint32(0x0); // 10
7994 data << uint32(0xa40) << uint32(0x14); // 11
7995 data << uint32(0xa3f) << uint32(0x0); // 12
7996 data << uint32(0xa3e) << uint32(0x0); // 13
7997 data << uint32(0xa3d) << uint32(0x5); // 14
7998 data << uint32(0xa3c) << uint32(0x0); // 15
7999 data << uint32(0xa87) << uint32(0x0); // 16
8000 data << uint32(0xa86) << uint32(0x0); // 17
8001 data << uint32(0xa85) << uint32(0x0); // 18
8002 data << uint32(0xa84) << uint32(0x0); // 19
8003 data << uint32(0xa83) << uint32(0x0); // 20
8004 data << uint32(0xa82) << uint32(0x0); // 21
8005 data << uint32(0xa81) << uint32(0x0); // 22
8006 data << uint32(0xa80) << uint32(0x0); // 23
8007 data << uint32(0xa7e) << uint32(0x0); // 24
8008 data << uint32(0xa7d) << uint32(0x0); // 25
8009 data << uint32(0xa7c) << uint32(0x0); // 26
8010 data << uint32(0xa7b) << uint32(0x0); // 27
8011 data << uint32(0xa7a) << uint32(0x0); // 28
8012 data << uint32(0xa79) << uint32(0x0); // 29
8013 data << uint32(0x9d0) << uint32(0x5); // 30
8014 data << uint32(0x9ce) << uint32(0x0); // 31
8015 data << uint32(0x9cd) << uint32(0x0); // 32
8016 data << uint32(0x9cc) << uint32(0x0); // 33
8017 data << uint32(0xa88) << uint32(0x0); // 34
8018 data << uint32(0xad0) << uint32(0x0); // 35
8019 data << uint32(0xacf) << uint32(0x1); // 36
8020 break;
8021 case 3521: // Zangarmarsh
8022 data << uint32(0x9e1) << uint32(0x0); // 10
8023 data << uint32(0x9e0) << uint32(0x0); // 11
8024 data << uint32(0x9df) << uint32(0x0); // 12
8025 data << uint32(0xa5d) << uint32(0x1); // 13
8026 data << uint32(0xa5c) << uint32(0x0); // 14
8027 data << uint32(0xa5b) << uint32(0x1); // 15
8028 data << uint32(0xa5a) << uint32(0x0); // 16
8029 data << uint32(0xa59) << uint32(0x1); // 17
8030 data << uint32(0xa58) << uint32(0x0); // 18
8031 data << uint32(0xa57) << uint32(0x0); // 19
8032 data << uint32(0xa56) << uint32(0x0); // 20
8033 data << uint32(0xa55) << uint32(0x1); // 21
8034 data << uint32(0xa54) << uint32(0x0); // 22
8035 data << uint32(0x9e7) << uint32(0x0); // 23
8036 data << uint32(0x9e6) << uint32(0x0); // 24
8037 data << uint32(0x9e5) << uint32(0x0); // 25
8038 data << uint32(0xa00) << uint32(0x0); // 26
8039 data << uint32(0x9ff) << uint32(0x1); // 27
8040 data << uint32(0x9fe) << uint32(0x0); // 28
8041 data << uint32(0x9fd) << uint32(0x0); // 29
8042 data << uint32(0x9fc) << uint32(0x1); // 30
8043 data << uint32(0x9fb) << uint32(0x0); // 31
8044 data << uint32(0xa62) << uint32(0x0); // 32
8045 data << uint32(0xa61) << uint32(0x1); // 33
8046 data << uint32(0xa60) << uint32(0x1); // 34
8047 data << uint32(0xa5f) << uint32(0x0); // 35
8048 break;
8049 case 3698: // Nagrand Arena
8050 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8051 bg->FillInitialWorldStates(data);
8052 else
8054 data << uint32(0xa0f) << uint32(0x0); // 7
8055 data << uint32(0xa10) << uint32(0x0); // 8
8056 data << uint32(0xa11) << uint32(0x0); // 9 show
8058 break;
8059 case 3702: // Blade's Edge Arena
8060 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8061 bg->FillInitialWorldStates(data);
8062 else
8064 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8065 data << uint32(0x9f1) << uint32(0x0); // 8 green
8066 data << uint32(0x9f3) << uint32(0x0); // 9 show
8068 break;
8069 case 3968: // Ruins of Lordaeron
8070 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8071 bg->FillInitialWorldStates(data);
8072 else
8074 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8075 data << uint32(0xbb9) << uint32(0x0); // 8 green
8076 data << uint32(0xbba) << uint32(0x0); // 9 show
8078 break;
8079 case 3703: // Shattrath City
8080 break;
8081 default:
8082 data << uint32(0x914) << uint32(0x0); // 7
8083 data << uint32(0x913) << uint32(0x0); // 8
8084 data << uint32(0x912) << uint32(0x0); // 9
8085 data << uint32(0x915) << uint32(0x0); // 10
8086 break;
8088 GetSession()->SendPacket(&data);
8091 uint32 Player::GetXPRestBonus(uint32 xp)
8093 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8095 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8096 rested_bonus = xp;
8098 SetRestBonus( GetRestBonus() - rested_bonus);
8100 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8101 return rested_bonus;
8104 void Player::SetBindPoint(uint64 guid)
8106 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8107 data << uint64(guid);
8108 GetSession()->SendPacket( &data );
8111 void Player::SendTalentWipeConfirm(uint64 guid)
8113 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8114 data << uint64(guid);
8115 data << uint32(resetTalentsCost());
8116 GetSession()->SendPacket( &data );
8119 void Player::SendPetSkillWipeConfirm()
8121 Pet* pet = GetPet();
8122 if(!pet)
8123 return;
8124 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8125 data << pet->GetGUID();
8126 data << uint32(pet->resetTalentsCost());
8127 GetSession()->SendPacket( &data );
8130 /*********************************************************/
8131 /*** STORAGE SYSTEM ***/
8132 /*********************************************************/
8134 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8136 assert(i < 3);
8137 if(i < 2 && item)
8139 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8140 return;
8141 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8142 if(charges == 0)
8143 return;
8144 if(charges > 1)
8145 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8146 else if(charges <= 1)
8148 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8149 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8154 void Player::SetSheath( uint32 sheathed )
8156 switch (sheathed)
8158 case SHEATH_STATE_UNARMED: // no prepared weapon
8159 SetVirtualItemSlot(0,NULL);
8160 SetVirtualItemSlot(1,NULL);
8161 SetVirtualItemSlot(2,NULL);
8162 break;
8163 case SHEATH_STATE_MELEE: // prepared melee weapon
8165 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
8166 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
8167 SetVirtualItemSlot(2,NULL);
8168 }; break;
8169 case SHEATH_STATE_RANGED: // prepared ranged weapon
8170 SetVirtualItemSlot(0,NULL);
8171 SetVirtualItemSlot(1,NULL);
8172 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
8173 break;
8174 default:
8175 SetVirtualItemSlot(0,NULL);
8176 SetVirtualItemSlot(1,NULL);
8177 SetVirtualItemSlot(2,NULL);
8178 break;
8180 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
8183 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8185 uint8 pClass = getClass();
8187 uint8 slots[4];
8188 slots[0] = NULL_SLOT;
8189 slots[1] = NULL_SLOT;
8190 slots[2] = NULL_SLOT;
8191 slots[3] = NULL_SLOT;
8192 switch( proto->InventoryType )
8194 case INVTYPE_HEAD:
8195 slots[0] = EQUIPMENT_SLOT_HEAD;
8196 break;
8197 case INVTYPE_NECK:
8198 slots[0] = EQUIPMENT_SLOT_NECK;
8199 break;
8200 case INVTYPE_SHOULDERS:
8201 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8202 break;
8203 case INVTYPE_BODY:
8204 slots[0] = EQUIPMENT_SLOT_BODY;
8205 break;
8206 case INVTYPE_CHEST:
8207 slots[0] = EQUIPMENT_SLOT_CHEST;
8208 break;
8209 case INVTYPE_ROBE:
8210 slots[0] = EQUIPMENT_SLOT_CHEST;
8211 break;
8212 case INVTYPE_WAIST:
8213 slots[0] = EQUIPMENT_SLOT_WAIST;
8214 break;
8215 case INVTYPE_LEGS:
8216 slots[0] = EQUIPMENT_SLOT_LEGS;
8217 break;
8218 case INVTYPE_FEET:
8219 slots[0] = EQUIPMENT_SLOT_FEET;
8220 break;
8221 case INVTYPE_WRISTS:
8222 slots[0] = EQUIPMENT_SLOT_WRISTS;
8223 break;
8224 case INVTYPE_HANDS:
8225 slots[0] = EQUIPMENT_SLOT_HANDS;
8226 break;
8227 case INVTYPE_FINGER:
8228 slots[0] = EQUIPMENT_SLOT_FINGER1;
8229 slots[1] = EQUIPMENT_SLOT_FINGER2;
8230 break;
8231 case INVTYPE_TRINKET:
8232 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8233 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8234 break;
8235 case INVTYPE_CLOAK:
8236 slots[0] = EQUIPMENT_SLOT_BACK;
8237 break;
8238 case INVTYPE_WEAPON:
8240 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8242 // suggest offhand slot only if know dual wielding
8243 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8244 if(CanDualWield())
8245 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8246 break;
8248 case INVTYPE_SHIELD:
8249 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8250 break;
8251 case INVTYPE_RANGED:
8252 slots[0] = EQUIPMENT_SLOT_RANGED;
8253 break;
8254 case INVTYPE_2HWEAPON:
8255 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8256 if (CanDualWield() && CanTitanGrip())
8257 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8258 break;
8259 case INVTYPE_TABARD:
8260 slots[0] = EQUIPMENT_SLOT_TABARD;
8261 break;
8262 case INVTYPE_WEAPONMAINHAND:
8263 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8264 break;
8265 case INVTYPE_WEAPONOFFHAND:
8266 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8267 break;
8268 case INVTYPE_HOLDABLE:
8269 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8270 break;
8271 case INVTYPE_THROWN:
8272 slots[0] = EQUIPMENT_SLOT_RANGED;
8273 break;
8274 case INVTYPE_RANGEDRIGHT:
8275 slots[0] = EQUIPMENT_SLOT_RANGED;
8276 break;
8277 case INVTYPE_BAG:
8278 slots[0] = INVENTORY_SLOT_BAG_1;
8279 slots[1] = INVENTORY_SLOT_BAG_2;
8280 slots[2] = INVENTORY_SLOT_BAG_3;
8281 slots[3] = INVENTORY_SLOT_BAG_4;
8282 break;
8283 case INVTYPE_RELIC:
8285 switch(proto->SubClass)
8287 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8288 if (pClass == CLASS_PALADIN)
8289 slots[0] = EQUIPMENT_SLOT_RANGED;
8290 break;
8291 case ITEM_SUBCLASS_ARMOR_IDOL:
8292 if (pClass == CLASS_DRUID)
8293 slots[0] = EQUIPMENT_SLOT_RANGED;
8294 break;
8295 case ITEM_SUBCLASS_ARMOR_TOTEM:
8296 if (pClass == CLASS_SHAMAN)
8297 slots[0] = EQUIPMENT_SLOT_RANGED;
8298 break;
8299 case ITEM_SUBCLASS_ARMOR_MISC:
8300 if (pClass == CLASS_WARLOCK)
8301 slots[0] = EQUIPMENT_SLOT_RANGED;
8302 break;
8303 case ITEM_SUBCLASS_ARMOR_SIGIL:
8304 if (pClass == CLASS_DEATH_KNIGHT)
8305 slots[0] = EQUIPMENT_SLOT_RANGED;
8306 break;
8308 break;
8310 default :
8311 return NULL_SLOT;
8314 if( slot != NULL_SLOT )
8316 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8318 for (int i = 0; i < 4; i++)
8320 if ( slots[i] == slot )
8321 return slot;
8325 else
8327 // search free slot at first
8328 for (int i = 0; i < 4; i++)
8330 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8332 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8333 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8334 return slots[i];
8338 // if not found free and can swap return first appropriate from used
8339 for (int i = 0; i < 4; i++)
8341 if ( slots[i] != NULL_SLOT && swap )
8342 return slots[i];
8346 // no free position
8347 return NULL_SLOT;
8350 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8352 Item *pItem;
8353 uint32 tempcount = 0;
8355 uint8 res = EQUIP_ERR_OK;
8357 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8359 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8360 if( pItem && pItem->GetEntry() == item )
8362 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8363 if(ires==EQUIP_ERR_OK)
8365 tempcount += pItem->GetCount();
8366 if( tempcount >= count )
8367 return EQUIP_ERR_OK;
8369 else
8370 res = ires;
8373 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8375 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8376 if( pItem && pItem->GetEntry() == item )
8378 tempcount += pItem->GetCount();
8379 if( tempcount >= count )
8380 return EQUIP_ERR_OK;
8383 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8385 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8386 if( pItem && pItem->GetEntry() == item )
8388 tempcount += pItem->GetCount();
8389 if( tempcount >= count )
8390 return EQUIP_ERR_OK;
8393 Bag *pBag;
8394 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8396 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8397 if( pBag )
8399 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8401 pItem = GetItemByPos( i, j );
8402 if( pItem && pItem->GetEntry() == item )
8404 tempcount += pItem->GetCount();
8405 if( tempcount >= count )
8406 return EQUIP_ERR_OK;
8412 // not found req. item count and have unequippable items
8413 return res;
8416 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8418 uint32 count = 0;
8419 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8421 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8422 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8423 count += pItem->GetCount();
8425 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8427 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8428 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8429 count += pItem->GetCount();
8431 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8433 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8434 if( pBag )
8435 count += pBag->GetItemCount(item,skipItem);
8438 if(skipItem && skipItem->GetProto()->GemProperties)
8440 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8442 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8443 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8444 count += pItem->GetGemCountWithID(item);
8448 if(inBankAlso)
8450 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8452 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8453 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8454 count += pItem->GetCount();
8456 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8458 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8459 if( pBag )
8460 count += pBag->GetItemCount(item,skipItem);
8463 if(skipItem && skipItem->GetProto()->GemProperties)
8465 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8467 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8468 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8469 count += pItem->GetGemCountWithID(item);
8474 return count;
8477 Item* Player::GetItemByGuid( uint64 guid ) const
8479 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8481 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8482 if( pItem && pItem->GetGUID() == guid )
8483 return pItem;
8485 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8487 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8488 if( pItem && pItem->GetGUID() == guid )
8489 return pItem;
8492 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8494 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8495 if( pBag )
8497 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8499 Item* pItem = pBag->GetItemByPos( j );
8500 if( pItem && pItem->GetGUID() == guid )
8501 return pItem;
8505 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8507 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8508 if( pBag )
8510 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8512 Item* pItem = pBag->GetItemByPos( j );
8513 if( pItem && pItem->GetGUID() == guid )
8514 return pItem;
8519 return NULL;
8522 Item* Player::GetItemByPos( uint16 pos ) const
8524 uint8 bag = pos >> 8;
8525 uint8 slot = pos & 255;
8526 return GetItemByPos( bag, slot );
8529 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8531 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8532 return m_items[slot];
8533 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8534 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8536 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8537 if ( pBag )
8538 return pBag->GetItemByPos(slot);
8540 return NULL;
8543 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8545 uint16 slot;
8546 switch (attackType)
8548 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8549 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8550 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8551 default: return NULL;
8554 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8555 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8556 return NULL;
8558 if(!useable)
8559 return item;
8561 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8562 return NULL;
8564 return item;
8567 Item* Player::GetShield(bool useable) const
8569 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8570 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8571 return NULL;
8573 if(!useable)
8574 return item;
8576 if( item->IsBroken())
8577 return NULL;
8579 return item;
8582 uint32 Player::GetAttackBySlot( uint8 slot )
8584 switch(slot)
8586 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8587 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8588 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8589 default: return MAX_ATTACK;
8593 bool Player::HasBankBagSlot( uint8 slot ) const
8595 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8596 if( slot < maxslot )
8597 return true;
8598 return false;
8601 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8603 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8604 return true;
8605 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8606 return true;
8607 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8608 return true;
8609 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8610 return true;
8611 return false;
8614 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8616 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8617 return true;
8618 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8619 return true;
8620 return false;
8623 bool Player::IsBankPos( uint8 bag, uint8 slot )
8625 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8626 return true;
8627 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8628 return true;
8629 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8630 return true;
8631 return false;
8634 bool Player::IsBagPos( uint16 pos )
8636 uint8 bag = pos >> 8;
8637 uint8 slot = pos & 255;
8638 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8639 return true;
8640 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8641 return true;
8642 return false;
8645 bool Player::IsValidPos( uint8 bag, uint8 slot )
8647 // post selected
8648 if(bag == NULL_BAG)
8649 return true;
8651 if (bag == INVENTORY_SLOT_BAG_0)
8653 // any post selected
8654 if (slot == NULL_SLOT)
8655 return true;
8657 // equipment
8658 if (slot < EQUIPMENT_SLOT_END)
8659 return true;
8661 // bag equip slots
8662 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8663 return true;
8665 // backpack slots
8666 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8667 return true;
8669 // keyring slots
8670 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8671 return true;
8673 // bank main slots
8674 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8675 return true;
8677 // bank bag slots
8678 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8679 return true;
8681 return false;
8684 // bag content slots
8685 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8687 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8688 if(!pBag)
8689 return false;
8691 // any post selected
8692 if (slot == NULL_SLOT)
8693 return true;
8695 return slot < pBag->GetBagSize();
8698 // bank bag content slots
8699 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8701 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8702 if(!pBag)
8703 return false;
8705 // any post selected
8706 if (slot == NULL_SLOT)
8707 return true;
8709 return slot < pBag->GetBagSize();
8712 // where this?
8713 return false;
8717 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8719 uint32 tempcount = 0;
8720 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8722 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8723 if( pItem && pItem->GetEntry() == item )
8725 tempcount += pItem->GetCount();
8726 if( tempcount >= count )
8727 return true;
8730 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8732 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8733 if( pItem && pItem->GetEntry() == item )
8735 tempcount += pItem->GetCount();
8736 if( tempcount >= count )
8737 return true;
8740 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8742 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8744 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8746 Item* pItem = GetItemByPos( i, j );
8747 if( pItem && pItem->GetEntry() == item )
8749 tempcount += pItem->GetCount();
8750 if( tempcount >= count )
8751 return true;
8757 if(inBankAlso)
8759 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8761 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8762 if( pItem && pItem->GetEntry() == item )
8764 tempcount += pItem->GetCount();
8765 if( tempcount >= count )
8766 return true;
8769 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8771 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8773 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8775 Item* pItem = GetItemByPos( i, j );
8776 if( pItem && pItem->GetEntry() == item )
8778 tempcount += pItem->GetCount();
8779 if( tempcount >= count )
8780 return true;
8787 return false;
8790 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8792 uint32 tempcount = 0;
8793 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8795 if(i==int(except_slot))
8796 continue;
8798 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8799 if( pItem && pItem->GetEntry() == item)
8801 tempcount += pItem->GetCount();
8802 if( tempcount >= count )
8803 return true;
8807 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8808 if (pProto && pProto->GemProperties)
8810 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8812 if(i==int(except_slot))
8813 continue;
8815 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8816 if( pItem && pItem->GetProto()->Socket[0].Color)
8818 tempcount += pItem->GetGemCountWithID(item);
8819 if( tempcount >= count )
8820 return true;
8825 return false;
8828 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8830 uint32 tempcount = 0;
8831 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8833 if(i==int(except_slot))
8834 continue;
8836 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8837 if (!pItem)
8838 continue;
8840 ItemPrototype const *pProto = pItem->GetProto();
8841 if (!pProto)
8842 continue;
8844 if (pProto->ItemLimitCategory == limitCategory)
8846 tempcount += pItem->GetCount();
8847 if( tempcount >= count )
8848 return true;
8851 if( pProto->Socket[0].Color)
8853 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8854 if( tempcount >= count )
8855 return true;
8859 return false;
8862 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8864 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8865 if( !pProto )
8867 if(no_space_count)
8868 *no_space_count = count;
8869 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8872 // no maximum
8873 if(pProto->MaxCount <= 0)
8874 return EQUIP_ERR_OK;
8876 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8878 if (curcount + count > uint32(pProto->MaxCount))
8880 if(no_space_count)
8881 *no_space_count = count +curcount - pProto->MaxCount;
8882 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8885 return EQUIP_ERR_OK;
8888 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8890 Item *pItem;
8891 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8893 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8894 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8895 return true;
8897 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8899 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8900 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8901 return true;
8903 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8905 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8907 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8909 pItem = GetItemByPos( i, j );
8910 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8911 return true;
8915 return false;
8918 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8920 Item* pItem2 = GetItemByPos( bag, slot );
8922 // ignore move item (this slot will be empty at move)
8923 if(pItem2==pSrcItem)
8924 pItem2 = NULL;
8926 uint32 need_space;
8928 // empty specific slot - check item fit to slot
8929 if( !pItem2 || swap )
8931 if( bag == INVENTORY_SLOT_BAG_0 )
8933 // keyring case
8934 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8935 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8937 // vanitypet case (not use, vanity pets stored as spells)
8938 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8939 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8941 // currencytoken case (disabled until proper implement)
8942 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8943 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8945 // guestbag case (disabled until proper implement)
8946 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8947 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8949 // prevent cheating
8950 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8951 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8953 else
8955 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8956 if( !pBag )
8957 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8959 ItemPrototype const* pBagProto = pBag->GetProto();
8960 if( !pBagProto )
8961 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8963 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8964 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8967 // non empty stack with space
8968 need_space = pProto->GetMaxStackSize();
8970 // non empty slot, check item type
8971 else
8973 // check item type
8974 if(pItem2->GetEntry() != pProto->ItemId)
8975 return EQUIP_ERR_ITEM_CANT_STACK;
8977 // check free space
8978 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8979 return EQUIP_ERR_ITEM_CANT_STACK;
8981 // free stack space or infinity
8982 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8985 if(need_space > count)
8986 need_space = count;
8988 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8989 if(!newPosition.isContainedIn(dest))
8991 dest.push_back(newPosition);
8992 count -= need_space;
8994 return EQUIP_ERR_OK;
8997 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
8999 // skip specific bag already processed in first called _CanStoreItem_InBag
9000 if(bag==skip_bag)
9001 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9003 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9004 if( !pBag )
9005 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9007 ItemPrototype const* pBagProto = pBag->GetProto();
9008 if( !pBagProto )
9009 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9011 // specialized bag mode or non-specilized
9012 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
9013 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9015 if( !ItemCanGoIntoBag(pProto,pBagProto) )
9016 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9018 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9020 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9021 if(j==skip_slot)
9022 continue;
9024 Item* pItem2 = GetItemByPos( bag, j );
9026 // ignore move item (this slot will be empty at move)
9027 if(pItem2==pSrcItem)
9028 pItem2 = NULL;
9030 // if merge skip empty, if !merge skip non-empty
9031 if((pItem2!=NULL)!=merge)
9032 continue;
9034 if( pItem2 )
9036 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9038 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9039 if(need_space > count)
9040 need_space = count;
9042 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9043 if(!newPosition.isContainedIn(dest))
9045 dest.push_back(newPosition);
9046 count -= need_space;
9048 if(count==0)
9049 return EQUIP_ERR_OK;
9053 else
9055 uint32 need_space = pProto->GetMaxStackSize();
9056 if(need_space > count)
9057 need_space = count;
9059 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9060 if(!newPosition.isContainedIn(dest))
9062 dest.push_back(newPosition);
9063 count -= need_space;
9065 if(count==0)
9066 return EQUIP_ERR_OK;
9070 return EQUIP_ERR_OK;
9073 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
9075 for(uint32 j = slot_begin; j < slot_end; j++)
9077 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9078 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9079 continue;
9081 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9083 // ignore move item (this slot will be empty at move)
9084 if(pItem2==pSrcItem)
9085 pItem2 = NULL;
9087 // if merge skip empty, if !merge skip non-empty
9088 if((pItem2!=NULL)!=merge)
9089 continue;
9091 if( pItem2 )
9093 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
9095 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9096 if(need_space > count)
9097 need_space = count;
9098 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9099 if(!newPosition.isContainedIn(dest))
9101 dest.push_back(newPosition);
9102 count -= need_space;
9104 if(count==0)
9105 return EQUIP_ERR_OK;
9109 else
9111 uint32 need_space = pProto->GetMaxStackSize();
9112 if(need_space > count)
9113 need_space = count;
9115 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9116 if(!newPosition.isContainedIn(dest))
9118 dest.push_back(newPosition);
9119 count -= need_space;
9121 if(count==0)
9122 return EQUIP_ERR_OK;
9126 return EQUIP_ERR_OK;
9129 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9131 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9133 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
9134 if( !pProto )
9136 if(no_space_count)
9137 *no_space_count = count;
9138 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9141 if(pItem && pItem->IsBindedNotWith(GetGUID()))
9143 if(no_space_count)
9144 *no_space_count = count;
9145 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9148 // check count of items (skip for auto move for same player from bank)
9149 uint32 no_similar_count = 0; // can't store this amount similar items
9150 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9151 if(res!=EQUIP_ERR_OK)
9153 if(count==no_similar_count)
9155 if(no_space_count)
9156 *no_space_count = no_similar_count;
9157 return res;
9159 count -= no_similar_count;
9162 // in specific slot
9163 if( bag != NULL_BAG && slot != NULL_SLOT )
9165 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9166 if(res!=EQUIP_ERR_OK)
9168 if(no_space_count)
9169 *no_space_count = count + no_similar_count;
9170 return res;
9173 if(count==0)
9175 if(no_similar_count==0)
9176 return EQUIP_ERR_OK;
9178 if(no_space_count)
9179 *no_space_count = count + no_similar_count;
9180 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9184 // not specific slot or have space for partly store only in specific slot
9186 // in specific bag
9187 if( bag != NULL_BAG )
9189 // search stack in bag for merge to
9190 if( pProto->Stackable != 1 )
9192 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9194 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9195 if(res!=EQUIP_ERR_OK)
9197 if(no_space_count)
9198 *no_space_count = count + no_similar_count;
9199 return res;
9202 if(count==0)
9204 if(no_similar_count==0)
9205 return EQUIP_ERR_OK;
9207 if(no_space_count)
9208 *no_space_count = count + no_similar_count;
9209 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9212 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9213 if(res!=EQUIP_ERR_OK)
9215 if(no_space_count)
9216 *no_space_count = count + no_similar_count;
9217 return res;
9220 if(count==0)
9222 if(no_similar_count==0)
9223 return EQUIP_ERR_OK;
9225 if(no_space_count)
9226 *no_space_count = count + no_similar_count;
9227 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9230 else // equipped bag
9232 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9233 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9234 if(res!=EQUIP_ERR_OK)
9235 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9237 if(res!=EQUIP_ERR_OK)
9239 if(no_space_count)
9240 *no_space_count = count + no_similar_count;
9241 return res;
9244 if(count==0)
9246 if(no_similar_count==0)
9247 return EQUIP_ERR_OK;
9249 if(no_space_count)
9250 *no_space_count = count + no_similar_count;
9251 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9256 // search free slot in bag for place to
9257 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9259 // search free slot - keyring case
9260 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9262 uint32 keyringSize = GetMaxKeyringSize();
9263 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9264 if(res!=EQUIP_ERR_OK)
9266 if(no_space_count)
9267 *no_space_count = count + no_similar_count;
9268 return res;
9271 if(count==0)
9273 if(no_similar_count==0)
9274 return EQUIP_ERR_OK;
9276 if(no_space_count)
9277 *no_space_count = count + no_similar_count;
9278 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9282 // Vanity pet case skipped as not used
9284 /* until proper implementation
9285 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9287 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9288 if(res!=EQUIP_ERR_OK)
9290 if(no_space_count)
9291 *no_space_count = count + no_similar_count;
9292 return res;
9295 if(count==0)
9297 if(no_similar_count==0)
9298 return EQUIP_ERR_OK;
9300 if(no_space_count)
9301 *no_space_count = count + no_similar_count;
9302 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9306 /* until proper implementation
9307 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9309 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,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;
9329 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9330 if(res!=EQUIP_ERR_OK)
9332 if(no_space_count)
9333 *no_space_count = count + no_similar_count;
9334 return res;
9337 if(count==0)
9339 if(no_similar_count==0)
9340 return EQUIP_ERR_OK;
9342 if(no_space_count)
9343 *no_space_count = count + no_similar_count;
9344 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9347 else // equipped bag
9349 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9350 if(res!=EQUIP_ERR_OK)
9351 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9353 if(res!=EQUIP_ERR_OK)
9355 if(no_space_count)
9356 *no_space_count = count + no_similar_count;
9357 return res;
9360 if(count==0)
9362 if(no_similar_count==0)
9363 return EQUIP_ERR_OK;
9365 if(no_space_count)
9366 *no_space_count = count + no_similar_count;
9367 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9372 // not specific bag or have space for partly store only in specific bag
9374 // search stack for merge to
9375 if( pProto->Stackable != 1 )
9377 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9378 if(res!=EQUIP_ERR_OK)
9380 if(no_space_count)
9381 *no_space_count = count + no_similar_count;
9382 return res;
9385 if(count==0)
9387 if(no_similar_count==0)
9388 return EQUIP_ERR_OK;
9390 if(no_space_count)
9391 *no_space_count = count + no_similar_count;
9392 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9395 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,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;
9413 if( pProto->BagFamily )
9415 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9417 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9418 if(res!=EQUIP_ERR_OK)
9419 continue;
9421 if(count==0)
9423 if(no_similar_count==0)
9424 return EQUIP_ERR_OK;
9426 if(no_space_count)
9427 *no_space_count = count + no_similar_count;
9428 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9433 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9435 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9436 if(res!=EQUIP_ERR_OK)
9437 continue;
9439 if(count==0)
9441 if(no_similar_count==0)
9442 return EQUIP_ERR_OK;
9444 if(no_space_count)
9445 *no_space_count = count + no_similar_count;
9446 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9451 // search free slot - special bag case
9452 if( pProto->BagFamily )
9454 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9456 uint32 keyringSize = GetMaxKeyringSize();
9457 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9458 if(res!=EQUIP_ERR_OK)
9460 if(no_space_count)
9461 *no_space_count = count + no_similar_count;
9462 return res;
9465 if(count==0)
9467 if(no_similar_count==0)
9468 return EQUIP_ERR_OK;
9470 if(no_space_count)
9471 *no_space_count = count + no_similar_count;
9472 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9476 // Vanity pet case skipped as not used
9478 /* until proper implementation
9479 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9481 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9482 if(res!=EQUIP_ERR_OK)
9484 if(no_space_count)
9485 *no_space_count = count + no_similar_count;
9486 return res;
9489 if(count==0)
9491 if(no_similar_count==0)
9492 return EQUIP_ERR_OK;
9494 if(no_space_count)
9495 *no_space_count = count + no_similar_count;
9496 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9500 /* until proper implementation
9501 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9503 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9504 if(res!=EQUIP_ERR_OK)
9506 if(no_space_count)
9507 *no_space_count = count + no_similar_count;
9508 return res;
9511 if(count==0)
9513 if(no_similar_count==0)
9514 return EQUIP_ERR_OK;
9516 if(no_space_count)
9517 *no_space_count = count + no_similar_count;
9518 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9523 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9525 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9526 if(res!=EQUIP_ERR_OK)
9527 continue;
9529 if(count==0)
9531 if(no_similar_count==0)
9532 return EQUIP_ERR_OK;
9534 if(no_space_count)
9535 *no_space_count = count + no_similar_count;
9536 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9541 // search free slot
9542 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9543 if(res!=EQUIP_ERR_OK)
9545 if(no_space_count)
9546 *no_space_count = count + no_similar_count;
9547 return res;
9550 if(count==0)
9552 if(no_similar_count==0)
9553 return EQUIP_ERR_OK;
9555 if(no_space_count)
9556 *no_space_count = count + no_similar_count;
9557 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9560 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9562 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9563 if(res!=EQUIP_ERR_OK)
9564 continue;
9566 if(count==0)
9568 if(no_similar_count==0)
9569 return EQUIP_ERR_OK;
9571 if(no_space_count)
9572 *no_space_count = count + no_similar_count;
9573 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9577 if(no_space_count)
9578 *no_space_count = count + no_similar_count;
9580 return EQUIP_ERR_INVENTORY_FULL;
9583 //////////////////////////////////////////////////////////////////////////
9584 uint8 Player::CanStoreItems( Item **pItems,int count) const
9586 Item *pItem2;
9588 // fill space table
9589 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9590 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9591 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9592 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9593 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9595 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9596 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9597 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9598 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9599 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9601 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9603 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9605 if (pItem2 && !pItem2->IsInTrade())
9607 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9611 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9613 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9615 if (pItem2 && !pItem2->IsInTrade())
9617 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9621 // Vanity pet case skipped as not used
9623 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9625 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9627 if (pItem2 && !pItem2->IsInTrade())
9629 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9633 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9635 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9637 if (pItem2 && !pItem2->IsInTrade())
9639 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9643 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9645 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9647 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9649 pItem2 = GetItemByPos( i, j );
9650 if (pItem2 && !pItem2->IsInTrade())
9652 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9658 // check free space for all items
9659 for (int k=0;k<count;k++)
9661 Item *pItem = pItems[k];
9663 // no item
9664 if (!pItem) continue;
9666 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9667 ItemPrototype const *pProto = pItem->GetProto();
9669 // strange item
9670 if( !pProto )
9671 return EQUIP_ERR_ITEM_NOT_FOUND;
9673 // item it 'bind'
9674 if(pItem->IsBindedNotWith(GetGUID()))
9675 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9677 Bag *pBag;
9678 ItemPrototype const *pBagProto;
9680 // item is 'one item only'
9681 uint8 res = CanTakeMoreSimilarItems(pItem);
9682 if(res != EQUIP_ERR_OK)
9683 return res;
9685 // search stack for merge to
9686 if( pProto->Stackable != 1 )
9688 bool b_found = false;
9690 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9692 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9693 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9695 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9696 b_found = true;
9697 break;
9700 if (b_found) continue;
9702 // Vanity pet case skipped as not used
9704 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9706 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9707 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9709 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9710 b_found = true;
9711 break;
9714 if (b_found) continue;
9716 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9718 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9719 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9721 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9722 b_found = true;
9723 break;
9726 if (b_found) continue;
9728 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9730 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9731 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9733 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9734 b_found = true;
9735 break;
9738 if (b_found) continue;
9740 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9742 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9743 if( pBag )
9745 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9747 pItem2 = GetItemByPos( t, j );
9748 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9750 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9751 b_found = true;
9752 break;
9757 if (b_found) continue;
9760 // special bag case
9761 if( pProto->BagFamily )
9763 bool b_found = false;
9764 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9766 uint32 keyringSize = GetMaxKeyringSize();
9767 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9769 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9771 inv_keys[t-KEYRING_SLOT_START] = 1;
9772 b_found = true;
9773 break;
9778 if (b_found) continue;
9780 // Vanity pet case skipped as not used
9782 /* until proper implementation
9783 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9785 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9787 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9789 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9790 b_found = true;
9791 break;
9796 if (b_found) continue;
9798 /* until proper implementation
9799 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9801 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9803 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9805 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9806 b_found = true;
9807 break;
9812 if (b_found) continue;
9815 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9817 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9818 if( pBag )
9820 pBagProto = pBag->GetProto();
9822 // not plain container check
9823 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9824 ItemCanGoIntoBag(pProto,pBagProto) )
9826 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9828 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9830 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9831 b_found = true;
9832 break;
9838 if (b_found) continue;
9841 // search free slot
9842 bool b_found = false;
9843 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9845 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9847 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9848 b_found = true;
9849 break;
9852 if (b_found) continue;
9854 // search free slot in bags
9855 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9857 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9858 if( pBag )
9860 pBagProto = pBag->GetProto();
9862 // special bag already checked
9863 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9864 continue;
9866 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9868 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9870 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9871 b_found = true;
9872 break;
9878 // no free slot found?
9879 if (!b_found)
9880 return EQUIP_ERR_INVENTORY_FULL;
9883 return EQUIP_ERR_OK;
9886 //////////////////////////////////////////////////////////////////////////
9887 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9889 dest = 0;
9890 Item *pItem = Item::CreateItem( item, 1, this );
9891 if( pItem )
9893 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9894 delete pItem;
9895 return result;
9898 return EQUIP_ERR_ITEM_NOT_FOUND;
9901 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9903 dest = 0;
9904 if( pItem )
9906 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9907 ItemPrototype const *pProto = pItem->GetProto();
9908 if( pProto )
9910 if(pItem->IsBindedNotWith(GetGUID()))
9911 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9913 // check count of items (skip for auto move for same player from bank)
9914 uint8 res = CanTakeMoreSimilarItems(pItem);
9915 if(res != EQUIP_ERR_OK)
9916 return res;
9918 // check this only in game
9919 if(not_loading)
9921 // May be here should be more stronger checks; STUNNED checked
9922 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9923 if (hasUnitState(UNIT_STAT_STUNNED))
9924 return EQUIP_ERR_YOU_ARE_STUNNED;
9926 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9927 // - combat
9928 // - in-progress arenas
9929 if( !pProto->CanChangeEquipStateInCombat() )
9931 if( isInCombat() )
9932 return EQUIP_ERR_NOT_IN_COMBAT;
9934 if(BattleGround* bg = GetBattleGround())
9935 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9936 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9939 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9940 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9942 if(IsNonMeleeSpellCasted(false))
9943 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9946 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9947 if( eslot == NULL_SLOT )
9948 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9950 uint8 msg = CanUseItem( pItem , not_loading );
9951 if( msg != EQUIP_ERR_OK )
9952 return msg;
9953 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9954 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9956 // if swap ignore item (equipped also)
9957 if(uint8 res = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9958 return res;
9960 // check unique-equipped special item classes
9961 if (pProto->Class == ITEM_CLASS_QUIVER)
9963 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9965 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9967 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9969 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9971 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9972 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9973 else
9974 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9981 uint32 type = pProto->InventoryType;
9983 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9985 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9987 if(!CanDualWield())
9988 return EQUIP_ERR_CANT_DUAL_WIELD;
9990 else if (type == INVTYPE_2HWEAPON)
9992 if(!CanDualWield() || !CanTitanGrip())
9993 return EQUIP_ERR_CANT_DUAL_WIELD;
9996 if(IsTwoHandUsed())
9997 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
10000 // equip two-hand weapon case (with possible unequip 2 items)
10001 if( type == INVTYPE_2HWEAPON )
10003 if (eslot == EQUIPMENT_SLOT_OFFHAND)
10005 if (!CanTitanGrip())
10006 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10008 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
10009 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10011 if (!CanTitanGrip())
10013 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10014 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10015 ItemPosCountVec off_dest;
10016 if( offItem && (!not_loading ||
10017 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10018 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
10019 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10022 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10023 return EQUIP_ERR_OK;
10026 if( !swap )
10027 return EQUIP_ERR_ITEM_NOT_FOUND;
10028 else
10029 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10032 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10034 // Applied only to equipped items and bank bags
10035 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10036 return EQUIP_ERR_OK;
10038 Item* pItem = GetItemByPos(pos);
10040 // Applied only to existed equipped item
10041 if( !pItem )
10042 return EQUIP_ERR_OK;
10044 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10046 ItemPrototype const *pProto = pItem->GetProto();
10047 if( !pProto )
10048 return EQUIP_ERR_ITEM_NOT_FOUND;
10050 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10051 // - combat
10052 // - in-progress arenas
10053 if( !pProto->CanChangeEquipStateInCombat() )
10055 if( isInCombat() )
10056 return EQUIP_ERR_NOT_IN_COMBAT;
10058 if(BattleGround* bg = GetBattleGround())
10059 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10060 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10063 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10064 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10066 return EQUIP_ERR_OK;
10069 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10071 if( !pItem )
10072 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10074 uint32 count = pItem->GetCount();
10076 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10077 ItemPrototype const *pProto = pItem->GetProto();
10078 if( !pProto )
10079 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10081 if( pItem->IsBindedNotWith(GetGUID()) )
10082 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10084 // check count of items (skip for auto move for same player from bank)
10085 uint8 res = CanTakeMoreSimilarItems(pItem);
10086 if(res != EQUIP_ERR_OK)
10087 return res;
10089 // in specific slot
10090 if( bag != NULL_BAG && slot != NULL_SLOT )
10092 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
10094 if (!pItem->IsBag())
10095 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10097 Bag *pBag = (Bag*)pItem;
10098 if( !HasBankBagSlot( slot ) )
10099 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10101 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
10102 return cantuse;
10105 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10106 if(res!=EQUIP_ERR_OK)
10107 return res;
10109 if(count==0)
10110 return EQUIP_ERR_OK;
10113 // not specific slot or have space for partly store only in specific slot
10115 // in specific bag
10116 if( bag != NULL_BAG )
10118 if( pProto->InventoryType == INVTYPE_BAG )
10120 Bag *pBag = (Bag*)pItem;
10121 if( pBag && !pBag->IsEmpty() )
10122 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10125 // search stack in bag for merge to
10126 if( pProto->Stackable != 1 )
10128 if( bag == INVENTORY_SLOT_BAG_0 )
10130 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10131 if(res!=EQUIP_ERR_OK)
10132 return res;
10134 if(count==0)
10135 return EQUIP_ERR_OK;
10137 else
10139 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10140 if(res!=EQUIP_ERR_OK)
10141 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10143 if(res!=EQUIP_ERR_OK)
10144 return res;
10146 if(count==0)
10147 return EQUIP_ERR_OK;
10151 // search free slot in bag
10152 if( bag == INVENTORY_SLOT_BAG_0 )
10154 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10155 if(res!=EQUIP_ERR_OK)
10156 return res;
10158 if(count==0)
10159 return EQUIP_ERR_OK;
10161 else
10163 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
10164 if(res!=EQUIP_ERR_OK)
10165 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
10167 if(res!=EQUIP_ERR_OK)
10168 return res;
10170 if(count==0)
10171 return EQUIP_ERR_OK;
10175 // not specific bag or have space for partly store only in specific bag
10177 // search stack for merge to
10178 if( pProto->Stackable != 1 )
10180 // in slots
10181 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10182 if(res!=EQUIP_ERR_OK)
10183 return res;
10185 if(count==0)
10186 return EQUIP_ERR_OK;
10188 // in special bags
10189 if( pProto->BagFamily )
10191 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10193 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10194 if(res!=EQUIP_ERR_OK)
10195 continue;
10197 if(count==0)
10198 return EQUIP_ERR_OK;
10202 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10204 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10205 if(res!=EQUIP_ERR_OK)
10206 continue;
10208 if(count==0)
10209 return EQUIP_ERR_OK;
10213 // search free place in special bag
10214 if( pProto->BagFamily )
10216 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10218 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10219 if(res!=EQUIP_ERR_OK)
10220 continue;
10222 if(count==0)
10223 return EQUIP_ERR_OK;
10227 // search free space
10228 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10229 if(res!=EQUIP_ERR_OK)
10230 return res;
10232 if(count==0)
10233 return EQUIP_ERR_OK;
10235 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10237 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10238 if(res!=EQUIP_ERR_OK)
10239 continue;
10241 if(count==0)
10242 return EQUIP_ERR_OK;
10244 return EQUIP_ERR_BANK_FULL;
10247 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10249 if( pItem )
10251 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10252 if( !isAlive() && not_loading )
10253 return EQUIP_ERR_YOU_ARE_DEAD;
10254 //if( isStunned() )
10255 // return EQUIP_ERR_YOU_ARE_STUNNED;
10256 ItemPrototype const *pProto = pItem->GetProto();
10257 if( pProto )
10259 if( pItem->IsBindedNotWith(GetGUID()) )
10260 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10261 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10262 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10263 if( pItem->GetSkill() != 0 )
10265 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10266 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10268 if( pProto->RequiredSkill != 0 )
10270 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10271 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10272 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10273 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10275 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10276 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10277 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10278 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10279 if( getLevel() < pProto->RequiredLevel )
10280 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10281 return EQUIP_ERR_OK;
10284 return EQUIP_ERR_ITEM_NOT_FOUND;
10287 bool Player::CanUseItem( ItemPrototype const *pProto )
10289 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10291 if( pProto )
10293 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10294 return false;
10295 if( pProto->RequiredSkill != 0 )
10297 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10298 return false;
10299 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10300 return false;
10302 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10303 return false;
10304 if( getLevel() < pProto->RequiredLevel )
10305 return false;
10306 return true;
10308 return false;
10311 uint8 Player::CanUseAmmo( uint32 item ) const
10313 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10314 if( !isAlive() )
10315 return EQUIP_ERR_YOU_ARE_DEAD;
10316 //if( isStunned() )
10317 // return EQUIP_ERR_YOU_ARE_STUNNED;
10318 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10319 if( pProto )
10321 if( pProto->InventoryType!= INVTYPE_AMMO )
10322 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10323 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10324 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10325 if( pProto->RequiredSkill != 0 )
10327 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10328 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10329 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10330 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10332 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10333 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10334 /*if( GetReputation() < pProto->RequiredReputation )
10335 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10337 if( getLevel() < pProto->RequiredLevel )
10338 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10340 // Requires No Ammo
10341 if(GetDummyAura(46699))
10342 return EQUIP_ERR_BAG_FULL6;
10344 return EQUIP_ERR_OK;
10346 return EQUIP_ERR_ITEM_NOT_FOUND;
10349 void Player::SetAmmo( uint32 item )
10351 if(!item)
10352 return;
10354 // already set
10355 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10356 return;
10358 // check ammo
10359 if(item)
10361 uint8 msg = CanUseAmmo( item );
10362 if( msg != EQUIP_ERR_OK )
10364 SendEquipError( msg, NULL, NULL );
10365 return;
10369 SetUInt32Value(PLAYER_AMMO_ID, item);
10371 _ApplyAmmoBonuses();
10374 void Player::RemoveAmmo()
10376 SetUInt32Value(PLAYER_AMMO_ID, 0);
10378 m_ammoDPS = 0.0f;
10380 if(CanModifyStats())
10381 UpdateDamagePhysical(RANGED_ATTACK);
10384 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10385 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10387 uint32 count = 0;
10388 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10389 count += itr->count;
10391 Item *pItem = Item::CreateItem( item, count, this );
10392 if( pItem )
10394 ItemAddedQuestCheck( item, count );
10395 if(randomPropertyId)
10396 pItem->SetItemRandomProperties(randomPropertyId);
10397 pItem = StoreItem( dest, pItem, update );
10399 return pItem;
10402 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10404 if( !pItem )
10405 return NULL;
10407 Item* lastItem = pItem;
10409 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10411 uint16 pos = itr->pos;
10412 uint32 count = itr->count;
10414 ++itr;
10416 if(itr == dest.end())
10418 lastItem = _StoreItem(pos,pItem,count,false,update);
10419 break;
10422 lastItem = _StoreItem(pos,pItem,count,true,update);
10425 return lastItem;
10428 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10429 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10431 if( !pItem )
10432 return NULL;
10434 uint8 bag = pos >> 8;
10435 uint8 slot = pos & 255;
10437 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10439 Item *pItem2 = GetItemByPos( bag, slot );
10441 if( !pItem2 )
10443 if(clone)
10444 pItem = pItem->CloneItem(count,this);
10445 else
10446 pItem->SetCount(count);
10448 if(!pItem)
10449 return NULL;
10451 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10452 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10453 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10454 pItem->SetBinding( true );
10456 if( bag == INVENTORY_SLOT_BAG_0 )
10458 m_items[slot] = pItem;
10459 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10460 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10461 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10463 pItem->SetSlot( slot );
10464 pItem->SetContainer( NULL );
10466 if( IsInWorld() && update )
10468 pItem->AddToWorld();
10469 pItem->SendUpdateToPlayer( this );
10472 pItem->SetState(ITEM_CHANGED, this);
10474 else
10476 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10477 if( pBag )
10479 pBag->StoreItem( slot, pItem, update );
10480 if( IsInWorld() && update )
10482 pItem->AddToWorld();
10483 pItem->SendUpdateToPlayer( this );
10485 pItem->SetState(ITEM_CHANGED, this);
10486 pBag->SetState(ITEM_CHANGED, this);
10490 AddEnchantmentDurations(pItem);
10491 AddItemDurations(pItem);
10493 return pItem;
10495 else
10497 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10498 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10499 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10500 pItem2->SetBinding( true );
10502 pItem2->SetCount( pItem2->GetCount() + count );
10503 if( IsInWorld() && update )
10504 pItem2->SendUpdateToPlayer( this );
10506 if(!clone)
10508 // delete item (it not in any slot currently)
10509 if( IsInWorld() && update )
10511 pItem->RemoveFromWorld();
10512 pItem->DestroyForPlayer( this );
10515 RemoveEnchantmentDurations(pItem);
10516 RemoveItemDurations(pItem);
10518 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10519 pItem->SetState(ITEM_REMOVED, this);
10521 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10522 AddEnchantmentDurations(pItem2);
10524 pItem2->SetState(ITEM_CHANGED, this);
10526 return pItem2;
10530 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10532 Item *pItem = Item::CreateItem( item, 1, this );
10533 if( pItem )
10535 ItemAddedQuestCheck( item, 1 );
10536 Item * retItem = EquipItem( pos, pItem, update );
10538 return retItem;
10540 return NULL;
10543 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10545 if( pItem )
10547 AddEnchantmentDurations(pItem);
10548 AddItemDurations(pItem);
10550 uint8 bag = pos >> 8;
10551 uint8 slot = pos & 255;
10553 Item *pItem2 = GetItemByPos( bag, slot );
10555 if( !pItem2 )
10557 VisualizeItem( slot, pItem);
10559 if(isAlive())
10561 ItemPrototype const *pProto = pItem->GetProto();
10563 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10564 if(pProto && pProto->ItemSet)
10565 AddItemsSetItem(this,pItem);
10567 _ApplyItemMods(pItem, slot, true);
10569 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10571 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10573 if (getClass() == CLASS_ROGUE)
10574 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10576 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10578 if (!spellProto)
10579 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10580 else
10582 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10584 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10585 data << uint64(GetGUID());
10586 data << uint8(1);
10587 data << uint32(cooldownSpell);
10588 data << uint32(0);
10589 GetSession()->SendPacket(&data);
10594 if( IsInWorld() && update )
10596 pItem->AddToWorld();
10597 pItem->SendUpdateToPlayer( this );
10600 ApplyEquipCooldown(pItem);
10602 if( slot == EQUIPMENT_SLOT_MAINHAND )
10603 UpdateExpertise(BASE_ATTACK);
10604 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10605 UpdateExpertise(OFF_ATTACK);
10607 else
10609 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10610 if( IsInWorld() && update )
10611 pItem2->SendUpdateToPlayer( this );
10613 // delete item (it not in any slot currently)
10614 //pItem->DeleteFromDB();
10615 if( IsInWorld() && update )
10617 pItem->RemoveFromWorld();
10618 pItem->DestroyForPlayer( this );
10621 RemoveEnchantmentDurations(pItem);
10622 RemoveItemDurations(pItem);
10624 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10625 pItem->SetState(ITEM_REMOVED, this);
10626 pItem2->SetState(ITEM_CHANGED, this);
10628 ApplyEquipCooldown(pItem2);
10630 return pItem2;
10634 return pItem;
10637 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10639 if( pItem )
10641 AddEnchantmentDurations(pItem);
10642 AddItemDurations(pItem);
10644 uint8 slot = pos & 255;
10645 VisualizeItem( slot, pItem);
10647 if( IsInWorld() )
10649 pItem->AddToWorld();
10650 pItem->SendUpdateToPlayer( this );
10655 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10657 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10658 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10659 // entry // Size: 1
10660 // inspected enchantments // Size: 6
10661 // ? // Size: 5
10662 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10663 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10664 // // = 16
10666 if(pItem)
10668 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10670 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10671 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10673 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10674 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10676 // Use SetInt16Value to prevent set high part to FFFF for negative value
10677 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10678 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10680 else
10682 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10684 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10685 SetUInt32Value(VisibleBase + 0, 0);
10687 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10688 SetUInt32Value(VisibleBase + 1 + i, 0);
10690 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10691 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10695 void Player::VisualizeItem( uint8 slot, Item *pItem)
10697 if(!pItem)
10698 return;
10700 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10701 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10702 pItem->SetBinding( true );
10704 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10706 m_items[slot] = pItem;
10707 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10708 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10709 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10710 pItem->SetSlot( slot );
10711 pItem->SetContainer( NULL );
10713 if( slot < EQUIPMENT_SLOT_END )
10714 SetVisibleItemSlot(slot,pItem);
10716 pItem->SetState(ITEM_CHANGED, this);
10719 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10721 // note: removeitem does not actually change the item
10722 // it only takes the item out of storage temporarily
10723 // note2: if removeitem is to be used for delinking
10724 // the item must be removed from the player's updatequeue
10726 Item *pItem = GetItemByPos( bag, slot );
10727 if( pItem )
10729 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10731 RemoveEnchantmentDurations(pItem);
10732 RemoveItemDurations(pItem);
10734 if( bag == INVENTORY_SLOT_BAG_0 )
10736 if ( slot < INVENTORY_SLOT_BAG_END )
10738 ItemPrototype const *pProto = pItem->GetProto();
10739 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10741 if(pProto && pProto->ItemSet)
10742 RemoveItemsSetItem(this,pProto);
10744 _ApplyItemMods(pItem, slot, false);
10746 // remove item dependent auras and casts (only weapon and armor slots)
10747 if(slot < EQUIPMENT_SLOT_END)
10748 RemoveItemDependentAurasAndCasts(pItem);
10750 // remove held enchantments
10751 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10753 if (pItem->GetItemSuffixFactor())
10755 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10756 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10758 else
10760 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10761 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10766 m_items[slot] = NULL;
10767 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10769 if ( slot < EQUIPMENT_SLOT_END )
10770 SetVisibleItemSlot(slot,NULL);
10772 else
10774 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10775 if( pBag )
10776 pBag->RemoveItem(slot, update);
10778 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10779 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10780 pItem->SetSlot( NULL_SLOT );
10781 if( IsInWorld() && update )
10782 pItem->SendUpdateToPlayer( this );
10784 if( slot == EQUIPMENT_SLOT_MAINHAND )
10785 UpdateExpertise(BASE_ATTACK);
10786 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10787 UpdateExpertise(OFF_ATTACK);
10791 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10792 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10794 if(Item* it = GetItemByPos(bag,slot))
10796 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10797 RemoveItem( bag,slot,update);
10798 it->RemoveFromUpdateQueueOf(this);
10799 if(it->IsInWorld())
10801 it->RemoveFromWorld();
10802 it->DestroyForPlayer( this );
10807 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10808 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10810 // update quest counters
10811 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10813 // store item
10814 Item* pLastItem = StoreItem( dest, pItem, update);
10816 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10817 if(pLastItem==pItem)
10819 // update owner for last item (this can be original item with wrong owner
10820 if(pLastItem->GetOwnerGUID() != GetGUID())
10821 pLastItem->SetOwnerGUID(GetGUID());
10823 // if this original item then it need create record in inventory
10824 // in case trade we already have item in other player inventory
10825 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10829 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10831 Item *pItem = GetItemByPos( bag, slot );
10832 if( pItem )
10834 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10836 // start from destroy contained items (only equipped bag can have its)
10837 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10839 for (int i = 0; i < MAX_BAG_SIZE; i++)
10840 DestroyItem(slot,i,update);
10843 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10844 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10846 RemoveEnchantmentDurations(pItem);
10847 RemoveItemDurations(pItem);
10849 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10851 if( bag == INVENTORY_SLOT_BAG_0 )
10853 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10855 // equipment and equipped bags can have applied bonuses
10856 if ( slot < INVENTORY_SLOT_BAG_END )
10858 ItemPrototype const *pProto = pItem->GetProto();
10860 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10861 if(pProto && pProto->ItemSet)
10862 RemoveItemsSetItem(this,pProto);
10864 _ApplyItemMods(pItem, slot, false);
10867 if ( slot < EQUIPMENT_SLOT_END )
10869 // remove item dependent auras and casts (only weapon and armor slots)
10870 RemoveItemDependentAurasAndCasts(pItem);
10872 // equipment visual show
10873 SetVisibleItemSlot(slot,NULL);
10876 m_items[slot] = NULL;
10878 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10879 pBag->RemoveItem(slot, update);
10881 if( IsInWorld() && update )
10883 pItem->RemoveFromWorld();
10884 pItem->DestroyForPlayer(this);
10887 //pItem->SetOwnerGUID(0);
10888 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10889 pItem->SetSlot( NULL_SLOT );
10890 pItem->SetState(ITEM_REMOVED, this);
10894 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10896 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10897 Item *pItem;
10898 ItemPrototype const *pProto;
10899 uint32 remcount = 0;
10901 // in inventory
10902 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10904 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10905 if( pItem && pItem->GetEntry() == item )
10907 if( pItem->GetCount() + remcount <= count )
10909 // all items in inventory can unequipped
10910 remcount += pItem->GetCount();
10911 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10913 if(remcount >=count)
10914 return;
10916 else
10918 pProto = pItem->GetProto();
10919 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10920 pItem->SetCount( pItem->GetCount() - count + remcount );
10921 if( IsInWorld() & update )
10922 pItem->SendUpdateToPlayer( this );
10923 pItem->SetState(ITEM_CHANGED, this);
10924 return;
10928 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10930 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10931 if( pItem && pItem->GetEntry() == item )
10933 if( pItem->GetCount() + remcount <= count )
10935 // all keys can be unequipped
10936 remcount += pItem->GetCount();
10937 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10939 if(remcount >=count)
10940 return;
10942 else
10944 pProto = pItem->GetProto();
10945 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10946 pItem->SetCount( pItem->GetCount() - count + remcount );
10947 if( IsInWorld() & update )
10948 pItem->SendUpdateToPlayer( this );
10949 pItem->SetState(ITEM_CHANGED, this);
10950 return;
10955 // in inventory bags
10956 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10958 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10960 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10962 pItem = pBag->GetItemByPos(j);
10963 if( pItem && pItem->GetEntry() == item )
10965 // all items in bags can be unequipped
10966 if( pItem->GetCount() + remcount <= count )
10968 remcount += pItem->GetCount();
10969 DestroyItem( i, j, update );
10971 if(remcount >=count)
10972 return;
10974 else
10976 pProto = pItem->GetProto();
10977 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10978 pItem->SetCount( pItem->GetCount() - count + remcount );
10979 if( IsInWorld() && update )
10980 pItem->SendUpdateToPlayer( this );
10981 pItem->SetState(ITEM_CHANGED, this);
10982 return;
10989 // in equipment and bag list
10990 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10992 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10993 if( pItem && pItem->GetEntry() == item )
10995 if( pItem->GetCount() + remcount <= count )
10997 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10999 remcount += pItem->GetCount();
11000 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11002 if(remcount >=count)
11003 return;
11006 else
11008 pProto = pItem->GetProto();
11009 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11010 pItem->SetCount( pItem->GetCount() - count + remcount );
11011 if( IsInWorld() & update )
11012 pItem->SendUpdateToPlayer( this );
11013 pItem->SetState(ITEM_CHANGED, this);
11014 return;
11020 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11022 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11024 // in inventory
11025 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11027 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11028 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11029 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11031 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
11033 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11034 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11035 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11038 // in inventory bags
11039 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11041 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11042 if( pBag )
11044 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11046 Item* pItem = pBag->GetItemByPos(j);
11047 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11048 DestroyItem( i, j, update);
11053 // in equipment and bag list
11054 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11056 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11057 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
11058 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11062 void Player::DestroyConjuredItems( bool update )
11064 // used when entering arena
11065 // destroys all conjured items
11066 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11068 // in inventory
11069 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11071 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11072 if( pItem && pItem->GetProto() &&
11073 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11074 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11075 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11078 // in inventory bags
11079 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11081 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11082 if( pBag )
11084 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11086 Item* pItem = pBag->GetItemByPos(j);
11087 if( pItem && pItem->GetProto() &&
11088 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11089 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11090 DestroyItem( i, j, update);
11095 // in equipment and bag list
11096 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
11098 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11099 if( pItem && pItem->GetProto() &&
11100 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
11101 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
11102 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11106 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11108 if(!pItem)
11109 return;
11111 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11113 if( pItem->GetCount() <= count )
11115 count-= pItem->GetCount();
11117 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11119 else
11121 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11122 pItem->SetCount( pItem->GetCount() - count );
11123 count = 0;
11124 if( IsInWorld() & update )
11125 pItem->SendUpdateToPlayer( this );
11126 pItem->SetState(ITEM_CHANGED, this);
11130 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11132 uint8 srcbag = src >> 8;
11133 uint8 srcslot = src & 255;
11135 uint8 dstbag = dst >> 8;
11136 uint8 dstslot = dst & 255;
11138 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11139 if( !pSrcItem )
11141 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11142 return;
11145 // not let split all items (can be only at cheating)
11146 if(pSrcItem->GetCount() == count)
11148 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11149 return;
11152 // not let split more existed items (can be only at cheating)
11153 if(pSrcItem->GetCount() < count)
11155 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11156 return;
11159 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11161 //best error message found for attempting to split while looting
11162 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11163 return;
11166 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11167 Item *pNewItem = pSrcItem->CloneItem( count, this );
11168 if( !pNewItem )
11170 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11171 return;
11174 if( IsInventoryPos( dst ) )
11176 // change item amount before check (for unique max count check)
11177 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11179 ItemPosCountVec dest;
11180 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11181 if( msg != EQUIP_ERR_OK )
11183 delete pNewItem;
11184 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11185 SendEquipError( msg, pSrcItem, NULL );
11186 return;
11189 if( IsInWorld() )
11190 pSrcItem->SendUpdateToPlayer( this );
11191 pSrcItem->SetState(ITEM_CHANGED, this);
11192 StoreItem( dest, pNewItem, true);
11194 else if( IsBankPos ( dst ) )
11196 // change item amount before check (for unique max count check)
11197 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11199 ItemPosCountVec dest;
11200 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11201 if( msg != EQUIP_ERR_OK )
11203 delete pNewItem;
11204 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11205 SendEquipError( msg, pSrcItem, NULL );
11206 return;
11209 if( IsInWorld() )
11210 pSrcItem->SendUpdateToPlayer( this );
11211 pSrcItem->SetState(ITEM_CHANGED, this);
11212 BankItem( dest, pNewItem, true);
11214 else if( IsEquipmentPos ( dst ) )
11216 // change item amount before check (for unique max count check), provide space for splitted items
11217 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11219 uint16 dest;
11220 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11221 if( msg != EQUIP_ERR_OK )
11223 delete pNewItem;
11224 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11225 SendEquipError( msg, pSrcItem, NULL );
11226 return;
11229 if( IsInWorld() )
11230 pSrcItem->SendUpdateToPlayer( this );
11231 pSrcItem->SetState(ITEM_CHANGED, this);
11232 EquipItem( dest, pNewItem, true);
11233 AutoUnequipOffhandIfNeed();
11237 void Player::SwapItem( uint16 src, uint16 dst )
11239 uint8 srcbag = src >> 8;
11240 uint8 srcslot = src & 255;
11242 uint8 dstbag = dst >> 8;
11243 uint8 dstslot = dst & 255;
11245 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11246 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11248 if( !pSrcItem )
11249 return;
11251 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11253 if(!isAlive() )
11255 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11256 return;
11259 // SRC checks
11261 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11263 //best error message found for attempting to swap while looting
11264 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11265 return;
11268 // check unequip potability for equipped items and bank bags
11269 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11271 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11272 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
11273 if(msg != EQUIP_ERR_OK)
11275 SendEquipError( msg, pSrcItem, pDstItem );
11276 return;
11280 // prevent put equipped/bank bag in self
11281 if( IsBagPos ( src ) && srcslot == dstbag)
11283 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11284 return;
11287 // DST checks
11289 if (pDstItem)
11291 if(pDstItem->m_lootGenerated) // prevent swap looting item
11293 //best error message found for attempting to swap while looting
11294 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11295 return;
11298 // check unequip potability for equipped items and bank bags
11299 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11301 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11302 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
11303 if(msg != EQUIP_ERR_OK)
11305 SendEquipError( msg, pSrcItem, pDstItem );
11306 return;
11311 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11312 // or swap empty bag with another empty or not empty bag (with items exchange)
11314 // Move case
11315 if( !pDstItem )
11317 if( IsInventoryPos( dst ) )
11319 ItemPosCountVec dest;
11320 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11321 if( msg != EQUIP_ERR_OK )
11323 SendEquipError( msg, pSrcItem, NULL );
11324 return;
11327 RemoveItem(srcbag, srcslot, true);
11328 StoreItem( dest, pSrcItem, true);
11330 else if( IsBankPos ( dst ) )
11332 ItemPosCountVec dest;
11333 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11334 if( msg != EQUIP_ERR_OK )
11336 SendEquipError( msg, pSrcItem, NULL );
11337 return;
11340 RemoveItem(srcbag, srcslot, true);
11341 BankItem( dest, pSrcItem, true);
11343 else if( IsEquipmentPos ( dst ) )
11345 uint16 dest;
11346 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11347 if( msg != EQUIP_ERR_OK )
11349 SendEquipError( msg, pSrcItem, NULL );
11350 return;
11353 RemoveItem(srcbag, srcslot, true);
11354 EquipItem( dest, pSrcItem, true);
11355 AutoUnequipOffhandIfNeed();
11358 return;
11361 // attempt merge to / fill target item
11362 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11364 uint8 msg;
11365 ItemPosCountVec sDest;
11366 uint16 eDest;
11367 if( IsInventoryPos( dst ) )
11368 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11369 else if( IsBankPos ( dst ) )
11370 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11371 else if( IsEquipmentPos ( dst ) )
11372 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11373 else
11374 return;
11376 // can be merge/fill
11377 if(msg == EQUIP_ERR_OK)
11379 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11381 RemoveItem(srcbag, srcslot, true);
11383 if( IsInventoryPos( dst ) )
11384 StoreItem( sDest, pSrcItem, true);
11385 else if( IsBankPos ( dst ) )
11386 BankItem( sDest, pSrcItem, true);
11387 else if( IsEquipmentPos ( dst ) )
11389 EquipItem( eDest, pSrcItem, true);
11390 AutoUnequipOffhandIfNeed();
11393 else
11395 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11396 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11397 pSrcItem->SetState(ITEM_CHANGED, this);
11398 pDstItem->SetState(ITEM_CHANGED, this);
11399 if( IsInWorld() )
11401 pSrcItem->SendUpdateToPlayer( this );
11402 pDstItem->SendUpdateToPlayer( this );
11405 return;
11409 // impossible merge/fill, do real swap
11410 uint8 msg;
11412 // check src->dest move possibility
11413 ItemPosCountVec sDest;
11414 uint16 eDest;
11415 if( IsInventoryPos( dst ) )
11416 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11417 else if( IsBankPos( dst ) )
11418 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11419 else if( IsEquipmentPos( dst ) )
11421 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11422 if( msg == EQUIP_ERR_OK )
11423 msg = CanUnequipItem( eDest, true );
11426 if( msg != EQUIP_ERR_OK )
11428 SendEquipError( msg, pSrcItem, pDstItem );
11429 return;
11432 // check dest->src move possibility
11433 ItemPosCountVec sDest2;
11434 uint16 eDest2;
11435 if( IsInventoryPos( src ) )
11436 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11437 else if( IsBankPos( src ) )
11438 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11439 else if( IsEquipmentPos( src ) )
11441 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11442 if( msg == EQUIP_ERR_OK )
11443 msg = CanUnequipItem( eDest2, true);
11446 if( msg != EQUIP_ERR_OK )
11448 SendEquipError( msg, pDstItem, pSrcItem );
11449 return;
11452 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11453 if(pSrcItem->IsBag() && pDstItem->IsBag())
11455 Bag* emptyBag = NULL;
11456 Bag* fullBag = NULL;
11457 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11459 emptyBag = (Bag*)pSrcItem;
11460 fullBag = (Bag*)pDstItem;
11462 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11464 emptyBag = (Bag*)pDstItem;
11465 fullBag = (Bag*)pSrcItem;
11468 // bag swap (with items exchange) case
11469 if(emptyBag && fullBag)
11471 ItemPrototype const* emotyProto = emptyBag->GetProto();
11473 uint32 count = 0;
11475 for(int i=0; i < fullBag->GetBagSize(); ++i)
11477 Item *bagItem = fullBag->GetItemByPos(i);
11478 if (!bagItem)
11479 continue;
11481 ItemPrototype const* bagItemProto = bagItem->GetProto();
11482 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11484 // one from items not go to empry target bag
11485 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11486 return;
11489 ++count;
11493 if (count > emptyBag->GetBagSize())
11495 // too small targeted bag
11496 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11497 return;
11500 // Items swap
11501 count = 0; // will pos in new bag
11502 for(int i=0; i< fullBag->GetBagSize(); ++i)
11504 Item *bagItem = fullBag->GetItemByPos(i);
11505 if (!bagItem)
11506 continue;
11508 fullBag->RemoveItem(i, true);
11509 emptyBag->StoreItem(count, bagItem, true);
11510 bagItem->SetState(ITEM_CHANGED, this);
11512 ++count;
11517 // now do moves, remove...
11518 RemoveItem(dstbag, dstslot, false);
11519 RemoveItem(srcbag, srcslot, false);
11521 // add to dest
11522 if( IsInventoryPos( dst ) )
11523 StoreItem(sDest, pSrcItem, true);
11524 else if( IsBankPos( dst ) )
11525 BankItem(sDest, pSrcItem, true);
11526 else if( IsEquipmentPos( dst ) )
11527 EquipItem(eDest, pSrcItem, true);
11529 // add to src
11530 if( IsInventoryPos( src ) )
11531 StoreItem(sDest2, pDstItem, true);
11532 else if( IsBankPos( src ) )
11533 BankItem(sDest2, pDstItem, true);
11534 else if( IsEquipmentPos( src ) )
11535 EquipItem(eDest2, pDstItem, true);
11537 AutoUnequipOffhandIfNeed();
11540 void Player::AddItemToBuyBackSlot( Item *pItem )
11542 if( pItem )
11544 uint32 slot = m_currentBuybackSlot;
11545 // if current back slot non-empty search oldest or free
11546 if(m_items[slot])
11548 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11549 uint32 oldest_slot = BUYBACK_SLOT_START;
11551 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11553 // found empty
11554 if(!m_items[i])
11556 slot = i;
11557 break;
11560 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11562 if(oldest_time > i_time)
11564 oldest_time = i_time;
11565 oldest_slot = i;
11569 // find oldest
11570 slot = oldest_slot;
11573 RemoveItemFromBuyBackSlot( slot, true );
11574 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11576 m_items[slot] = pItem;
11577 time_t base = time(NULL);
11578 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11579 uint32 eslot = slot - BUYBACK_SLOT_START;
11581 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11582 ItemPrototype const *pProto = pItem->GetProto();
11583 if( pProto )
11584 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11585 else
11586 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11587 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11589 // move to next (for non filled list is move most optimized choice)
11590 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11591 ++m_currentBuybackSlot;
11595 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11597 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11598 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11599 return m_items[slot];
11600 return NULL;
11603 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11605 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11606 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11608 Item *pItem = m_items[slot];
11609 if( pItem )
11611 pItem->RemoveFromWorld();
11612 if(del) pItem->SetState(ITEM_REMOVED, this);
11615 m_items[slot] = NULL;
11617 uint32 eslot = slot - BUYBACK_SLOT_START;
11618 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11619 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11620 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11622 // if current backslot is filled set to now free slot
11623 if(m_items[m_currentBuybackSlot])
11624 m_currentBuybackSlot = slot;
11628 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11630 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11631 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11632 data << uint8(msg);
11634 if(msg)
11636 data << uint64(pItem ? pItem->GetGUID() : 0);
11637 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11638 data << uint8(0); // not 0 there...
11640 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11642 uint32 level = 0;
11644 if(pItem)
11645 if(ItemPrototype const* proto = pItem->GetProto())
11646 level = proto->RequiredLevel;
11648 data << uint32(level); // new 2.4.0
11651 GetSession()->SendPacket(&data);
11654 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11656 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11657 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11658 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11659 data << uint32(item);
11660 if( param > 0 )
11661 data << uint32(param);
11662 data << uint8(msg);
11663 GetSession()->SendPacket(&data);
11666 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11668 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11669 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11670 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11671 data << uint64(guid);
11672 if( param > 0 )
11673 data << uint32(param);
11674 data << uint8(msg);
11675 GetSession()->SendPacket(&data);
11678 void Player::ClearTrade()
11680 tradeGold = 0;
11681 acceptTrade = false;
11682 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11683 tradeItems[i] = NULL_SLOT;
11686 void Player::TradeCancel(bool sendback)
11688 if(pTrader)
11690 // send yellow "Trade canceled" message to both traders
11691 WorldSession* ws;
11692 ws = GetSession();
11693 if(sendback)
11694 ws->SendCancelTrade();
11695 ws = pTrader->GetSession();
11696 if(!ws->PlayerLogout())
11697 ws->SendCancelTrade();
11699 // cleanup
11700 ClearTrade();
11701 pTrader->ClearTrade();
11702 // prevent loss of reference
11703 pTrader->pTrader = NULL;
11704 pTrader = NULL;
11708 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11710 if(m_itemDuration.empty())
11711 return;
11713 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11715 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11717 Item* item = *itr;
11718 ++itr; // current element can be erased in UpdateDuration
11720 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11721 item->UpdateDuration(this,time);
11725 void Player::UpdateEnchantTime(uint32 time)
11727 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11729 assert(itr->item);
11730 next=itr;
11731 if(!itr->item->GetEnchantmentId(itr->slot))
11733 next = m_enchantDuration.erase(itr);
11735 else if(itr->leftduration <= time)
11737 ApplyEnchantment(itr->item,itr->slot,false,false);
11738 itr->item->ClearEnchantment(itr->slot);
11739 next = m_enchantDuration.erase(itr);
11741 else if(itr->leftduration > time)
11743 itr->leftduration -= time;
11744 ++next;
11749 void Player::AddEnchantmentDurations(Item *item)
11751 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11753 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11754 continue;
11756 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11757 if( duration > 0 )
11758 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11762 void Player::RemoveEnchantmentDurations(Item *item)
11764 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11766 if(itr->item == item)
11768 // save duration in item
11769 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11770 itr = m_enchantDuration.erase(itr);
11772 else
11773 ++itr;
11777 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11779 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11780 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11782 next = itr;
11783 if(itr->slot==slot)
11785 if(itr->item && itr->item->GetEnchantmentId(slot))
11787 // remove from stats
11788 ApplyEnchantment(itr->item,slot,false,false);
11789 // remove visual
11790 itr->item->ClearEnchantment(slot);
11792 // remove from update list
11793 next = m_enchantDuration.erase(itr);
11795 else
11796 ++next;
11799 // remove enchants from inventory items
11800 // NOTE: no need to remove these from stats, since these aren't equipped
11801 // in inventory
11802 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11804 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11805 if( pItem && pItem->GetEnchantmentId(slot) )
11806 pItem->ClearEnchantment(slot);
11809 // in inventory bags
11810 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11812 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11813 if( pBag )
11815 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11817 Item* pItem = pBag->GetItemByPos(j);
11818 if( pItem && pItem->GetEnchantmentId(slot) )
11819 pItem->ClearEnchantment(slot);
11825 // duration == 0 will remove item enchant
11826 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11828 if(!item)
11829 return;
11831 if(slot >= MAX_ENCHANTMENT_SLOT)
11832 return;
11834 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11836 if(itr->item == item && itr->slot == slot)
11838 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11839 m_enchantDuration.erase(itr);
11840 break;
11843 if(item && duration > 0 )
11845 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11846 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11850 void Player::ApplyEnchantment(Item *item,bool apply)
11852 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11853 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11856 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11858 if(!item)
11859 return;
11861 if(!item->IsEquipped())
11862 return;
11864 if(slot >= MAX_ENCHANTMENT_SLOT)
11865 return;
11867 uint32 enchant_id = item->GetEnchantmentId(slot);
11868 if(!enchant_id)
11869 return;
11871 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11872 if(!pEnchant)
11873 return;
11875 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11876 return;
11878 for (int s=0; s<3; s++)
11880 uint32 enchant_display_type = pEnchant->type[s];
11881 uint32 enchant_amount = pEnchant->amount[s];
11882 uint32 enchant_spell_id = pEnchant->spellid[s];
11884 switch(enchant_display_type)
11886 case ITEM_ENCHANTMENT_TYPE_NONE:
11887 break;
11888 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11889 // processed in Player::CastItemCombatSpell
11890 break;
11891 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11892 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11893 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11894 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11895 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11896 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11897 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11898 break;
11899 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11900 if(enchant_spell_id)
11902 if(apply)
11904 int32 basepoints = 0;
11905 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11906 if (item->GetItemRandomPropertyId())
11908 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11909 if (item_rand)
11911 // Search enchant_amount
11912 for (int k=0; k<3; k++)
11914 if(item_rand->enchant_id[k] == enchant_id)
11916 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11917 break;
11922 // Cast custom spell vs all equal basepoints getted from enchant_amount
11923 if (basepoints)
11924 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11925 else
11926 CastSpell(this,enchant_spell_id,true,item);
11928 else
11929 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11931 break;
11932 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11933 if (!enchant_amount)
11935 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11936 if(item_rand)
11938 for (int k=0; k<3; k++)
11940 if(item_rand->enchant_id[k] == enchant_id)
11942 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11943 break;
11949 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11950 break;
11951 case ITEM_ENCHANTMENT_TYPE_STAT:
11953 if (!enchant_amount)
11955 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11956 if(item_rand_suffix)
11958 for (int k=0; k<3; k++)
11960 if(item_rand_suffix->enchant_id[k] == enchant_id)
11962 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11963 break;
11969 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11970 switch (enchant_spell_id)
11972 case ITEM_MOD_AGILITY:
11973 sLog.outDebug("+ %u AGILITY",enchant_amount);
11974 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11975 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11976 break;
11977 case ITEM_MOD_STRENGTH:
11978 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11979 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11980 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11981 break;
11982 case ITEM_MOD_INTELLECT:
11983 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11984 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11985 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11986 break;
11987 case ITEM_MOD_SPIRIT:
11988 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11989 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11990 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11991 break;
11992 case ITEM_MOD_STAMINA:
11993 sLog.outDebug("+ %u STAMINA",enchant_amount);
11994 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11995 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11996 break;
11997 case ITEM_MOD_DEFENSE_SKILL_RATING:
11998 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11999 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12000 break;
12001 case ITEM_MOD_DODGE_RATING:
12002 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12003 sLog.outDebug("+ %u DODGE", enchant_amount);
12004 break;
12005 case ITEM_MOD_PARRY_RATING:
12006 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12007 sLog.outDebug("+ %u PARRY", enchant_amount);
12008 break;
12009 case ITEM_MOD_BLOCK_RATING:
12010 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12011 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12012 break;
12013 case ITEM_MOD_HIT_MELEE_RATING:
12014 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12015 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12016 break;
12017 case ITEM_MOD_HIT_RANGED_RATING:
12018 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12019 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12020 break;
12021 case ITEM_MOD_HIT_SPELL_RATING:
12022 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12023 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12024 break;
12025 case ITEM_MOD_CRIT_MELEE_RATING:
12026 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12027 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12028 break;
12029 case ITEM_MOD_CRIT_RANGED_RATING:
12030 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12031 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12032 break;
12033 case ITEM_MOD_CRIT_SPELL_RATING:
12034 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12035 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12036 break;
12037 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12038 // in Enchantments
12039 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12040 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12041 // break;
12042 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12043 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12044 // break;
12045 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12046 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12047 // break;
12048 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12049 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12050 // break;
12051 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12052 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12053 // break;
12054 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12055 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12056 // break;
12057 // case ITEM_MOD_HASTE_MELEE_RATING:
12058 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12059 // break;
12060 // case ITEM_MOD_HASTE_RANGED_RATING:
12061 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12062 // break;
12063 case ITEM_MOD_HASTE_SPELL_RATING:
12064 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12065 break;
12066 case ITEM_MOD_HIT_RATING:
12067 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12068 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12069 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12070 sLog.outDebug("+ %u HIT", enchant_amount);
12071 break;
12072 case ITEM_MOD_CRIT_RATING:
12073 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12074 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12075 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12076 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12077 break;
12078 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12079 // case ITEM_MOD_HIT_TAKEN_RATING:
12080 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12081 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12082 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12083 // break;
12084 // case ITEM_MOD_CRIT_TAKEN_RATING:
12085 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12086 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12087 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12088 // break;
12089 case ITEM_MOD_RESILIENCE_RATING:
12090 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12091 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12092 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12093 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12094 break;
12095 case ITEM_MOD_HASTE_RATING:
12096 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12097 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12098 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12099 sLog.outDebug("+ %u HASTE", enchant_amount);
12100 break;
12101 case ITEM_MOD_EXPERTISE_RATING:
12102 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12103 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12104 break;
12105 case ITEM_MOD_ATTACK_POWER:
12106 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12107 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12108 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12109 break;
12110 case ITEM_MOD_RANGED_ATTACK_POWER:
12111 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12112 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12113 break;
12114 case ITEM_MOD_FERAL_ATTACK_POWER:
12115 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
12116 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
12117 break;
12118 case ITEM_MOD_SPELL_HEALING_DONE:
12119 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12120 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
12121 break;
12122 case ITEM_MOD_SPELL_DAMAGE_DONE:
12123 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12124 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
12125 break;
12126 case ITEM_MOD_MANA_REGENERATION:
12127 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12128 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12129 break;
12130 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12131 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12132 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12133 break;
12134 case ITEM_MOD_SPELL_POWER:
12135 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
12136 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
12137 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12138 break;
12139 default:
12140 break;
12142 break;
12144 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12146 if(getClass() == CLASS_SHAMAN)
12148 float addValue = 0.0f;
12149 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12151 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12152 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12154 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12156 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
12157 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12160 break;
12162 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12163 // processed in Player::CastItemUseSpell
12164 break;
12165 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12166 // nothing do..
12167 break;
12168 default:
12169 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12170 break;
12171 } /*switch(enchant_display_type)*/
12172 } /*for*/
12174 // visualize enchantment at player and equipped items
12175 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
12177 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
12178 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
12181 if(apply_dur)
12183 if(apply)
12185 // set duration
12186 uint32 duration = item->GetEnchantmentDuration(slot);
12187 if(duration > 0)
12188 AddEnchantmentDuration(item,slot,duration);
12190 else
12192 // duration == 0 will remove EnchantDuration
12193 AddEnchantmentDuration(item,slot,0);
12198 void Player::SendEnchantmentDurations()
12200 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
12202 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
12206 void Player::SendItemDurations()
12208 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
12210 (*itr)->SendTimeUpdate(this);
12214 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12216 if(!item) // prevent crash
12217 return;
12219 // last check 2.0.10
12220 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12221 data << GetGUID(); // player GUID
12222 data << uint32(received); // 0=looted, 1=from npc
12223 data << uint32(created); // 0=received, 1=created
12224 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12225 data << (uint8)item->GetBagSlot(); // bagslot
12226 // item slot, but when added to stack: 0xFFFFFFFF
12227 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
12228 data << uint32(item->GetEntry()); // item id
12229 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12230 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12231 data << uint32(count); // count of items
12232 data << GetItemCount(item->GetEntry()); // count of items in inventory
12234 if (broadcast && GetGroup())
12235 GetGroup()->BroadcastPacket(&data);
12236 else
12237 GetSession()->SendPacket(&data);
12240 /*********************************************************/
12241 /*** QUEST SYSTEM ***/
12242 /*********************************************************/
12244 void Player::PrepareQuestMenu( uint64 guid )
12246 Object *pObject;
12247 QuestRelations* pObjectQR;
12248 QuestRelations* pObjectQIR;
12249 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12250 if( pCreature )
12252 pObject = (Object*)pCreature;
12253 pObjectQR = &objmgr.mCreatureQuestRelations;
12254 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12256 else
12258 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12259 if( pGameObject )
12261 pObject = (Object*)pGameObject;
12262 pObjectQR = &objmgr.mGOQuestRelations;
12263 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12265 else
12266 return;
12269 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12270 qm.ClearMenu();
12272 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12274 uint32 quest_id = i->second;
12275 QuestStatus status = GetQuestStatus( quest_id );
12276 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12277 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12278 else if ( status == QUEST_STATUS_INCOMPLETE )
12279 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
12280 else if (status == QUEST_STATUS_AVAILABLE )
12281 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12284 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12286 uint32 quest_id = i->second;
12287 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12288 if(!pQuest) continue;
12290 QuestStatus status = GetQuestStatus( quest_id );
12292 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12293 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
12294 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12295 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
12299 void Player::SendPreparedQuest( uint64 guid )
12301 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12302 if( questMenu.Empty() )
12303 return;
12305 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
12307 uint32 status = qmi0.m_qIcon;
12309 // single element case
12310 if ( questMenu.MenuItemCount() == 1 )
12312 // Auto open -- maybe also should verify there is no greeting
12313 uint32 quest_id = qmi0.m_qId;
12314 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
12315 if ( pQuest )
12317 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12318 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
12319 else if( status == DIALOG_STATUS_INCOMPLETE )
12320 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12321 // Send completable on repeatable quest if player don't have quest
12322 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12323 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12324 else
12325 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12328 // multiply entries
12329 else
12331 QEmote qe;
12332 qe._Delay = 0;
12333 qe._Emote = 0;
12334 std::string title = "";
12335 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12336 if( pCreature )
12338 uint32 textid = pCreature->GetNpcTextId();
12339 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12340 if( !gossiptext )
12342 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12343 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12344 title = "";
12346 else
12348 qe = gossiptext->Options[0].Emotes[0];
12350 if(!gossiptext->Options[0].Text_0.empty())
12352 title = gossiptext->Options[0].Text_0;
12354 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12355 if (loc_idx >= 0)
12357 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12358 if (nl)
12360 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12361 title = nl->Text_0[0][loc_idx];
12365 else
12367 title = gossiptext->Options[0].Text_1;
12369 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12370 if (loc_idx >= 0)
12372 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12373 if (nl)
12375 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12376 title = nl->Text_1[0][loc_idx];
12382 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12386 bool Player::IsActiveQuest( uint32 quest_id ) const
12388 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12390 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12393 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12395 Object *pObject;
12396 QuestRelations* pObjectQR;
12397 QuestRelations* pObjectQIR;
12399 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12400 if( pCreature )
12402 pObject = (Object*)pCreature;
12403 pObjectQR = &objmgr.mCreatureQuestRelations;
12404 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12406 else
12408 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12409 if( pGameObject )
12411 pObject = (Object*)pGameObject;
12412 pObjectQR = &objmgr.mGOQuestRelations;
12413 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12415 else
12416 return NULL;
12419 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12420 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12422 if (itr->second == nextQuestID)
12423 return objmgr.GetQuestTemplate(nextQuestID);
12426 return NULL;
12429 bool Player::CanSeeStartQuest( Quest const *pQuest )
12431 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12432 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12433 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12434 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12436 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12439 return false;
12442 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12444 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12445 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12446 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12447 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12448 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12449 && SatisfyQuestDay( pQuest, msg );
12452 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12454 if( !SatisfyQuestLog( msg ) )
12455 return false;
12457 uint32 srcitem = pQuest->GetSrcItemId();
12458 if( srcitem > 0 )
12460 uint32 count = pQuest->GetSrcItemCount();
12461 ItemPosCountVec dest;
12462 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12464 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12465 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12466 return true;
12467 else if( msg != EQUIP_ERR_OK )
12469 SendEquipError( msg, NULL, NULL );
12470 return false;
12473 return true;
12476 bool Player::CanCompleteQuest( uint32 quest_id )
12478 if( quest_id )
12480 QuestStatusData& q_status = mQuestStatus[quest_id];
12481 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12482 return false; // not allow re-complete quest
12484 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12486 if(!qInfo)
12487 return false;
12489 // auto complete quest
12490 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12491 return true;
12493 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12496 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12498 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12500 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12501 return false;
12505 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12507 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12509 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12510 continue;
12512 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12513 return false;
12517 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12518 return false;
12520 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12521 return false;
12523 if ( qInfo->GetRewOrReqMoney() < 0 )
12525 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12526 return false;
12529 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12530 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12531 return false;
12533 return true;
12536 return false;
12539 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12541 // Solve problem that player don't have the quest and try complete it.
12542 // if repeatable she must be able to complete event if player don't have it.
12543 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12544 if( !CanTakeQuest(pQuest, false) )
12545 return false;
12547 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12548 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12549 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12550 return false;
12552 if( !CanRewardQuest(pQuest, false) )
12553 return false;
12555 return true;
12558 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12560 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12561 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12562 return false;
12564 // daily quest can't be rewarded (25 daily quest already completed)
12565 if(!SatisfyQuestDay(pQuest,true))
12566 return false;
12568 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12569 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12570 return false;
12572 // prevent receive reward with quest items in bank
12573 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12575 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12577 if( pQuest->ReqItemCount[i]!= 0 &&
12578 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12580 if(msg)
12581 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12582 return false;
12587 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12588 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12589 return false;
12591 return true;
12594 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12596 // prevent receive reward with quest items in bank or for not completed quest
12597 if(!CanRewardQuest(pQuest,msg))
12598 return false;
12600 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12602 if( pQuest->RewChoiceItemId[reward] )
12604 ItemPosCountVec dest;
12605 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12606 if( res != EQUIP_ERR_OK )
12608 SendEquipError( res, NULL, NULL );
12609 return false;
12614 if ( pQuest->GetRewItemsCount() > 0 )
12616 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12618 if( pQuest->RewItemId[i] )
12620 ItemPosCountVec dest;
12621 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12622 if( res != EQUIP_ERR_OK )
12624 SendEquipError( res, NULL, NULL );
12625 return false;
12631 return true;
12634 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12636 uint16 log_slot = FindQuestSlot( 0 );
12637 assert(log_slot < MAX_QUEST_LOG_SIZE);
12639 uint32 quest_id = pQuest->GetQuestId();
12641 // if not exist then created with set uState==NEW and rewarded=false
12642 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12644 // check for repeatable quests status reset
12645 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12646 questStatusData.m_explored = false;
12648 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12650 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12651 questStatusData.m_itemcount[i] = 0;
12654 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12656 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12657 questStatusData.m_creatureOrGOcount[i] = 0;
12660 GiveQuestSourceItem( pQuest );
12661 AdjustQuestReqItemCount( pQuest, questStatusData );
12663 if( pQuest->GetRepObjectiveFaction() )
12664 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12666 uint32 qtime = 0;
12667 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12669 uint32 limittime = pQuest->GetLimitTime();
12671 // shared timed quest
12672 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12673 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12675 AddTimedQuest( quest_id );
12676 questStatusData.m_timer = limittime * IN_MILISECONDS;
12677 qtime = static_cast<uint32>(time(NULL)) + limittime;
12679 else
12680 questStatusData.m_timer = 0;
12682 SetQuestSlot(log_slot, quest_id, qtime);
12684 if (questStatusData.uState != QUEST_NEW)
12685 questStatusData.uState = QUEST_CHANGED;
12687 //starting initial quest script
12688 if(questGiver && pQuest->GetQuestStartScript()!=0)
12689 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12691 // Some spells applied at quest activation
12692 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12693 if(saBounds.first != saBounds.second)
12695 uint32 zone = GetZoneId();
12696 uint32 area = GetAreaId();
12698 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12699 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12700 if( !HasAura(itr->second->spellId,0) )
12701 CastSpell(this,itr->second->spellId,true);
12704 UpdateForQuestsGO();
12707 void Player::CompleteQuest( uint32 quest_id )
12709 if( quest_id )
12711 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12713 uint16 log_slot = FindQuestSlot( quest_id );
12714 if( log_slot < MAX_QUEST_LOG_SIZE)
12715 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12717 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12719 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12720 RewardQuest(qInfo,0,this,false);
12721 else
12722 SendQuestComplete( quest_id );
12727 void Player::IncompleteQuest( uint32 quest_id )
12729 if( quest_id )
12731 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12733 uint16 log_slot = FindQuestSlot( quest_id );
12734 if( log_slot < MAX_QUEST_LOG_SIZE)
12735 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12739 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12741 uint32 quest_id = pQuest->GetQuestId();
12743 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12745 if ( pQuest->ReqItemId[i] )
12746 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12749 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12750 // SetTimedQuest( 0 );
12751 m_timedquests.erase(pQuest->GetQuestId());
12753 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12755 if( pQuest->RewChoiceItemId[reward] )
12757 ItemPosCountVec dest;
12758 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12760 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12761 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12766 if ( pQuest->GetRewItemsCount() > 0 )
12768 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12770 if( pQuest->RewItemId[i] )
12772 ItemPosCountVec dest;
12773 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12775 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12776 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12782 RewardReputation( pQuest );
12784 if( pQuest->GetRewSpellCast() > 0 )
12785 CastSpell( this, pQuest->GetRewSpellCast(), true);
12786 else if( pQuest->GetRewSpell() > 0)
12787 CastSpell( this, pQuest->GetRewSpell(), true);
12789 uint16 log_slot = FindQuestSlot( quest_id );
12790 if( log_slot < MAX_QUEST_LOG_SIZE)
12791 SetQuestSlot(log_slot,0);
12793 QuestStatusData& q_status = mQuestStatus[quest_id];
12795 // Not give XP in case already completed once repeatable quest
12796 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12798 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12799 GiveXP( XP , NULL );
12800 else
12802 int32 money = int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12803 ModifyMoney( money );
12804 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12807 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12808 if(pQuest->GetRewOrReqMoney())
12810 ModifyMoney( pQuest->GetRewOrReqMoney() );
12811 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12814 // honor reward
12815 if(pQuest->GetRewHonorableKills())
12816 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12818 // title reward
12819 if(pQuest->GetCharTitleId())
12821 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12822 SetTitle(titleEntry);
12825 if(pQuest->GetBonusTalents())
12827 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12828 InitTalentForLevel();
12831 // Send reward mail
12832 if(pQuest->GetRewMailTemplateId())
12834 MailMessageType mailType;
12835 uint32 senderGuidOrEntry;
12836 switch(questGiver->GetTypeId())
12838 case TYPEID_UNIT:
12839 mailType = MAIL_CREATURE;
12840 senderGuidOrEntry = questGiver->GetEntry();
12841 break;
12842 case TYPEID_GAMEOBJECT:
12843 mailType = MAIL_GAMEOBJECT;
12844 senderGuidOrEntry = questGiver->GetEntry();
12845 break;
12846 case TYPEID_ITEM:
12847 mailType = MAIL_ITEM;
12848 senderGuidOrEntry = questGiver->GetEntry();
12849 break;
12850 case TYPEID_PLAYER:
12851 mailType = MAIL_NORMAL;
12852 senderGuidOrEntry = questGiver->GetGUIDLow();
12853 break;
12854 default:
12855 mailType = MAIL_NORMAL;
12856 senderGuidOrEntry = GetGUIDLow();
12857 break;
12860 Loot questMailLoot;
12862 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12864 // fill mail
12865 MailItemsInfo mi; // item list preparing
12867 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12868 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12870 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12872 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12874 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12875 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12880 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12883 if(pQuest->IsDaily())
12885 SetDailyQuestStatus(quest_id);
12886 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12889 if ( !pQuest->IsRepeatable() )
12890 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12891 else
12892 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12894 q_status.m_rewarded = true;
12896 if(announce)
12897 SendQuestReward( pQuest, XP, questGiver );
12899 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12900 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12901 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12903 uint32 zone = 0;
12904 uint32 area = 0;
12906 // remove auras from spells with quest reward state limitations
12907 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12908 if(saEndBounds.first != saEndBounds.second)
12910 uint32 zone = GetZoneId();
12911 uint32 area = GetAreaId();
12913 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12914 if(!itr->second->IsFitToRequirements(this,zone,area))
12915 RemoveAurasDueToSpell(itr->second->spellId);
12918 // Some spells applied at quest reward
12919 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12920 if(saBounds.first != saBounds.second)
12922 if(!zone) zone = GetZoneId();
12923 if(!area) area = GetAreaId();
12925 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12926 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12927 if( !HasAura(itr->second->spellId,0) )
12928 CastSpell(this,itr->second->spellId,true);
12932 void Player::FailQuest( uint32 quest_id )
12934 if( quest_id )
12936 IncompleteQuest( quest_id );
12938 uint16 log_slot = FindQuestSlot( quest_id );
12939 if( log_slot < MAX_QUEST_LOG_SIZE)
12941 SetQuestSlotTimer(log_slot, 1 );
12942 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12944 SendQuestFailed( quest_id );
12948 void Player::FailTimedQuest( uint32 quest_id )
12950 if( quest_id )
12952 QuestStatusData& q_status = mQuestStatus[quest_id];
12954 q_status.m_timer = 0;
12955 if (q_status.uState != QUEST_NEW)
12956 q_status.uState = QUEST_CHANGED;
12958 IncompleteQuest( quest_id );
12960 uint16 log_slot = FindQuestSlot( quest_id );
12961 if( log_slot < MAX_QUEST_LOG_SIZE)
12963 SetQuestSlotTimer(log_slot, 1 );
12964 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12966 SendQuestTimerFailed( quest_id );
12970 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12972 int32 zoneOrSort = qInfo->GetZoneOrSort();
12973 int32 skillOrClass = qInfo->GetSkillOrClass();
12975 // skip zone zoneOrSort and 0 case skillOrClass
12976 if( zoneOrSort >= 0 && skillOrClass == 0 )
12977 return true;
12979 int32 questSort = -zoneOrSort;
12980 uint8 reqSortClass = ClassByQuestSort(questSort);
12982 // check class sort cases in zoneOrSort
12983 if( reqSortClass != 0 && getClass() != reqSortClass)
12985 if( msg )
12986 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12987 return false;
12990 // check class
12991 if( skillOrClass < 0 )
12993 uint8 reqClass = -int32(skillOrClass);
12994 if(getClass() != reqClass)
12996 if( msg )
12997 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12998 return false;
13001 // check skill
13002 else if( skillOrClass > 0 )
13004 uint32 reqSkill = skillOrClass;
13005 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13007 if( msg )
13008 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13009 return false;
13013 return true;
13016 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13018 if( getLevel() < qInfo->GetMinLevel() )
13020 if( msg )
13021 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13022 return false;
13024 return true;
13027 bool Player::SatisfyQuestLog( bool msg )
13029 // exist free slot
13030 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13031 return true;
13033 if( msg )
13035 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13036 GetSession()->SendPacket( &data );
13037 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13039 return false;
13042 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13044 // No previous quest (might be first quest in a series)
13045 if( qInfo->prevQuests.empty())
13046 return true;
13048 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13050 uint32 prevId = abs(*iter);
13052 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13053 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
13055 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13057 // If any of the positive previous quests completed, return true
13058 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13060 // skip one-from-all exclusive group
13061 if(qPrevInfo->GetExclusiveGroup() >= 0)
13062 return true;
13064 // each-from-all exclusive group ( < 0)
13065 // can be start if only all quests in prev quest exclusive group completed and rewarded
13066 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13067 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13069 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13071 for(; iter != end; ++iter)
13073 uint32 exclude_Id = iter->second;
13075 // skip checked quest id, only state of other quests in group is interesting
13076 if(exclude_Id == prevId)
13077 continue;
13079 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13081 // alternative quest from group also must be completed and rewarded(reported)
13082 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13084 if( msg )
13085 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13086 return false;
13089 return true;
13091 // If any of the negative previous quests active, return true
13092 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13093 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13095 // skip one-from-all exclusive group
13096 if(qPrevInfo->GetExclusiveGroup() >= 0)
13097 return true;
13099 // each-from-all exclusive group ( < 0)
13100 // can be start if only all quests in prev quest exclusive group active
13101 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13102 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13104 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13106 for(; iter != end; ++iter)
13108 uint32 exclude_Id = iter->second;
13110 // skip checked quest id, only state of other quests in group is interesting
13111 if(exclude_Id == prevId)
13112 continue;
13114 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13116 // alternative quest from group also must be active
13117 if( i_exstatus == mQuestStatus.end() ||
13118 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13119 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13121 if( msg )
13122 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13123 return false;
13126 return true;
13131 // Has only positive prev. quests in non-rewarded state
13132 // and negative prev. quests in non-active state
13133 if( msg )
13134 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13136 return false;
13139 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13141 uint32 reqraces = qInfo->GetRequiredRaces();
13142 if ( reqraces == 0 )
13143 return true;
13144 if( (reqraces & getRaceMask()) == 0 )
13146 if( msg )
13147 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13148 return false;
13150 return true;
13153 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13155 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13156 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13158 if( msg )
13159 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13160 return false;
13163 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13164 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13166 if( msg )
13167 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13168 return false;
13171 return true;
13174 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13176 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13177 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13179 if( msg )
13180 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13181 return false;
13183 return true;
13186 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
13188 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
13190 if( msg )
13191 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
13192 return false;
13194 return true;
13197 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13199 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13200 if(qInfo->GetExclusiveGroup() <= 0)
13201 return true;
13203 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13204 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13206 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13208 for(; iter != end; ++iter)
13210 uint32 exclude_Id = iter->second;
13212 // skip checked quest id, only state of other quests in group is interesting
13213 if(exclude_Id == qInfo->GetQuestId())
13214 continue;
13216 // not allow have daily quest if daily quest from exclusive group already recently completed
13217 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
13218 if( !SatisfyQuestDay(Nquest, false) )
13220 if( msg )
13221 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13222 return false;
13225 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13227 // alternative quest already started or completed
13228 if( i_exstatus != mQuestStatus.end()
13229 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13231 if( msg )
13232 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13233 return false;
13236 return true;
13239 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13241 if(!qInfo->GetNextQuestInChain())
13242 return true;
13244 // next quest in chain already started or completed
13245 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13246 if( itr != mQuestStatus.end()
13247 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13249 if( msg )
13250 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13251 return false;
13254 // check for all quests further up the chain
13255 // only necessary if there are quest chains with more than one quest that can be skipped
13256 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13257 return true;
13260 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13262 // No previous quest in chain
13263 if( qInfo->prevChainQuests.empty())
13264 return true;
13266 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13268 uint32 prevId = *iter;
13270 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
13272 if( i_prevstatus != mQuestStatus.end() )
13274 // If any of the previous quests in chain active, return false
13275 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13276 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13278 if( msg )
13279 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13280 return false;
13284 // check for all quests further down the chain
13285 // only necessary if there are quest chains with more than one quest that can be skipped
13286 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13287 // return false;
13290 // No previous quest in chain active
13291 return true;
13294 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13296 if(!qInfo->IsDaily())
13297 return true;
13299 bool have_slot = false;
13300 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13302 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13303 if(qInfo->GetQuestId()==id)
13304 return false;
13306 if(!id)
13307 have_slot = true;
13310 if(!have_slot)
13312 if( msg )
13313 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13314 return false;
13317 return true;
13320 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13322 uint32 srcitem = pQuest->GetSrcItemId();
13323 if( srcitem > 0 )
13325 uint32 count = pQuest->GetSrcItemCount();
13326 if( count <= 0 )
13327 count = 1;
13329 ItemPosCountVec dest;
13330 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13331 if( msg == EQUIP_ERR_OK )
13333 Item * item = StoreNewItem(dest, srcitem, true);
13334 SendNewItem(item, count, true, false);
13335 return true;
13337 // player already have max amount required item, just report success
13338 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13339 return true;
13340 else
13341 SendEquipError( msg, NULL, NULL );
13342 return false;
13345 return true;
13348 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13350 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13351 if( qInfo )
13353 uint32 srcitem = qInfo->GetSrcItemId();
13354 if( srcitem > 0 )
13356 uint32 count = qInfo->GetSrcItemCount();
13357 if( count <= 0 )
13358 count = 1;
13360 // exist one case when destroy source quest item not possible:
13361 // non un-equippable item (equipped non-empty bag, for example)
13362 uint8 res = CanUnequipItems(srcitem,count);
13363 if(res != EQUIP_ERR_OK)
13365 if(msg)
13366 SendEquipError( res, NULL, NULL );
13367 return false;
13370 DestroyItemCount(srcitem, count, true, true);
13373 return true;
13376 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13378 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13379 if( qInfo )
13381 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13382 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13383 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13384 && !qInfo->IsRepeatable() )
13385 return itr->second.m_rewarded;
13387 return false;
13389 return false;
13392 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13394 if( quest_id )
13396 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13397 if( itr != mQuestStatus.end() )
13398 return itr->second.m_status;
13400 return QUEST_STATUS_NONE;
13403 bool Player::CanShareQuest(uint32 quest_id) const
13405 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13406 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13408 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13409 if( itr != mQuestStatus.end() )
13410 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13412 return false;
13415 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13417 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13418 if( qInfo )
13420 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13422 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13423 m_timedquests.erase(qInfo->GetQuestId());
13426 QuestStatusData& q_status = mQuestStatus[quest_id];
13428 q_status.m_status = status;
13429 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13432 UpdateForQuestsGO();
13435 // not used in MaNGOS, but used in scripting code
13436 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13438 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13439 if( !qInfo )
13440 return 0;
13442 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13443 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13444 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13446 return 0;
13449 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13451 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13453 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13455 uint32 reqitemcount = pQuest->ReqItemCount[i];
13456 if( reqitemcount != 0 )
13458 uint32 quest_id = pQuest->GetQuestId();
13459 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13461 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13462 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13468 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13470 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13471 if ( GetQuestSlotQuestId(i) == quest_id )
13472 return i;
13474 return MAX_QUEST_LOG_SIZE;
13477 void Player::AreaExploredOrEventHappens( uint32 questId )
13479 if( questId )
13481 uint16 log_slot = FindQuestSlot( questId );
13482 if( log_slot < MAX_QUEST_LOG_SIZE)
13484 QuestStatusData& q_status = mQuestStatus[questId];
13486 if(!q_status.m_explored)
13488 q_status.m_explored = true;
13489 if (q_status.uState != QUEST_NEW)
13490 q_status.uState = QUEST_CHANGED;
13493 if( CanCompleteQuest( questId ) )
13494 CompleteQuest( questId );
13498 //not used in mangosd, function for external script library
13499 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13501 if( Group *pGroup = GetGroup() )
13503 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13505 Player *pGroupGuy = itr->getSource();
13507 // for any leave or dead (with not released body) group member at appropriate distance
13508 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13509 pGroupGuy->AreaExploredOrEventHappens(questId);
13512 else
13513 AreaExploredOrEventHappens(questId);
13516 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13518 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13520 uint32 questid = GetQuestSlotQuestId(i);
13521 if ( questid == 0 )
13522 continue;
13524 QuestStatusData& q_status = mQuestStatus[questid];
13526 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13527 continue;
13529 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13530 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13531 continue;
13533 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13535 uint32 reqitem = qInfo->ReqItemId[j];
13536 if ( reqitem == entry )
13538 uint32 reqitemcount = qInfo->ReqItemCount[j];
13539 uint32 curitemcount = q_status.m_itemcount[j];
13540 if ( curitemcount < reqitemcount )
13542 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13543 q_status.m_itemcount[j] += additemcount;
13544 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13546 SendQuestUpdateAddItem( qInfo, j, additemcount );
13548 if ( CanCompleteQuest( questid ) )
13549 CompleteQuest( questid );
13550 return;
13554 UpdateForQuestsGO();
13555 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13558 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13560 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13562 uint32 questid = GetQuestSlotQuestId(i);
13563 if(!questid)
13564 continue;
13565 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13566 if ( !qInfo )
13567 continue;
13568 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13569 continue;
13571 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13573 uint32 reqitem = qInfo->ReqItemId[j];
13574 if ( reqitem == entry )
13576 QuestStatusData& q_status = mQuestStatus[questid];
13578 uint32 reqitemcount = qInfo->ReqItemCount[j];
13579 uint32 curitemcount;
13580 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13581 curitemcount = q_status.m_itemcount[j];
13582 else
13583 curitemcount = GetItemCount(entry,true);
13584 if ( curitemcount < reqitemcount + count )
13586 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13587 q_status.m_itemcount[j] = curitemcount - remitemcount;
13588 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13590 IncompleteQuest( questid );
13592 return;
13596 UpdateForQuestsGO();
13599 void Player::KilledMonster( uint32 entry, uint64 guid )
13601 uint32 addkillcount = 1;
13602 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13603 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13605 uint32 questid = GetQuestSlotQuestId(i);
13606 if(!questid)
13607 continue;
13609 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13610 if( !qInfo )
13611 continue;
13612 // just if !ingroup || !noraidgroup || raidgroup
13613 QuestStatusData& q_status = mQuestStatus[questid];
13614 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13616 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13618 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13620 // skip GO activate objective or none
13621 if(qInfo->ReqCreatureOrGOId[j] <=0)
13622 continue;
13624 // skip Cast at creature objective
13625 if(qInfo->ReqSpell[j] !=0 )
13626 continue;
13628 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13630 if ( reqkill == entry )
13632 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13633 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13634 if ( curkillcount < reqkillcount )
13636 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13637 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13639 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13641 if ( CanCompleteQuest( questid ) )
13642 CompleteQuest( questid );
13644 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13645 continue;
13653 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13655 bool isCreature = IS_CREATURE_GUID(guid);
13657 uint32 addCastCount = 1;
13658 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13660 uint32 questid = GetQuestSlotQuestId(i);
13661 if(!questid)
13662 continue;
13664 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13665 if ( !qInfo )
13666 continue;
13668 QuestStatusData& q_status = mQuestStatus[questid];
13670 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13672 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13674 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13676 // skip kill creature objective (0) or wrong spell casts
13677 if(qInfo->ReqSpell[j] != spell_id )
13678 continue;
13680 uint32 reqTarget = 0;
13682 if(isCreature)
13684 // creature activate objectives
13685 if(qInfo->ReqCreatureOrGOId[j] > 0)
13686 // checked at quest_template loading
13687 reqTarget = qInfo->ReqCreatureOrGOId[j];
13689 else
13691 // GO activate objective
13692 if(qInfo->ReqCreatureOrGOId[j] < 0)
13693 // checked at quest_template loading
13694 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13697 // other not this creature/GO related objectives
13698 if( reqTarget != entry )
13699 continue;
13701 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13702 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13703 if ( curCastCount < reqCastCount )
13705 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13706 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13708 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13711 if ( CanCompleteQuest( questid ) )
13712 CompleteQuest( questid );
13714 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13715 break;
13722 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13724 uint32 addTalkCount = 1;
13725 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13727 uint32 questid = GetQuestSlotQuestId(i);
13728 if(!questid)
13729 continue;
13731 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13732 if ( !qInfo )
13733 continue;
13735 QuestStatusData& q_status = mQuestStatus[questid];
13737 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13739 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13741 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13743 // skip spell casts and Gameobject objectives
13744 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13745 continue;
13747 uint32 reqTarget = 0;
13749 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13750 // checked at quest_template loading
13751 reqTarget = qInfo->ReqCreatureOrGOId[j];
13752 else
13753 continue;
13755 if ( reqTarget == entry )
13757 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13758 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13759 if ( curTalkCount < reqTalkCount )
13761 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13762 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13764 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13766 if ( CanCompleteQuest( questid ) )
13767 CompleteQuest( questid );
13769 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13770 continue;
13778 void Player::MoneyChanged( uint32 count )
13780 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13782 uint32 questid = GetQuestSlotQuestId(i);
13783 if (!questid)
13784 continue;
13786 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13787 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13789 QuestStatusData& q_status = mQuestStatus[questid];
13791 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13793 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13795 if ( CanCompleteQuest( questid ) )
13796 CompleteQuest( questid );
13799 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13801 if(int32(count) < -qInfo->GetRewOrReqMoney())
13802 IncompleteQuest( questid );
13808 bool Player::HasQuestForItem( uint32 itemid ) const
13810 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13812 uint32 questid = GetQuestSlotQuestId(i);
13813 if ( questid == 0 )
13814 continue;
13816 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13817 if(qs_itr == mQuestStatus.end())
13818 continue;
13820 QuestStatusData const& q_status = qs_itr->second;
13822 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13824 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13825 if(!qinfo)
13826 continue;
13828 // hide quest if player is in raid-group and quest is no raid quest
13829 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13830 continue;
13832 // There should be no mixed ReqItem/ReqSource drop
13833 // This part for ReqItem drop
13834 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13836 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13837 return true;
13839 // This part - for ReqSource
13840 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13842 // examined item is a source item
13843 if (qinfo->ReqSourceId[j] == itemid)
13845 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13847 // 'unique' item
13848 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13849 return true;
13851 // allows custom amount drop when not 0
13852 if (qinfo->ReqSourceCount[j])
13854 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13855 return true;
13856 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13857 return true;
13862 return false;
13865 void Player::SendQuestComplete( uint32 quest_id )
13867 if( quest_id )
13869 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13870 data << uint32(quest_id);
13871 GetSession()->SendPacket( &data );
13872 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13876 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13878 uint32 questid = pQuest->GetQuestId();
13879 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13880 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13881 data << uint32(questid);
13883 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13885 data << uint32(XP);
13886 data << uint32(pQuest->GetRewOrReqMoney());
13888 else
13890 data << uint32(0);
13891 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13894 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13895 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13896 GetSession()->SendPacket( &data );
13898 if (pQuest->GetQuestCompleteScript() != 0)
13899 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13902 void Player::SendQuestFailed( uint32 quest_id )
13904 if( quest_id )
13906 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13907 data << quest_id;
13908 data << uint32(0); // failed reason (4 for inventory is full)
13909 GetSession()->SendPacket( &data );
13910 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13914 void Player::SendQuestTimerFailed( uint32 quest_id )
13916 if( quest_id )
13918 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13919 data << quest_id;
13920 GetSession()->SendPacket( &data );
13921 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13925 void Player::SendCanTakeQuestResponse( uint32 msg )
13927 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13928 data << uint32(msg);
13929 GetSession()->SendPacket( &data );
13930 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13933 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13935 if( pPlayer )
13937 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13938 data << uint64(pPlayer->GetGUID());
13939 data << uint8(msg); // valid values: 0-8
13940 GetSession()->SendPacket( &data );
13941 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13945 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13947 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13948 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13949 //data << pQuest->ReqItemId[item_idx];
13950 //data << count;
13951 GetSession()->SendPacket( &data );
13954 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13956 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13958 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13959 if (entry < 0)
13960 // client expected gameobject template id in form (id|0x80000000)
13961 entry = (-entry) | 0x80000000;
13963 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13964 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13965 data << uint32(pQuest->GetQuestId());
13966 data << uint32(entry);
13967 data << uint32(old_count + add_count);
13968 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13969 data << uint64(guid);
13970 GetSession()->SendPacket(&data);
13972 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13973 if( log_slot < MAX_QUEST_LOG_SIZE)
13974 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13977 /*********************************************************/
13978 /*** LOAD SYSTEM ***/
13979 /*********************************************************/
13981 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13983 bool delete_result = true;
13984 if(!result)
13986 // 0 1 2 3 4 5 6 7 8 9
13987 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13988 if(!result) return false;
13990 else delete_result = false;
13992 Field *fields = result->Fetch();
13994 if(!LoadValues( fields[1].GetString()))
13996 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13997 if(delete_result) delete result;
13998 return false;
14001 // overwrite possible wrong/corrupted guid
14002 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14004 m_name = fields[2].GetCppString();
14006 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
14007 SetMapId(fields[6].GetUInt32());
14008 // the instance id is not needed at character enum
14010 m_Played_time[0] = fields[7].GetUInt32();
14011 m_Played_time[1] = fields[8].GetUInt32();
14013 m_atLoginFlags = fields[9].GetUInt32();
14015 // I don't see these used anywhere ..
14016 /*_LoadGroup();
14018 _LoadBoundInstances();*/
14020 if (delete_result) delete result;
14022 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
14023 m_items[i] = NULL;
14025 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14026 m_deathState = DEAD;
14028 return true;
14031 void Player::_LoadDeclinedNames(QueryResult* result)
14033 if(!result)
14034 return;
14036 if(m_declinedname)
14037 delete m_declinedname;
14039 m_declinedname = new DeclinedName;
14040 Field *fields = result->Fetch();
14041 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14042 m_declinedname->name[i] = fields[i].GetCppString();
14044 delete result;
14047 void Player::_LoadArenaTeamInfo(QueryResult *result)
14049 // arenateamid, played_week, played_season, personal_rating
14050 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
14051 if (!result)
14052 return;
14056 Field *fields = result->Fetch();
14058 uint32 arenateamid = fields[0].GetUInt32();
14059 uint32 played_week = fields[1].GetUInt32();
14060 uint32 played_season = fields[2].GetUInt32();
14061 uint32 personal_rating = fields[3].GetUInt32();
14063 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
14064 if(!aTeam)
14066 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
14067 continue;
14069 uint8 arenaSlot = aTeam->GetSlot();
14071 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
14072 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14073 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
14074 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
14075 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
14076 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
14078 }while (result->NextRow());
14079 delete result;
14082 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14084 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14085 if(!result)
14086 return false;
14088 Field *fields = result->Fetch();
14090 x = fields[0].GetFloat();
14091 y = fields[1].GetFloat();
14092 z = fields[2].GetFloat();
14093 o = fields[3].GetFloat();
14094 mapid = fields[4].GetUInt32();
14095 in_flight = !fields[5].GetCppString().empty();
14097 delete result;
14098 return true;
14101 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14103 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14104 if( !result )
14105 return false;
14107 Field *fields = result->Fetch();
14109 data = StrSplit(fields[0].GetCppString(), " ");
14111 delete result;
14113 return true;
14116 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14118 if(index >= data.size())
14119 return 0;
14121 return (uint32)atoi(data[index].c_str());
14124 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14126 float result;
14127 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14128 memcpy(&result, &temp, sizeof(result));
14130 return result;
14133 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14135 Tokens data;
14136 if(!LoadValuesArrayFromDB(data,guid))
14137 return 0;
14139 return GetUInt32ValueFromArray(data,index);
14142 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14144 float result;
14145 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14146 memcpy(&result, &temp, sizeof(result));
14148 return result;
14151 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14153 //// 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
14154 //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);
14155 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14157 if(!result)
14159 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14160 return false;
14163 Field *fields = result->Fetch();
14165 uint32 dbAccountId = fields[1].GetUInt32();
14167 // check if the character's account in the db and the logged in account match.
14168 // player should be able to load/delete character only with correct account!
14169 if( dbAccountId != GetSession()->GetAccountId() )
14171 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14172 delete result;
14173 return false;
14176 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14178 m_name = fields[3].GetCppString();
14180 // check name limitations
14181 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
14183 delete result;
14184 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14185 return false;
14188 if(!LoadValues( fields[2].GetString()))
14190 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
14191 delete result;
14192 return false;
14195 // overwrite possible wrong/corrupted guid
14196 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14198 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14199 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14201 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
14202 SetVisibleItemSlot(slot,NULL);
14204 if (m_items[slot])
14206 delete m_items[slot];
14207 m_items[slot] = NULL;
14211 // update money limits
14212 if(GetMoney() > MAX_MONEY_AMOUNT)
14213 SetMoney(MAX_MONEY_AMOUNT);
14215 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14216 outDebugValues();
14218 m_race = fields[4].GetUInt8();
14219 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14220 //Other way is to saves m_team into characters table.
14221 setFactionForRace(m_race);
14222 SetCharm(0);
14224 m_class = fields[5].GetUInt8();
14226 // load home bind and check in same time class/race pair, it used later for restore broken positions
14227 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14228 return false;
14230 InitPrimaryProffesions(); // to max set before any spell loaded
14232 // init saved position, and fix it later if problematic
14233 uint32 transGUID = fields[24].GetUInt32();
14234 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
14235 SetMapId(fields[9].GetUInt32());
14236 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
14238 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14240 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14242 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
14243 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14244 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14246 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14248 // check arena teams integrity
14249 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14251 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14252 if(!arena_team_id)
14253 continue;
14255 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
14256 if(at->HaveMember(GetGUID()))
14257 continue;
14259 // arena team not exist or not member, cleanup fields
14260 for(int j =0; j < 6; ++j)
14261 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
14264 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14266 if(!IsPositionValid())
14268 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());
14269 RelocateToHomebind();
14271 transGUID = 0;
14273 m_movementInfo.t_x = 0.0f;
14274 m_movementInfo.t_y = 0.0f;
14275 m_movementInfo.t_z = 0.0f;
14276 m_movementInfo.t_o = 0.0f;
14279 uint32 bgid = fields[34].GetUInt32();
14280 uint32 bgteam = fields[35].GetUInt32();
14282 if(bgid) //saved in BattleGround
14284 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14286 // check entry point and fix to homebind if need
14287 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14288 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14289 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14291 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14293 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14295 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14296 uint32 queueSlot = AddBattleGroundQueueId(bgQueueTypeId);
14298 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14299 SetBGTeam(bgteam);
14301 //join player to battleground group
14302 currentBg->PlayerRelogin(this);
14303 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14305 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14307 else
14309 Relocate(GetBattleGroundEntryPoint());
14310 //RemoveArenaAuras(true);
14313 else
14315 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14316 // if server restart after player save in BG or area
14317 // player can have current coordinates in to BG/Arean map, fix this
14318 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14320 // return to BG master
14321 SetMapId(fields[36].GetUInt32());
14322 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14324 // check entry point and fix to homebind if need
14325 mapEntry = sMapStore.LookupEntry(GetMapId());
14326 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14327 RelocateToHomebind();
14331 if (transGUID != 0)
14333 m_movementInfo.t_x = fields[20].GetFloat();
14334 m_movementInfo.t_y = fields[21].GetFloat();
14335 m_movementInfo.t_z = fields[22].GetFloat();
14336 m_movementInfo.t_o = fields[23].GetFloat();
14338 if( !MaNGOS::IsValidMapCoord(
14339 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14340 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14341 // transport size limited
14342 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14344 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14345 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14346 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14348 RelocateToHomebind();
14350 m_movementInfo.t_x = 0.0f;
14351 m_movementInfo.t_y = 0.0f;
14352 m_movementInfo.t_z = 0.0f;
14353 m_movementInfo.t_o = 0.0f;
14355 transGUID = 0;
14359 if (transGUID != 0)
14361 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14363 if( (*iter)->GetGUIDLow() == transGUID)
14365 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14366 // client without expansion support
14367 if(GetSession()->Expansion() < transMapEntry->Expansion())
14369 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14370 break;
14373 m_transport = *iter;
14374 m_transport->AddPassenger(this);
14375 SetMapId(m_transport->GetMapId());
14376 break;
14380 if(!m_transport)
14382 sLog.outError("ERROR: Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14383 guid,transGUID);
14385 RelocateToHomebind();
14387 m_movementInfo.t_x = 0.0f;
14388 m_movementInfo.t_y = 0.0f;
14389 m_movementInfo.t_z = 0.0f;
14390 m_movementInfo.t_o = 0.0f;
14392 transGUID = 0;
14395 else // not transport case
14397 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14398 // client without expansion support
14399 if(GetSession()->Expansion() < mapEntry->Expansion())
14401 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14402 RelocateToHomebind();
14406 // NOW player must have valid map
14407 // load the player's map here if it's not already loaded
14408 Map *map = GetMap();
14410 // since the player may not be bound to the map yet, make sure subsequent
14411 // getmap calls won't create new maps
14412 SetInstanceId(map->GetInstanceId());
14414 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14415 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14417 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14418 if(at)
14419 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14420 else
14421 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());
14424 SaveRecallPosition();
14426 time_t now = time(NULL);
14427 time_t logoutTime = time_t(fields[16].GetUInt64());
14429 // since last logout (in seconds)
14430 uint64 time_diff = uint64(now - logoutTime);
14432 // set value, including drunk invisibility detection
14433 // calculate sobering. after 15 minutes logged out, the player will be sober again
14434 float soberFactor;
14435 if(time_diff > 15*MINUTE)
14436 soberFactor = 0;
14437 else
14438 soberFactor = 1-time_diff/(15.0f*MINUTE);
14439 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14440 SetDrunkValue(newDrunkenValue);
14442 m_rest_bonus = fields[15].GetFloat();
14443 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14444 float bubble0 = 0.031;
14445 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14446 float bubble1 = 0.125;
14448 if((int32)fields[16].GetUInt32() > 0)
14450 float bubble = fields[17].GetUInt32() > 0
14451 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14452 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14454 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14457 m_cinematic = fields[12].GetUInt32();
14458 m_Played_time[0]= fields[13].GetUInt32();
14459 m_Played_time[1]= fields[14].GetUInt32();
14461 m_resetTalentsCost = fields[18].GetUInt32();
14462 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14464 // reserve some flags
14465 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14467 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14468 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14470 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14472 uint32 extraflags = fields[25].GetUInt32();
14474 m_stableSlots = fields[26].GetUInt32();
14475 if(m_stableSlots > 4)
14477 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
14478 m_stableSlots = 4;
14481 m_atLoginFlags = fields[27].GetUInt32();
14483 // Honor system
14484 // Update Honor kills data
14485 m_lastHonorUpdateTime = logoutTime;
14486 UpdateHonorFields();
14488 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14489 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14490 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14492 std::string taxi_nodes = fields[31].GetCppString();
14494 delete result;
14496 // clear channel spell data (if saved at channel spell casting)
14497 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14498 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14500 // clear charm/summon related fields
14501 SetCharm(NULL);
14502 SetPet(NULL);
14503 SetCharmerGUID(0);
14504 SetOwnerGUID(0);
14505 SetCreatorGUID(0);
14507 // reset some aura modifiers before aura apply
14508 SetFarSightGUID(0);
14509 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14510 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14512 _LoadSkills();
14514 // make sure the unit is considered out of combat for proper loading
14515 ClearInCombat();
14517 // make sure the unit is considered not in duel for proper loading
14518 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14519 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14521 // remember loaded power/health values to restore after stats initialization and modifier applying
14522 uint32 savedHealth = GetHealth();
14523 uint32 savedPower[MAX_POWERS];
14524 for(uint32 i = 0; i < MAX_POWERS; ++i)
14525 savedPower[i] = GetPower(Powers(i));
14527 // reset stats before loading any modifiers
14528 InitStatsForLevel();
14529 InitTaxiNodesForLevel();
14530 InitGlyphsForLevel();
14531 InitRunes();
14533 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14535 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14536 //_LoadMail();
14538 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14539 _LoadGlyphAuras();
14541 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14542 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14543 m_deathState = DEAD;
14545 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14547 // after spell load, learn rewarded spell if need also
14548 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14549 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14551 // after spell and quest load
14552 InitTalentForLevel();
14553 learnDefaultSpells();
14555 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14557 // must be before inventory (some items required reputation check)
14558 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14560 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14562 // update items with duration and realtime
14563 UpdateItemDuration(time_diff, true);
14565 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14567 // unread mails and next delivery time, actual mails not loaded
14568 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14570 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14572 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14573 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14574 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14576 if(!HasTitle(curTitle))
14577 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14580 // Not finish taxi flight path
14581 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14583 // problems with taxi path loading
14584 TaxiNodesEntry const* nodeEntry = NULL;
14585 if(uint32 node_id = m_taxi.GetTaxiSource())
14586 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14588 if(!nodeEntry) // don't know taxi start node, to homebind
14590 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14591 RelocateToHomebind();
14592 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14594 else // have start node, to it
14596 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14597 SetMapId(nodeEntry->map_id);
14598 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14599 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14601 m_taxi.ClearTaxiDestinations();
14603 else if(uint32 node_id = m_taxi.GetTaxiSource())
14605 // save source node as recall coord to prevent recall and fall from sky
14606 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14607 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14608 m_recallMap = nodeEntry->map_id;
14609 m_recallX = nodeEntry->x;
14610 m_recallY = nodeEntry->y;
14611 m_recallZ = nodeEntry->z;
14613 // flight will started later
14616 // has to be called after last Relocate() in Player::LoadFromDB
14617 SetFallInformation(0, GetPositionZ());
14619 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14621 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14622 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14623 if(!isAlive())
14624 RemoveAllAurasOnDeath();
14626 //apply all stat bonuses from items and auras
14627 SetCanModifyStats(true);
14628 UpdateAllStats();
14630 // restore remembered power/health values (but not more max values)
14631 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14632 for(uint32 i = 0; i < MAX_POWERS; ++i)
14633 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14635 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14636 outDebugValues();
14638 // GM state
14639 if(GetSession()->GetSecurity() > SEC_PLAYER)
14641 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14643 default:
14644 case 0: break; // disable
14645 case 1: SetGameMaster(true); break; // enable
14646 case 2: // save state
14647 if(extraflags & PLAYER_EXTRA_GM_ON)
14648 SetGameMaster(true);
14649 break;
14652 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14654 default:
14655 case 0: SetGMVisible(false); break; // invisible
14656 case 1: break; // visible
14657 case 2: // save state
14658 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14659 SetGMVisible(false);
14660 break;
14663 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14665 default:
14666 case 0: break; // disable
14667 case 1: SetAcceptTicket(true); break; // enable
14668 case 2: // save state
14669 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14670 SetAcceptTicket(true);
14671 break;
14674 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14676 default:
14677 case 0: break; // disable
14678 case 1: SetGMChat(true); break; // enable
14679 case 2: // save state
14680 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14681 SetGMChat(true);
14682 break;
14685 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14687 default:
14688 case 0: break; // disable
14689 case 1: SetAcceptWhispers(true); break; // enable
14690 case 2: // save state
14691 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14692 SetAcceptWhispers(true);
14693 break;
14697 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14699 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14700 m_achievementMgr.CheckAllAchievementCriteria();
14701 return true;
14704 bool Player::isAllowedToLoot(Creature* creature)
14706 if(Player* recipient = creature->GetLootRecipient())
14708 if (recipient == this)
14709 return true;
14710 if( Group* otherGroup = recipient->GetGroup())
14712 Group* thisGroup = GetGroup();
14713 if(!thisGroup)
14714 return false;
14715 return thisGroup == otherGroup;
14717 return false;
14719 else
14720 // prevent other players from looting if the recipient got disconnected
14721 return !creature->hasLootRecipient();
14724 void Player::_LoadActions(QueryResult *result)
14726 m_actionButtons.clear();
14728 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14730 if(result)
14734 Field *fields = result->Fetch();
14736 uint8 button = fields[0].GetUInt8();
14738 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14740 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14742 while( result->NextRow() );
14744 delete result;
14748 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14750 m_Auras.clear();
14751 for (int i = 0; i < TOTAL_AURAS; i++)
14752 m_modAuras[i].clear();
14754 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14756 if(result)
14760 Field *fields = result->Fetch();
14761 uint64 caster_guid = fields[0].GetUInt64();
14762 uint32 spellid = fields[1].GetUInt32();
14763 uint32 effindex = fields[2].GetUInt32();
14764 uint32 stackcount = fields[3].GetUInt32();
14765 int32 damage = (int32)fields[4].GetUInt32();
14766 int32 maxduration = (int32)fields[5].GetUInt32();
14767 int32 remaintime = (int32)fields[6].GetUInt32();
14768 int32 remaincharges = (int32)fields[7].GetUInt32();
14770 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14771 if(!spellproto)
14773 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14774 continue;
14777 if(effindex >= 3)
14779 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14780 continue;
14783 // negative effects should continue counting down after logout
14784 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14786 if(remaintime <= int32(timediff))
14787 continue;
14789 remaintime -= timediff;
14792 // prevent wrong values of remaincharges
14793 if(spellproto->procCharges)
14795 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14796 remaincharges = spellproto->procCharges;
14798 else
14799 remaincharges = 0;
14801 //do not load single target auras (unless they were cast by the player)
14802 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14803 continue;
14805 for(uint32 i=0; i<stackcount; i++)
14807 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14808 if(!damage)
14809 damage = aura->GetModifier()->m_amount;
14810 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14811 AddAura(aura);
14812 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14815 while( result->NextRow() );
14817 delete result;
14820 if(m_class == CLASS_WARRIOR)
14821 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14824 void Player::_LoadGlyphAuras()
14826 for (uint8 i = 0; i <= MAX_GLYPH_SLOT_INDEX; ++i)
14828 if (uint32 glyph = GetGlyph(i))
14830 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14832 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14834 if(gp->TypeFlags == gs->TypeFlags)
14836 CastSpell(this, gp->SpellId, true);
14837 continue;
14839 else
14840 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14842 else
14843 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14845 else
14846 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14848 // On any error remove glyph
14849 SetGlyph(i, 0);
14854 void Player::LoadCorpse()
14856 if( isAlive() )
14858 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14860 else
14862 if(Corpse *corpse = GetCorpse())
14864 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14866 else
14868 //Prevent Dead Player login without corpse
14869 ResurrectPlayer(0.5f);
14874 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14876 //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());
14877 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14878 //NOTE: the "order by `bag`" is important because it makes sure
14879 //the bagMap is filled before items in the bags are loaded
14880 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14881 //expected to be equipped before offhand items (TODO: fixme)
14883 uint32 zone = GetZoneId();
14885 if (result)
14887 std::list<Item*> problematicItems;
14889 // prevent items from being added to the queue when stored
14890 m_itemUpdateQueueBlocked = true;
14893 Field *fields = result->Fetch();
14894 uint32 bag_guid = fields[1].GetUInt32();
14895 uint8 slot = fields[2].GetUInt8();
14896 uint32 item_guid = fields[3].GetUInt32();
14897 uint32 item_id = fields[4].GetUInt32();
14899 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14901 if(!proto)
14903 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14904 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14905 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14906 continue;
14909 Item *item = NewItemOrBag(proto);
14911 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14913 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14914 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14915 item->FSetState(ITEM_REMOVED);
14916 item->SaveToDB(); // it also deletes item object !
14917 continue;
14920 // not allow have in alive state item limited to another map/zone
14921 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14923 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14924 item->FSetState(ITEM_REMOVED);
14925 item->SaveToDB(); // it also deletes item object !
14926 continue;
14929 // "Conjured items disappear if you are logged out for more than 15 minutes"
14930 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14932 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14933 item->FSetState(ITEM_REMOVED);
14934 item->SaveToDB(); // it also deletes item object !
14935 continue;
14938 bool success = true;
14940 if (!bag_guid)
14942 // the item is not in a bag
14943 item->SetContainer( NULL );
14944 item->SetSlot(slot);
14946 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14948 ItemPosCountVec dest;
14949 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14950 item = StoreItem(dest, item, true);
14951 else
14952 success = false;
14954 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14956 uint16 dest;
14957 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14958 QuickEquipItem(dest, item);
14959 else
14960 success = false;
14962 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14964 ItemPosCountVec dest;
14965 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14966 item = BankItem(dest, item, true);
14967 else
14968 success = false;
14971 if(success)
14973 // store bags that may contain items in them
14974 if(item->IsBag() && IsBagPos(item->GetPos()))
14975 bagMap[item_guid] = (Bag*)item;
14978 else
14980 item->SetSlot(NULL_SLOT);
14981 // the item is in a bag, find the bag
14982 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14983 if(itr != bagMap.end())
14984 itr->second->StoreItem(slot, item, true );
14985 else
14986 success = false;
14989 // item's state may have changed after stored
14990 if (success)
14991 item->SetState(ITEM_UNCHANGED, this);
14992 else
14994 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);
14995 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14996 problematicItems.push_back(item);
14998 } while (result->NextRow());
15000 delete result;
15001 m_itemUpdateQueueBlocked = false;
15003 // send by mail problematic items
15004 while(!problematicItems.empty())
15006 // fill mail
15007 MailItemsInfo mi; // item list preparing
15009 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15011 Item* item = problematicItems.front();
15012 problematicItems.pop_front();
15014 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
15017 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15019 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
15022 //if(isAlive())
15023 _ApplyAllItemMods();
15026 // load mailed item which should receive current player
15027 void Player::_LoadMailedItems(Mail *mail)
15029 // data needs to be at first place for Item::LoadFromDB
15030 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);
15031 if(!result)
15032 return;
15036 Field *fields = result->Fetch();
15037 uint32 item_guid_low = fields[1].GetUInt32();
15038 uint32 item_template = fields[2].GetUInt32();
15040 mail->AddItem(item_guid_low, item_template);
15042 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
15044 if(!proto)
15046 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);
15047 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15048 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15049 continue;
15052 Item *item = NewItemOrBag(proto);
15054 if(!item->LoadFromDB(item_guid_low, 0, result))
15056 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15057 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15058 item->FSetState(ITEM_REMOVED);
15059 item->SaveToDB(); // it also deletes item object !
15060 continue;
15063 AddMItem(item);
15064 } while (result->NextRow());
15066 delete result;
15069 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15071 //set a count of unread mails
15072 //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);
15073 if (resultUnread)
15075 Field *fieldMail = resultUnread->Fetch();
15076 unReadMails = fieldMail[0].GetUInt8();
15077 delete resultUnread;
15080 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15081 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15082 if (resultDelivery)
15084 Field *fieldMail = resultDelivery->Fetch();
15085 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15086 delete resultDelivery;
15090 void Player::_LoadMail()
15092 m_mail.clear();
15093 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15094 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());
15095 if(result)
15099 Field *fields = result->Fetch();
15100 Mail *m = new Mail;
15101 m->messageID = fields[0].GetUInt32();
15102 m->messageType = fields[1].GetUInt8();
15103 m->sender = fields[2].GetUInt32();
15104 m->receiver = fields[3].GetUInt32();
15105 m->subject = fields[4].GetCppString();
15106 m->itemTextId = fields[5].GetUInt32();
15107 bool has_items = fields[6].GetBool();
15108 m->expire_time = (time_t)fields[7].GetUInt64();
15109 m->deliver_time = (time_t)fields[8].GetUInt64();
15110 m->money = fields[9].GetUInt32();
15111 m->COD = fields[10].GetUInt32();
15112 m->checked = fields[11].GetUInt32();
15113 m->stationery = fields[12].GetUInt8();
15114 m->mailTemplateId = fields[13].GetInt16();
15116 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15118 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15119 m->mailTemplateId = 0;
15122 m->state = MAIL_STATE_UNCHANGED;
15124 if (has_items)
15125 _LoadMailedItems(m);
15127 m_mail.push_back(m);
15128 } while( result->NextRow() );
15129 delete result;
15131 m_mailsLoaded = true;
15134 void Player::LoadPet()
15136 //fixme: the pet should still be loaded if the player is not in world
15137 // just not added to the map
15138 if(IsInWorld())
15140 Pet *pet = new Pet;
15141 if(!pet->LoadPetFromDB(this,0,0,true))
15142 delete pet;
15146 void Player::_LoadQuestStatus(QueryResult *result)
15148 mQuestStatus.clear();
15150 uint32 slot = 0;
15152 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15153 //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());
15155 if(result)
15159 Field *fields = result->Fetch();
15161 uint32 quest_id = fields[0].GetUInt32();
15162 // used to be new, no delete?
15163 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15164 if( pQuest )
15166 // find or create
15167 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15169 uint32 qstatus = fields[1].GetUInt32();
15170 if(qstatus < MAX_QUEST_STATUS)
15171 questStatusData.m_status = QuestStatus(qstatus);
15172 else
15174 questStatusData.m_status = QUEST_STATUS_NONE;
15175 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15178 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15179 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15181 time_t quest_time = time_t(fields[4].GetUInt64());
15183 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15185 AddTimedQuest( quest_id );
15187 if (quest_time <= sWorld.GetGameTime())
15188 questStatusData.m_timer = 1;
15189 else
15190 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15192 else
15193 quest_time = 0;
15195 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15196 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15197 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15198 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15199 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15200 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15201 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15202 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15204 questStatusData.uState = QUEST_UNCHANGED;
15206 // add to quest log
15207 if( slot < MAX_QUEST_LOG_SIZE &&
15208 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
15209 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
15210 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
15212 SetQuestSlot(slot,quest_id,quest_time);
15214 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
15215 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
15217 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15218 if(questStatusData.m_creatureOrGOcount[idx])
15219 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
15221 ++slot;
15224 if(questStatusData.m_rewarded)
15226 // learn rewarded spell if unknown
15227 learnQuestRewardedSpells(pQuest);
15229 // set rewarded title if any
15230 if(pQuest->GetCharTitleId())
15232 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15233 SetTitle(titleEntry);
15236 if(pQuest->GetBonusTalents())
15237 m_questRewardTalentCount+=pQuest->GetBonusTalents();
15240 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15243 while( result->NextRow() );
15245 delete result;
15248 // clear quest log tail
15249 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15250 SetQuestSlot(i,0);
15253 void Player::_LoadDailyQuestStatus(QueryResult *result)
15255 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15256 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15258 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15260 if(result)
15262 uint32 quest_daily_idx = 0;
15266 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15268 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15269 break;
15272 Field *fields = result->Fetch();
15274 uint32 quest_id = fields[0].GetUInt32();
15276 // save _any_ from daily quest times (it must be after last reset anyway)
15277 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15279 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15280 if( !pQuest )
15281 continue;
15283 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15284 ++quest_daily_idx;
15286 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15288 while( result->NextRow() );
15290 delete result;
15293 m_DailyQuestChanged = false;
15296 void Player::_LoadReputation(QueryResult *result)
15298 m_factions.clear();
15300 // Set initial reputations (so everything is nifty before DB data load)
15301 SetInitialFactions();
15303 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15305 if(result)
15309 Field *fields = result->Fetch();
15311 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
15312 if( factionEntry && (factionEntry->reputationListID >= 0))
15314 FactionState* faction = &m_factions[factionEntry->reputationListID];
15316 // update standing to current
15317 faction->Standing = int32(fields[1].GetUInt32());
15319 uint32 dbFactionFlags = fields[2].GetUInt32();
15321 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
15322 SetFactionVisible(faction); // have internal checks for forced invisibility
15324 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
15325 SetFactionInactive(faction,true); // have internal checks for visibility requirement
15327 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
15328 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15329 else // DB not at war
15331 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15332 if( faction->Flags & FACTION_FLAG_VISIBLE )
15333 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15336 // set atWar for hostile
15337 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
15338 SetFactionAtWar(faction,true);
15340 // reset changed flag if values similar to saved in DB
15341 if(faction->Flags==dbFactionFlags)
15342 faction->Changed = false;
15345 while( result->NextRow() );
15347 delete result;
15351 void Player::_LoadSpells(QueryResult *result)
15353 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15355 if(result)
15359 Field *fields = result->Fetch();
15361 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15363 while( result->NextRow() );
15365 delete result;
15369 void Player::_LoadTutorials(QueryResult *result)
15371 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15373 if(result)
15377 Field *fields = result->Fetch();
15379 for (int iI=0; iI<8; iI++)
15380 m_Tutorials[iI] = fields[iI].GetUInt32();
15382 while( result->NextRow() );
15384 delete result;
15387 m_TutorialsChanged = false;
15390 void Player::_LoadGroup(QueryResult *result)
15392 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15393 if(result)
15395 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15396 delete result;
15397 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15398 if(group)
15400 uint8 subgroup = group->GetMemberGroup(GetGUID());
15401 SetGroup(group, subgroup);
15402 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15404 // the group leader may change the instance difficulty while the player is offline
15405 SetDifficulty(group->GetDifficulty());
15411 void Player::_LoadBoundInstances(QueryResult *result)
15413 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15414 m_boundInstances[i].clear();
15416 Group *group = GetGroup();
15418 //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));
15419 if(result)
15423 Field *fields = result->Fetch();
15424 bool perm = fields[1].GetBool();
15425 uint32 mapId = fields[2].GetUInt32();
15426 uint32 instanceId = fields[0].GetUInt32();
15427 uint8 difficulty = fields[3].GetUInt8();
15428 time_t resetTime = (time_t)fields[4].GetUInt64();
15429 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15430 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15431 // and in that case it is not used
15433 if(!perm && group)
15435 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);
15436 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15437 continue;
15440 // since non permanent binds are always solo bind, they can always be reset
15441 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15442 if(save) BindToInstance(save, perm, true);
15443 } while(result->NextRow());
15444 delete result;
15448 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15450 // some instances only have one difficulty
15451 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15452 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15454 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15455 if(itr != m_boundInstances[difficulty].end())
15456 return &itr->second;
15457 else
15458 return NULL;
15461 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15463 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15464 UnbindInstance(itr, difficulty, unload);
15467 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15469 if(itr != m_boundInstances[difficulty].end())
15471 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15472 itr->second.save->RemovePlayer(this); // save can become invalid
15473 m_boundInstances[difficulty].erase(itr++);
15477 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15479 if(save)
15481 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15482 if(bind.save)
15484 // update the save when the group kills a boss
15485 if(permanent != bind.perm || save != bind.save)
15486 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());
15488 else
15489 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15491 if(bind.save != save)
15493 if(bind.save) bind.save->RemovePlayer(this);
15494 save->AddPlayer(this);
15497 if(permanent) save->SetCanReset(false);
15499 bind.save = save;
15500 bind.perm = permanent;
15501 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());
15502 return &bind;
15504 else
15505 return NULL;
15508 void Player::SendRaidInfo()
15510 uint32 counter = 0;
15512 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15514 size_t p_counter = data.wpos();
15515 data << uint32(counter); // placeholder
15517 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15519 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15521 if(itr->second.perm)
15523 InstanceSave *save = itr->second.save;
15524 data << uint32(save->GetMapId());
15525 data << uint32(save->GetResetTime() - time(NULL));
15526 data << uint32(save->GetInstanceId());
15527 data << uint32(save->GetDifficulty());
15528 ++counter;
15532 data.put<uint32>(p_counter,counter);
15533 GetSession()->SendPacket(&data);
15537 - called on every successful teleportation to a map
15539 void Player::SendSavedInstances()
15541 bool hasBeenSaved = false;
15542 WorldPacket data;
15544 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15546 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15548 if(itr->second.perm) // only permanent binds are sent
15550 hasBeenSaved = true;
15551 break;
15556 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15557 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15558 data << uint32(hasBeenSaved);
15559 GetSession()->SendPacket(&data);
15561 if(!hasBeenSaved)
15562 return;
15564 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15566 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15568 if(itr->second.perm)
15570 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15571 data << uint32(itr->second.save->GetMapId());
15572 GetSession()->SendPacket(&data);
15578 /// convert the player's binds to the group
15579 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15581 bool has_binds = false;
15582 bool has_solo = false;
15584 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15585 assert(player_guid);
15587 // copy all binds to the group, when changing leader it's assumed the character
15588 // will not have any solo binds
15590 if(player)
15592 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15594 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15596 has_binds = true;
15597 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15598 // permanent binds are not removed
15599 if(!itr->second.perm)
15601 player->UnbindInstance(itr, i, true); // increments itr
15602 has_solo = true;
15604 else
15605 ++itr;
15610 // if the player's not online we don't know what binds it has
15611 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));
15612 // the following should not get executed when changing leaders
15613 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15616 bool Player::_LoadHomeBind(QueryResult *result)
15618 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15619 if(!info)
15621 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15622 return false;
15625 bool ok = false;
15626 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15627 if (result)
15629 Field *fields = result->Fetch();
15630 m_homebindMapId = fields[0].GetUInt32();
15631 m_homebindZoneId = fields[1].GetUInt16();
15632 m_homebindX = fields[2].GetFloat();
15633 m_homebindY = fields[3].GetFloat();
15634 m_homebindZ = fields[4].GetFloat();
15635 delete result;
15637 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15639 // accept saved data only for valid position (and non instanceable), and accessable
15640 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15641 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15643 ok = true;
15645 else
15646 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15649 if(!ok)
15651 m_homebindMapId = info->mapId;
15652 m_homebindZoneId = info->zoneId;
15653 m_homebindX = info->positionX;
15654 m_homebindY = info->positionY;
15655 m_homebindZ = info->positionZ;
15657 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);
15660 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15661 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15663 return true;
15666 /*********************************************************/
15667 /*** SAVE SYSTEM ***/
15668 /*********************************************************/
15670 void Player::SaveToDB()
15672 // delay auto save at any saves (manual, in code, or autosave)
15673 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15675 // first save/honor gain after midnight will also update the player's honor fields
15676 UpdateHonorFields();
15678 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15679 //save, far from tavern/city
15680 //save, but in tavern/city
15681 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15682 outDebugValues();
15684 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15685 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15686 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15687 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15688 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15689 uint32 tmp_displayid = GetDisplayId();
15691 // Set player sit state to standing on save, also stealth and shifted form
15692 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15693 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15694 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15695 SetDisplayId(GetNativeDisplayId());
15697 bool inworld = IsInWorld();
15699 CharacterDatabase.BeginTransaction();
15701 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15703 std::string sql_name = m_name;
15704 CharacterDatabase.escape_string(sql_name);
15706 std::ostringstream ss;
15707 ss << "INSERT INTO characters (guid,account,name,race,class,"
15708 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15709 "taximask, online, cinematic, "
15710 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15711 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15712 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15713 << GetGUIDLow() << ", "
15714 << GetSession()->GetAccountId() << ", '"
15715 << sql_name << "', "
15716 << m_race << ", "
15717 << m_class << ", ";
15719 if(!IsBeingTeleported())
15721 ss << GetMapId() << ", "
15722 << (uint32)GetDifficulty() << ", "
15723 << finiteAlways(GetPositionX()) << ", "
15724 << finiteAlways(GetPositionY()) << ", "
15725 << finiteAlways(GetPositionZ()) << ", "
15726 << finiteAlways(GetOrientation()) << ", '";
15728 else
15730 ss << GetTeleportDest().mapid << ", "
15731 << (uint32)GetDifficulty() << ", "
15732 << finiteAlways(GetTeleportDest().x) << ", "
15733 << finiteAlways(GetTeleportDest().y) << ", "
15734 << finiteAlways(GetTeleportDest().z) << ", "
15735 << finiteAlways(GetTeleportDest().o) << ", '";
15738 uint16 i;
15739 for( i = 0; i < m_valuesCount; i++ )
15741 ss << GetUInt32Value(i) << " ";
15744 ss << "', ";
15746 ss << m_taxi; // string with TaxiMaskSize numbers
15748 ss << ", ";
15749 ss << (inworld ? 1 : 0);
15751 ss << ", ";
15752 ss << m_cinematic;
15754 ss << ", ";
15755 ss << m_Played_time[0];
15756 ss << ", ";
15757 ss << m_Played_time[1];
15759 ss << ", ";
15760 ss << finiteAlways(m_rest_bonus);
15761 ss << ", ";
15762 ss << (uint64)time(NULL);
15763 ss << ", ";
15764 ss << is_save_resting;
15765 ss << ", ";
15766 ss << m_resetTalentsCost;
15767 ss << ", ";
15768 ss << (uint64)m_resetTalentsTime;
15770 ss << ", ";
15771 ss << finiteAlways(m_movementInfo.t_x);
15772 ss << ", ";
15773 ss << finiteAlways(m_movementInfo.t_y);
15774 ss << ", ";
15775 ss << finiteAlways(m_movementInfo.t_z);
15776 ss << ", ";
15777 ss << finiteAlways(m_movementInfo.t_o);
15778 ss << ", ";
15779 if (m_transport)
15780 ss << m_transport->GetGUIDLow();
15781 else
15782 ss << "0";
15784 ss << ", ";
15785 ss << m_ExtraFlags;
15787 ss << ", ";
15788 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15790 ss << ", ";
15791 ss << uint32(m_atLoginFlags);
15793 ss << ", ";
15794 ss << GetZoneId();
15796 ss << ", ";
15797 ss << (uint64)m_deathExpireTime;
15799 ss << ", '";
15800 ss << m_taxi.SaveTaxiDestinationsToString();
15801 ss << "', '0', ";
15802 ss << GetBattleGroundId();
15803 ss << ", ";
15804 ss << GetBGTeam();
15805 ss << ", ";
15806 ss << m_bgEntryPoint.mapid << ", "
15807 << finiteAlways(m_bgEntryPoint.x) << ", "
15808 << finiteAlways(m_bgEntryPoint.y) << ", "
15809 << finiteAlways(m_bgEntryPoint.z) << ", "
15810 << finiteAlways(m_bgEntryPoint.o);
15811 ss << ")";
15813 CharacterDatabase.Execute( ss.str().c_str() );
15815 if(m_mailsUpdated) //save mails only when needed
15816 _SaveMail();
15818 _SaveInventory();
15819 _SaveQuestStatus();
15820 _SaveDailyQuestStatus();
15821 _SaveTutorials();
15822 _SaveSpells();
15823 _SaveSpellCooldowns();
15824 _SaveActions();
15825 _SaveAuras();
15826 _SaveReputation();
15828 CharacterDatabase.CommitTransaction();
15830 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15831 SetDisplayId(tmp_displayid);
15832 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15833 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15834 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15835 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15837 // save pet (hunter pet level and experience and all type pets health/mana).
15838 if(Pet* pet = GetPet())
15839 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15840 m_achievementMgr.SaveToDB();
15843 // fast save function for item/money cheating preventing - save only inventory and money state
15844 void Player::SaveInventoryAndGoldToDB()
15846 _SaveInventory();
15847 //money is in data field
15848 SaveDataFieldToDB();
15851 void Player::_SaveActions()
15853 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15855 switch (itr->second.uState)
15857 case ACTIONBUTTON_NEW:
15858 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15859 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15860 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15861 ++itr;
15862 break;
15863 case ACTIONBUTTON_CHANGED:
15864 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15865 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15866 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15867 ++itr;
15868 break;
15869 case ACTIONBUTTON_DELETED:
15870 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15871 m_actionButtons.erase(itr++);
15872 break;
15873 default:
15874 ++itr;
15875 break;
15880 void Player::_SaveAuras()
15882 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15884 AuraMap const& auras = GetAuras();
15886 if (auras.empty())
15887 return;
15889 spellEffectPair lastEffectPair = auras.begin()->first;
15890 uint32 stackCounter = 1;
15892 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15894 if(itr == auras.end() || lastEffectPair != itr->first)
15896 AuraMap::const_iterator itr2 = itr;
15897 // save previous spellEffectPair to db
15898 itr2--;
15900 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15902 //skip all auras from spells that are passive or need a shapeshift
15903 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15905 //do not save single target auras (unless they were cast by the player)
15906 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15908 uint8 i;
15909 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15910 for (i = 0; i < 3; i++)
15911 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15912 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15913 break;
15915 if (i == 3)
15917 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15918 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15919 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()));
15924 if(itr == auras.end())
15925 break;
15928 if (lastEffectPair == itr->first)
15929 stackCounter++;
15930 else
15932 lastEffectPair = itr->first;
15933 stackCounter = 1;
15938 void Player::_SaveInventory()
15940 // force items in buyback slots to new state
15941 // and remove those that aren't already
15942 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15944 Item *item = m_items[i];
15945 if (!item || item->GetState() == ITEM_NEW) continue;
15946 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15947 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15948 m_items[i]->FSetState(ITEM_NEW);
15951 // update enchantment durations
15952 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15954 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15957 // if no changes
15958 if (m_itemUpdateQueue.empty()) return;
15960 // do not save if the update queue is corrupt
15961 bool error = false;
15962 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15964 Item *item = m_itemUpdateQueue[i];
15965 if(!item || item->GetState() == ITEM_REMOVED) continue;
15966 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15968 if (test == NULL)
15970 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());
15971 error = true;
15973 else if (test != item)
15975 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());
15976 error = true;
15980 if (error)
15982 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15983 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15984 return;
15987 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15989 Item *item = m_itemUpdateQueue[i];
15990 if(!item) continue;
15992 Bag *container = item->GetContainer();
15993 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15995 switch(item->GetState())
15997 case ITEM_NEW:
15998 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());
15999 break;
16000 case ITEM_CHANGED:
16001 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());
16002 break;
16003 case ITEM_REMOVED:
16004 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16005 break;
16006 case ITEM_UNCHANGED:
16007 break;
16010 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16012 m_itemUpdateQueue.clear();
16015 void Player::_SaveMail()
16017 if (!m_mailsLoaded)
16018 return;
16020 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16022 Mail *m = (*itr);
16023 if (m->state == MAIL_STATE_CHANGED)
16025 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'",
16026 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16027 if(m->removedItems.size())
16029 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16030 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16031 m->removedItems.clear();
16033 m->state = MAIL_STATE_UNCHANGED;
16035 else if (m->state == MAIL_STATE_DELETED)
16037 if (m->HasItems())
16038 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16039 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16040 if (m->itemTextId)
16041 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16042 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16043 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16047 //deallocate deleted mails...
16048 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16050 if ((*itr)->state == MAIL_STATE_DELETED)
16052 Mail* m = *itr;
16053 m_mail.erase(itr);
16054 delete m;
16055 itr = m_mail.begin();
16057 else
16058 ++itr;
16061 m_mailsUpdated = false;
16064 void Player::_SaveQuestStatus()
16066 // we don't need transactions here.
16067 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16069 switch (i->second.uState)
16071 case QUEST_NEW :
16072 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16073 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16074 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
16075 break;
16076 case QUEST_CHANGED :
16077 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' ",
16078 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
16079 break;
16080 case QUEST_UNCHANGED:
16081 break;
16083 i->second.uState = QUEST_UNCHANGED;
16087 void Player::_SaveDailyQuestStatus()
16089 if(!m_DailyQuestChanged)
16090 return;
16092 m_DailyQuestChanged = false;
16094 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16096 // we don't need transactions here.
16097 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16098 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16099 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16100 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
16101 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16104 void Player::_SaveReputation()
16106 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
16108 if (itr->second.Changed)
16110 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
16111 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);
16112 itr->second.Changed = false;
16117 void Player::_SaveSpells()
16119 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16121 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16122 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16124 // add only changed/new not dependent spells
16125 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16126 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);
16128 if (itr->second->state == PLAYERSPELL_REMOVED)
16130 delete itr->second;
16131 m_spells.erase(itr++);
16133 else
16135 itr->second->state = PLAYERSPELL_UNCHANGED;
16136 ++itr;
16142 void Player::_SaveTutorials()
16144 if(!m_TutorialsChanged)
16145 return;
16147 uint32 Rows=0;
16148 // it's better than rebuilding indexes multiple times
16149 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
16150 if(result)
16152 Rows = result->Fetch()[0].GetUInt32();
16153 delete result;
16156 if (Rows)
16158 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'",
16159 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 );
16161 else
16163 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]);
16166 m_TutorialsChanged = false;
16169 void Player::outDebugValues() const
16171 if(!sLog.IsOutDebug()) // optimize disabled debug output
16172 return;
16174 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16175 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16176 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16177 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
16178 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16179 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16180 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16181 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16182 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16183 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16184 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16185 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16188 /*********************************************************/
16189 /*** FLOOD FILTER SYSTEM ***/
16190 /*********************************************************/
16192 void Player::UpdateSpeakTime()
16194 // ignore chat spam protection for GMs in any mode
16195 if(GetSession()->GetSecurity() > SEC_PLAYER)
16196 return;
16198 time_t current = time (NULL);
16199 if(m_speakTime > current)
16201 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16202 if(!max_count)
16203 return;
16205 ++m_speakCount;
16206 if(m_speakCount >= max_count)
16208 // prevent overwrite mute time, if message send just before mutes set, for example.
16209 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16210 if(GetSession()->m_muteTime < new_mute)
16211 GetSession()->m_muteTime = new_mute;
16213 m_speakCount = 0;
16216 else
16217 m_speakCount = 0;
16219 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16222 bool Player::CanSpeak() const
16224 return GetSession()->m_muteTime <= time (NULL);
16227 /*********************************************************/
16228 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16229 /*********************************************************/
16231 void Player::SendAttackSwingNotInRange()
16233 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16234 GetSession()->SendPacket( &data );
16237 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16239 std::ostringstream ss;
16240 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16241 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16242 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16243 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16244 sLog.outDebug(ss.str().c_str());
16245 CharacterDatabase.Execute(ss.str().c_str());
16248 void Player::SaveDataFieldToDB()
16250 std::ostringstream ss;
16251 ss<<"UPDATE characters SET data='";
16253 for(uint16 i = 0; i < m_valuesCount; i++ )
16255 ss << GetUInt32Value(i) << " ";
16257 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16259 CharacterDatabase.Execute(ss.str().c_str());
16262 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16264 std::ostringstream ss2;
16265 ss2<<"UPDATE characters SET data='";
16266 int i=0;
16267 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16269 ss2<<tokens[i]<<" ";
16271 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16273 return CharacterDatabase.Execute(ss2.str().c_str());
16276 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16278 char buf[11];
16279 snprintf(buf,11,"%u",value);
16281 if(index >= tokens.size())
16282 return;
16284 tokens[index] = buf;
16287 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16289 Tokens tokens;
16290 if(!LoadValuesArrayFromDB(tokens,guid))
16291 return;
16293 if(index >= tokens.size())
16294 return;
16296 char buf[11];
16297 snprintf(buf,11,"%u",value);
16298 tokens[index] = buf;
16300 SaveValuesArrayInDB(tokens,guid);
16303 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16305 uint32 temp;
16306 memcpy(&temp, &value, sizeof(value));
16307 Player::SetUInt32ValueInDB(index, temp, guid);
16310 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16312 Tokens tokens;
16313 if(!LoadValuesArrayFromDB(tokens, guid))
16314 return;
16316 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
16317 uint8 race = unit_bytes0 & 0xFF;
16318 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
16320 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
16321 if(!info)
16322 return;
16324 unit_bytes0 &= ~(0xFF << 16);
16325 unit_bytes0 |= (gender << 16);
16326 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
16328 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16329 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16331 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16333 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16334 player_bytes2 &= ~0xFF;
16335 player_bytes2 |= facialHair;
16336 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16338 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16339 player_bytes3 &= ~0xFF;
16340 player_bytes3 |= gender;
16341 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16343 SaveValuesArrayInDB(tokens, guid);
16346 void Player::SendAttackSwingNotStanding()
16348 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16349 GetSession()->SendPacket( &data );
16352 void Player::SendAttackSwingDeadTarget()
16354 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16355 GetSession()->SendPacket( &data );
16358 void Player::SendAttackSwingCantAttack()
16360 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16361 GetSession()->SendPacket( &data );
16364 void Player::SendAttackSwingCancelAttack()
16366 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16367 GetSession()->SendPacket( &data );
16370 void Player::SendAttackSwingBadFacingAttack()
16372 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16373 GetSession()->SendPacket( &data );
16376 void Player::SendAutoRepeatCancel()
16378 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16379 data.append(GetPackGUID()); // may be it's target guid
16380 GetSession()->SendPacket( &data );
16383 void Player::PlaySound(uint32 Sound, bool OnlySelf)
16385 WorldPacket data(SMSG_PLAY_SOUND, 4);
16386 data << Sound;
16387 if (OnlySelf)
16388 GetSession()->SendPacket( &data );
16389 else
16390 SendMessageToSet( &data, true );
16393 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16395 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16396 data << Area;
16397 data << Experience;
16398 GetSession()->SendPacket(&data);
16401 void Player::SendDungeonDifficulty(bool IsInGroup)
16403 uint8 val = 0x00000001;
16404 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16405 data << (uint32)GetDifficulty();
16406 data << uint32(val);
16407 data << uint32(IsInGroup);
16408 GetSession()->SendPacket(&data);
16411 void Player::SendResetFailedNotify(uint32 mapid)
16413 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16414 data << uint32(mapid);
16415 GetSession()->SendPacket(&data);
16418 /// Reset all solo instances and optionally send a message on success for each
16419 void Player::ResetInstances(uint8 method)
16421 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16423 // we assume that when the difficulty changes, all instances that can be reset will be
16424 uint8 dif = GetDifficulty();
16426 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16428 InstanceSave *p = itr->second.save;
16429 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16430 if(!entry || !p->CanReset())
16432 ++itr;
16433 continue;
16436 if(method == INSTANCE_RESET_ALL)
16438 // the "reset all instances" method can only reset normal maps
16439 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16441 ++itr;
16442 continue;
16446 // if the map is loaded, reset it
16447 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16448 if(map && map->IsDungeon())
16449 ((InstanceMap*)map)->Reset(method);
16451 // since this is a solo instance there should not be any players inside
16452 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16453 SendResetInstanceSuccess(p->GetMapId());
16455 p->DeleteFromDB();
16456 m_boundInstances[dif].erase(itr++);
16458 // the following should remove the instance save from the manager and delete it as well
16459 p->RemovePlayer(this);
16463 void Player::SendResetInstanceSuccess(uint32 MapId)
16465 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16466 data << MapId;
16467 GetSession()->SendPacket(&data);
16470 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16472 // TODO: find what other fail reasons there are besides players in the instance
16473 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16474 data << reason;
16475 data << MapId;
16476 GetSession()->SendPacket(&data);
16479 /*********************************************************/
16480 /*** Update timers ***/
16481 /*********************************************************/
16483 ///checks the 15 afk reports per 5 minutes limit
16484 void Player::UpdateAfkReport(time_t currTime)
16486 if(m_bgAfkReportedTimer <= currTime)
16488 m_bgAfkReportedCount = 0;
16489 m_bgAfkReportedTimer = currTime+5*MINUTE;
16493 void Player::UpdateContestedPvP(uint32 diff)
16495 if(!m_contestedPvPTimer||isInCombat())
16496 return;
16497 if(m_contestedPvPTimer <= diff)
16499 ResetContestedPvP();
16501 else
16502 m_contestedPvPTimer -= diff;
16505 void Player::UpdatePvPFlag(time_t currTime)
16507 if(!IsPvP())
16508 return;
16509 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16510 return;
16512 UpdatePvP(false);
16515 void Player::UpdateDuelFlag(time_t currTime)
16517 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16518 return;
16520 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16521 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16523 duel->startTimer = 0;
16524 duel->startTime = currTime;
16525 duel->opponent->duel->startTimer = 0;
16526 duel->opponent->duel->startTime = currTime;
16529 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16531 if(!pet)
16532 pet = GetPet();
16534 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16536 //returning of reagents only for players, so best done here
16537 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16538 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16540 if(spellInfo)
16542 for(uint32 i = 0; i < 7; ++i)
16544 if(spellInfo->Reagent[i] > 0)
16546 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16547 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16548 if( msg == EQUIP_ERR_OK )
16550 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16551 if(IsInWorld())
16552 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16557 m_temporaryUnsummonedPetNumber = 0;
16560 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16561 return;
16563 // only if current pet in slot
16564 switch(pet->getPetType())
16566 case MINI_PET:
16567 m_miniPet = 0;
16568 break;
16569 case GUARDIAN_PET:
16570 m_guardianPets.erase(pet->GetGUID());
16571 break;
16572 default:
16573 if(GetPetGUID() == pet->GetGUID())
16574 SetPet(NULL);
16575 break;
16578 pet->CombatStop();
16580 if(returnreagent)
16582 switch(pet->GetEntry())
16584 //warlock pets except imp are removed(?) when logging out
16585 case 1860:
16586 case 1863:
16587 case 417:
16588 case 17252:
16589 mode = PET_SAVE_NOT_IN_SLOT;
16590 break;
16594 pet->SavePetToDB(mode);
16596 pet->CleanupsBeforeDelete();
16597 pet->AddObjectToRemoveList();
16598 pet->m_removed = true;
16600 if(pet->isControlled())
16602 WorldPacket data(SMSG_PET_SPELLS, 8);
16603 data << uint64(0);
16604 data << uint32(0);
16605 GetSession()->SendPacket(&data);
16607 if(GetGroup())
16608 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16612 void Player::RemoveMiniPet()
16614 if(Pet* pet = GetMiniPet())
16616 pet->Remove(PET_SAVE_AS_DELETED);
16617 m_miniPet = 0;
16621 Pet* Player::GetMiniPet()
16623 if(!m_miniPet)
16624 return NULL;
16625 return ObjectAccessor::GetPet(m_miniPet);
16628 void Player::RemoveGuardians()
16630 while(!m_guardianPets.empty())
16632 uint64 guid = *m_guardianPets.begin();
16633 if(Pet* pet = ObjectAccessor::GetPet(guid))
16634 pet->Remove(PET_SAVE_AS_DELETED);
16636 m_guardianPets.erase(guid);
16640 bool Player::HasGuardianWithEntry(uint32 entry)
16642 // pet guid middle part is entry (and creature also)
16643 // and in guardian list must be guardians with same entry _always_
16644 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16645 if(GUID_ENPART(*itr)==entry)
16646 return true;
16648 return false;
16651 void Player::Uncharm()
16653 Unit* charm = GetCharm();
16654 if(!charm)
16655 return;
16657 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16658 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16661 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16663 *data << (uint8)msgtype;
16664 *data << (uint32)language;
16665 *data << (uint64)GetGUID();
16666 *data << (uint32)language; //language 2.1.0 ?
16667 *data << (uint64)GetGUID();
16668 *data << (uint32)(text.length()+1);
16669 *data << text;
16670 *data << (uint8)chatTag();
16673 void Player::Say(const std::string& text, const uint32 language)
16675 WorldPacket data(SMSG_MESSAGECHAT, 200);
16676 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16677 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16680 void Player::Yell(const std::string& text, const uint32 language)
16682 WorldPacket data(SMSG_MESSAGECHAT, 200);
16683 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16684 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16687 void Player::TextEmote(const std::string& text)
16689 WorldPacket data(SMSG_MESSAGECHAT, 200);
16690 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16691 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16694 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16696 if (language != LANG_ADDON) // if not addon data
16697 language = LANG_UNIVERSAL; // whispers should always be readable
16699 Player *rPlayer = objmgr.GetPlayer(receiver);
16701 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16702 if(!rPlayer->isDND() || isGameMaster())
16704 WorldPacket data(SMSG_MESSAGECHAT, 200);
16705 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16706 rPlayer->GetSession()->SendPacket(&data);
16708 data.Initialize(SMSG_MESSAGECHAT, 200);
16709 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16710 GetSession()->SendPacket(&data);
16712 else
16714 // announce to player that player he is whispering to is dnd and cannot receive his message
16715 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16718 if(!isAcceptWhispers())
16720 SetAcceptWhispers(true);
16721 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16724 // announce to player that player he is whispering to is afk
16725 if(rPlayer->isAFK())
16726 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16728 // if player whisper someone, auto turn of dnd to be able to receive an answer
16729 if(isDND() && !rPlayer->isGameMaster())
16730 ToggleDND();
16733 void Player::PetSpellInitialize()
16735 Pet* pet = GetPet();
16737 if(!pet)
16738 return;
16740 sLog.outDebug("Pet Spells Groups");
16742 CharmInfo *charmInfo = pet->GetCharmInfo();
16744 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16745 data << uint64(pet->GetGUID());
16746 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16747 data << uint32(0);
16748 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16750 // action bar loop
16751 for(uint32 i = 0; i < 10; i++)
16753 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16756 size_t spellsCountPos = data.wpos();
16758 // spells count
16759 uint8 addlist = 0;
16760 data << uint8(addlist); // placeholder
16762 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16764 // spells loop
16765 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16767 if(itr->second->state == PETSPELL_REMOVED)
16768 continue;
16770 data << uint16(itr->first);
16771 data << uint16(itr->second->active); // pet spell active state isn't boolean
16772 ++addlist;
16776 data.put<uint8>(spellsCountPos, addlist);
16778 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16779 data << uint8(cooldownsCount);
16781 time_t curTime = time(NULL);
16783 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16785 time_t cooldown = 0;
16787 if(itr->second > curTime)
16788 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16790 data << uint16(itr->first); // spellid
16791 data << uint16(0); // spell category?
16792 data << uint32(itr->second); // cooldown
16793 data << uint32(0); // category cooldown
16796 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16798 time_t cooldown = 0;
16800 if(itr->second > curTime)
16801 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16803 data << uint16(itr->first); // spellid
16804 data << uint16(0); // spell category?
16805 data << uint32(0); // cooldown
16806 data << uint32(itr->second); // category cooldown
16809 GetSession()->SendPacket(&data);
16812 void Player::PossessSpellInitialize()
16814 Unit* charm = GetCharm();
16816 if(!charm)
16817 return;
16819 CharmInfo *charmInfo = charm->GetCharmInfo();
16821 if(!charmInfo)
16823 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16824 return;
16827 uint8 addlist = 0;
16828 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16830 //16
16831 data << uint64(charm->GetGUID());
16832 data << uint32(0x00000000);
16833 data << uint32(0);
16834 data << uint8(0) << uint8(0) << uint16(0);
16836 for(uint32 i = 0; i < 10; i++) //40
16838 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16841 data << uint8(addlist); //1
16843 uint8 count = 0;
16844 data << uint8(count); // cooldowns count
16846 GetSession()->SendPacket(&data);
16849 void Player::CharmSpellInitialize()
16851 Unit* charm = GetCharm();
16853 if(!charm)
16854 return;
16856 CharmInfo *charmInfo = charm->GetCharmInfo();
16857 if(!charmInfo)
16859 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16860 return;
16863 uint8 addlist = 0;
16865 if(charm->GetTypeId() != TYPEID_PLAYER)
16867 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16869 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16871 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16873 if(charmInfo->GetCharmSpell(i)->spellId)
16874 ++addlist;
16879 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16881 data << uint64(charm->GetGUID());
16882 data << uint32(0x00000000);
16883 data << uint32(0);
16884 if(charm->GetTypeId() != TYPEID_PLAYER)
16885 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16886 else
16887 data << uint8(0) << uint8(0);
16888 data << uint16(0);
16890 for(uint32 i = 0; i < 10; i++) //40
16892 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16895 data << uint8(addlist); //1
16897 if(addlist)
16899 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16901 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16902 if(cspell->spellId)
16904 data << uint16(cspell->spellId);
16905 data << uint16(cspell->active);
16910 uint8 count = 0;
16911 data << uint8(count); // cooldowns count
16913 GetSession()->SendPacket(&data);
16916 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16918 if (!mod || !spellInfo)
16919 return false;
16921 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16923 // prevent apply to any spell except spell that trigger expire
16924 if(spell)
16926 if(mod->lastAffected != spell)
16927 return false;
16929 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16930 return false;
16933 return spellmgr.IsAffectedByMod(spellInfo, mod);
16936 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16938 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16940 for(int eff=0;eff<96;++eff)
16942 uint64 _mask = 0;
16943 uint64 _mask2= 0;
16944 if (eff<64) _mask = uint64(1) << (eff- 0);
16945 else _mask2= uint64(1) << (eff-64);
16946 if ( mod->mask & _mask || mod->mask2 & _mask2)
16948 int32 val = 0;
16949 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16951 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16952 val += (*itr)->value;
16954 val += apply ? mod->value : -(mod->value);
16955 WorldPacket data(Opcode, (1+1+4));
16956 data << uint8(eff);
16957 data << uint8(mod->op);
16958 data << int32(val);
16959 SendDirectMessage(&data);
16963 if (apply)
16964 m_spellMods[mod->op].push_back(mod);
16965 else
16967 if (mod->charges == -1)
16968 --m_SpellModRemoveCount;
16969 m_spellMods[mod->op].remove(mod);
16970 delete mod;
16974 void Player::RemoveSpellMods(Spell const* spell)
16976 if(!spell || (m_SpellModRemoveCount == 0))
16977 return;
16979 for(int i=0;i<MAX_SPELLMOD;++i)
16981 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16983 SpellModifier *mod = *itr;
16984 ++itr;
16986 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16988 RemoveAurasDueToSpell(mod->spellId);
16989 if (m_spellMods[i].empty())
16990 break;
16991 else
16992 itr = m_spellMods[i].begin();
16998 // send Proficiency
16999 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17001 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17002 data << pr1 << pr2;
17003 GetSession()->SendPacket (&data);
17006 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17008 QueryResult *result = NULL;
17009 if(type==10)
17010 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17011 else
17012 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17013 if(result)
17015 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.
17016 { // and SendPetitionQueryOpcode reads data from the DB
17017 Field *fields = result->Fetch();
17018 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17019 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17021 // send update if charter owner in game
17022 Player* owner = objmgr.GetPlayer(ownerguid);
17023 if(owner)
17024 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17026 } while ( result->NextRow() );
17028 delete result;
17030 if(type==10)
17031 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17032 else
17033 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17036 CharacterDatabase.BeginTransaction();
17037 if(type == 10)
17039 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17040 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17042 else
17044 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17045 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17047 CharacterDatabase.CommitTransaction();
17050 void Player::LeaveAllArenaTeams(uint64 guid)
17052 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));
17053 if(!result)
17054 return;
17058 Field *fields = result->Fetch();
17059 uint32 at_id = fields[0].GetUInt32();
17060 if(at_id != 0)
17062 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
17063 if(at)
17064 at->DelMember(guid);
17066 } while (result->NextRow());
17068 delete result;
17071 void Player::SetRestBonus (float rest_bonus_new)
17073 // Prevent resting on max level
17074 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17075 rest_bonus_new = 0;
17077 if(rest_bonus_new < 0)
17078 rest_bonus_new = 0;
17080 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17082 if(rest_bonus_new > rest_bonus_max)
17083 m_rest_bonus = rest_bonus_max;
17084 else
17085 m_rest_bonus = rest_bonus_new;
17087 // update data for client
17088 if(m_rest_bonus>10)
17089 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17090 else if(m_rest_bonus<=1)
17091 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17093 //RestTickUpdate
17094 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17097 void Player::HandleStealthedUnitsDetection()
17099 std::list<Unit*> stealthedUnits;
17101 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17102 Cell cell(p);
17103 cell.data.Part.reserved = ALL_DISTRICT;
17104 cell.SetNoCreate();
17106 MaNGOS::AnyStealthedCheck u_check;
17107 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17109 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17110 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17112 CellLock<GridReadGuard> cell_lock(cell, p);
17113 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
17114 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
17116 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
17118 if((*i)==this)
17120 i = stealthedUnits.erase(i);
17121 continue;
17124 if ((*i)->isVisibleForOrDetect(this,true))
17127 (*i)->SendUpdateToPlayer(this);
17128 m_clientGUIDs.insert((*i)->GetGUID());
17130 #ifdef MANGOS_DEBUG
17131 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17132 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17133 #endif
17135 // target aura duration for caster show only if target exist at caster client
17136 // send data at target visibility change (adding to client)
17137 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17138 SendAurasForTarget(*i);
17140 i = stealthedUnits.erase(i);
17141 continue;
17144 ++i;
17148 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
17150 if(nodes.size() < 2)
17151 return false;
17153 // not let cheating with start flight mounted
17154 if(IsMounted())
17156 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17157 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17158 GetSession()->SendPacket(&data);
17159 return false;
17162 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17164 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17165 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17166 GetSession()->SendPacket(&data);
17167 return false;
17170 // 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
17171 if(GetSession()->isLogingOut() ||
17172 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
17173 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
17174 IsNonMeleeSpellCasted(false) ||
17175 isInCombat())
17177 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17178 data << uint32(ERR_TAXIPLAYERBUSY);
17179 GetSession()->SendPacket(&data);
17180 return false;
17183 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17184 return false;
17186 uint32 sourcenode = nodes[0];
17188 // starting node too far away (cheat?)
17189 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17190 if( !node || node->map_id != GetMapId() ||
17191 (node->x - GetPositionX())*(node->x - GetPositionX())+
17192 (node->y - GetPositionY())*(node->y - GetPositionY())+
17193 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17194 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
17196 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17197 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17198 GetSession()->SendPacket(&data);
17199 return false;
17202 // Prepare to flight start now
17204 // stop combat at start taxi flight if any
17205 CombatStop();
17207 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17208 TradeCancel(true);
17210 // clean not finished taxi path if any
17211 m_taxi.ClearTaxiDestinations();
17213 // 0 element current node
17214 m_taxi.AddTaxiDestination(sourcenode);
17216 // fill destinations path tail
17217 uint32 sourcepath = 0;
17218 uint32 totalcost = 0;
17220 uint32 prevnode = sourcenode;
17221 uint32 lastnode = 0;
17223 for(uint32 i = 1; i < nodes.size(); ++i)
17225 uint32 path, cost;
17227 lastnode = nodes[i];
17228 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
17230 if(!path)
17232 m_taxi.ClearTaxiDestinations();
17233 return false;
17236 totalcost += cost;
17238 if(prevnode == sourcenode)
17239 sourcepath = path;
17241 m_taxi.AddTaxiDestination(lastnode);
17243 prevnode = lastnode;
17246 if(!mount_id) // if not provide then attempt use default.
17247 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
17249 if (mount_id == 0 || sourcepath == 0)
17251 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17252 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17253 GetSession()->SendPacket(&data);
17254 m_taxi.ClearTaxiDestinations();
17255 return false;
17258 uint32 money = GetMoney();
17260 if(npc)
17262 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17265 if(money < totalcost)
17267 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17268 data << uint32(ERR_TAXINOTENOUGHMONEY);
17269 GetSession()->SendPacket(&data);
17270 m_taxi.ClearTaxiDestinations();
17271 return false;
17274 //Checks and preparations done, DO FLIGHT
17275 ModifyMoney(-(int32)totalcost);
17276 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17278 // prevent stealth flight
17279 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17281 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17282 data << uint32(ERR_TAXIOK);
17283 GetSession()->SendPacket(&data);
17285 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17287 GetSession()->SendDoFlight(mount_id, sourcepath);
17289 return true;
17292 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17294 // last check 2.0.10
17295 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17296 data << GetGUID();
17297 data << uint8(0x0); // flags (0x1, 0x2)
17298 time_t curTime = time(NULL);
17299 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17301 if (itr->second->state == PLAYERSPELL_REMOVED)
17302 continue;
17303 uint32 unSpellId = itr->first;
17304 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17305 if (!spellInfo)
17307 ASSERT(spellInfo);
17308 continue;
17311 // Not send cooldown for this spells
17312 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17313 continue;
17315 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17317 data << unSpellId;
17318 data << unTimeMs; // in m.secs
17319 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17322 GetSession()->SendPacket(&data);
17325 void Player::InitDataForForm(bool reapplyMods)
17327 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17328 if(ssEntry && ssEntry->attackSpeed)
17330 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17331 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17332 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17334 else
17335 SetRegularAttackTime();
17337 switch(m_form)
17339 case FORM_CAT:
17341 if(getPowerType()!=POWER_ENERGY)
17342 setPowerType(POWER_ENERGY);
17343 break;
17345 case FORM_BEAR:
17346 case FORM_DIREBEAR:
17348 if(getPowerType()!=POWER_RAGE)
17349 setPowerType(POWER_RAGE);
17350 break;
17352 default: // 0, for example
17354 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17355 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17356 setPowerType(Powers(cEntry->powerType));
17357 break;
17361 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17362 if (!reapplyMods)
17363 UpdateEquipSpellsAtFormChange();
17365 UpdateAttackPowerAndDamage();
17366 UpdateAttackPowerAndDamage(true);
17369 // Return true is the bought item has a max count to force refresh of window by caller
17370 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17372 // cheating attempt
17373 if(count < 1) count = 1;
17375 if(!isAlive())
17376 return false;
17378 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17379 if( !pProto )
17381 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17382 return false;
17385 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
17386 if (!pCreature)
17388 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17389 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17390 return false;
17393 VendorItemData const* vItems = pCreature->GetVendorItems();
17394 if(!vItems || vItems->Empty())
17396 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17397 return false;
17400 size_t vendor_slot = vItems->FindItemSlot(item);
17401 if(vendor_slot >= vItems->GetItemCount())
17403 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17404 return false;
17407 VendorItem const* crItem = vItems->m_items[vendor_slot];
17409 // check current item amount if it limited
17410 if( crItem->maxcount != 0 )
17412 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17414 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17415 return false;
17419 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17421 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17422 return false;
17425 if(crItem->ExtendedCost)
17427 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17428 if(!iece)
17430 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17431 return false;
17434 // honor points price
17435 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17437 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17438 return false;
17441 // arena points price
17442 if(GetArenaPoints() < (iece->reqarenapoints * count))
17444 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17445 return false;
17448 // item base price
17449 for (uint8 i = 0; i < 5; ++i)
17451 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17453 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17454 return false;
17458 // check for personal arena rating requirement
17459 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17461 // probably not the proper equip err
17462 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17463 return false;
17467 uint32 price = pProto->BuyPrice * count;
17469 // reputation discount
17470 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17472 if( GetMoney() < price )
17474 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17475 return false;
17478 uint8 bag = 0; // init for case invalid bagGUID
17480 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17482 Bag *pBag;
17483 if( bagguid == GetGUID() )
17485 bag = INVENTORY_SLOT_BAG_0;
17487 else
17489 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
17491 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17492 if( pBag )
17494 if( bagguid == pBag->GetGUID() )
17496 bag = i;
17497 break;
17504 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17506 ItemPosCountVec dest;
17507 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17508 if( msg != EQUIP_ERR_OK )
17510 SendEquipError( msg, NULL, NULL );
17511 return false;
17514 ModifyMoney( -(int32)price );
17515 if(crItem->ExtendedCost) // case for new honor system
17517 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17518 if(iece->reqhonorpoints)
17519 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17520 if(iece->reqarenapoints)
17521 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17522 for (uint8 i = 0; i < 5; ++i)
17524 if(iece->reqitem[i])
17525 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17529 if(Item *it = StoreNewItem( dest, item, true ))
17531 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17533 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17534 data << pCreature->GetGUID();
17535 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17536 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17537 data << (uint32)count;
17538 GetSession()->SendPacket(&data);
17540 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17543 else if( IsEquipmentPos( bag, slot ) )
17545 if(pProto->BuyCount * count != 1)
17547 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17548 return false;
17551 uint16 dest;
17552 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17553 if( msg != EQUIP_ERR_OK )
17555 SendEquipError( msg, NULL, NULL );
17556 return false;
17559 ModifyMoney( -(int32)price );
17560 if(crItem->ExtendedCost) // case for new honor system
17562 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17563 if(iece->reqhonorpoints)
17564 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17565 if(iece->reqarenapoints)
17566 ModifyArenaPoints( - int32(iece->reqarenapoints));
17567 for (uint8 i = 0; i < 5; ++i)
17569 if(iece->reqitem[i])
17570 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17574 if(Item *it = EquipNewItem( dest, item, true ))
17576 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17578 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17579 data << pCreature->GetGUID();
17580 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17581 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17582 data << (uint32)count;
17583 GetSession()->SendPacket(&data);
17585 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17587 AutoUnequipOffhandIfNeed();
17590 else
17592 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17593 return false;
17596 return crItem->maxcount!=0;
17599 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17601 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17602 // the personal rating of the arena team must match the required limit as well
17603 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17604 uint32 max_personal_rating = 0;
17605 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17607 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17609 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17610 uint32 t_rating = at->GetRating();
17611 p_rating = p_rating<t_rating? p_rating : t_rating;
17612 if(max_personal_rating < p_rating)
17613 max_personal_rating = p_rating;
17616 return max_personal_rating;
17619 void Player::UpdateHomebindTime(uint32 time)
17621 // GMs never get homebind timer online
17622 if (m_InstanceValid || isGameMaster())
17624 if(m_HomebindTimer) // instance valid, but timer not reset
17626 // hide reminder
17627 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17628 data << uint32(0);
17629 data << uint32(0);
17630 GetSession()->SendPacket(&data);
17632 // instance is valid, reset homebind timer
17633 m_HomebindTimer = 0;
17635 else if (m_HomebindTimer > 0)
17637 if (time >= m_HomebindTimer)
17639 // teleport to homebind location
17640 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17642 else
17643 m_HomebindTimer -= time;
17645 else
17647 // instance is invalid, start homebind timer
17648 m_HomebindTimer = 60000;
17649 // send message to player
17650 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17651 data << m_HomebindTimer;
17652 data << uint32(1);
17653 GetSession()->SendPacket(&data);
17654 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17658 void Player::UpdatePvP(bool state, bool ovrride)
17660 if(!state || ovrride)
17662 SetPvP(state);
17663 if(Pet* pet = GetPet())
17664 pet->SetPvP(state);
17665 if(Unit* charmed = GetCharm())
17666 charmed->SetPvP(state);
17668 pvpInfo.endTimer = 0;
17670 else
17672 if(pvpInfo.endTimer != 0)
17673 pvpInfo.endTimer = time(NULL);
17674 else
17676 SetPvP(state);
17678 if(Pet* pet = GetPet())
17679 pet->SetPvP(state);
17680 if(Unit* charmed = GetCharm())
17681 charmed->SetPvP(state);
17686 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17688 // init cooldown values
17689 uint32 cat = 0;
17690 int32 rec = -1;
17691 int32 catrec = -1;
17693 // some special item spells without correct cooldown in SpellInfo
17694 // cooldown information stored in item prototype
17695 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17697 if(itemId)
17699 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17701 for(int idx = 0; idx < 5; ++idx)
17703 if(proto->Spells[idx].SpellId == spellInfo->Id)
17705 cat = proto->Spells[idx].SpellCategory;
17706 rec = proto->Spells[idx].SpellCooldown;
17707 catrec = proto->Spells[idx].SpellCategoryCooldown;
17708 break;
17714 // if no cooldown found above then base at DBC data
17715 if(rec < 0 && catrec < 0)
17717 cat = spellInfo->Category;
17718 rec = spellInfo->RecoveryTime;
17719 catrec = spellInfo->CategoryRecoveryTime;
17722 time_t curTime = time(NULL);
17724 time_t catrecTime;
17725 time_t recTime;
17727 // overwrite time for selected category
17728 if(infinityCooldown)
17730 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17731 // but not allow ignore until reset or re-login
17732 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17733 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17735 else
17737 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17738 // prevent 0 cooldowns set by another way
17739 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17740 rec = GetAttackTime(RANGED_ATTACK);
17742 // Now we have cooldown data (if found any), time to apply mods
17743 if(rec > 0)
17744 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17746 if(catrec > 0)
17747 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17749 // replace negative cooldowns by 0
17750 if (rec < 0) rec = 0;
17751 if (catrec < 0) catrec = 0;
17753 // no cooldown after applying spell mods
17754 if( rec == 0 && catrec == 0)
17755 return;
17757 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17758 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17761 // self spell cooldown
17762 if(recTime > 0)
17763 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17765 // category spells
17766 if (cat && catrec > 0)
17768 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17769 if(i_scstore != sSpellCategoryStore.end())
17771 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17773 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17774 continue;
17776 AddSpellCooldown(*i_scset, itemId, catrecTime);
17782 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17784 SpellCooldown sc;
17785 sc.end = end_time;
17786 sc.itemid = itemid;
17787 m_spellCooldowns[spellid] = sc;
17790 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17792 // start cooldowns at server side, if any
17793 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17795 // Send activate cooldown timer (possible 0) at client side
17796 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17797 data << spellInfo->Id;
17798 data << GetGUID();
17799 SendDirectMessage(&data);
17802 void Player::UpdatePotionCooldown(Spell* spell)
17804 // no potion used i combat or still in combat
17805 if(!m_lastPotionId || isInCombat())
17806 return;
17808 // Call not from spell cast, send cooldown event for item spells if no in combat
17809 if(!spell)
17811 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17812 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17813 for(int idx = 0; idx < 5; ++idx)
17814 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17815 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17816 SendCooldownEvent(spellInfo,m_lastPotionId);
17818 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17819 else
17820 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17822 m_lastPotionId = 0;
17825 //slot to be excluded while counting
17826 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17828 if(!enchantmentcondition)
17829 return true;
17831 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17833 if(!Condition)
17834 return true;
17836 uint8 curcount[4] = {0, 0, 0, 0};
17838 //counting current equipped gem colors
17839 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17841 if(i == slot)
17842 continue;
17843 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17844 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17846 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17848 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17849 if(!enchant_id)
17850 continue;
17852 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17853 if(!enchantEntry)
17854 continue;
17856 uint32 gemid = enchantEntry->GemID;
17857 if(!gemid)
17858 continue;
17860 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17861 if(!gemProto)
17862 continue;
17864 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17865 if(!gemProperty)
17866 continue;
17868 uint8 GemColor = gemProperty->color;
17870 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17872 if(tmpcolormask & GemColor)
17873 ++curcount[b];
17879 bool activate = true;
17881 for(int i = 0; i < 5; i++)
17883 if(!Condition->Color[i])
17884 continue;
17886 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17888 // if have <CompareColor> use them as count, else use <value> from Condition
17889 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17891 switch(Condition->Comparator[i])
17893 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17894 activate &= (_cur_gem < _cmp_gem) ? true : false;
17895 break;
17896 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17897 activate &= (_cur_gem > _cmp_gem) ? true : false;
17898 break;
17899 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17900 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17901 break;
17905 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");
17907 return activate;
17910 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17912 //cycle all equipped items
17913 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17915 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17916 if(slot == exceptslot)
17917 continue;
17919 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17921 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17922 continue;
17924 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17926 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17927 if(!enchant_id)
17928 continue;
17930 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17931 if(!enchantEntry)
17932 continue;
17934 uint32 condition = enchantEntry->EnchantmentCondition;
17935 if(condition)
17937 //was enchant active with/without item?
17938 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17939 //should it now be?
17940 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17942 // ignore item gem conditions
17943 //if state changed, (dis)apply enchant
17944 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17951 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17952 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17954 //cycle all equipped items
17955 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17957 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17958 if(slot == exceptslot)
17959 continue;
17961 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17963 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17964 continue;
17966 //cycle all (gem)enchants
17967 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17969 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17970 if(!enchant_id) //if no enchant go to next enchant(slot)
17971 continue;
17973 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17974 if(!enchantEntry)
17975 continue;
17977 //only metagems to be (de)activated, so only enchants with condition
17978 uint32 condition = enchantEntry->EnchantmentCondition;
17979 if(condition)
17980 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17985 void Player::LeaveBattleground(bool teleportToEntryPoint)
17987 if(BattleGround *bg = GetBattleGround())
17989 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17991 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17993 // call after remove to be sure that player resurrected for correct cast
17994 if(need_debuf)
17995 CastSpell(this, 26013, true); // Deserter
17999 bool Player::CanJoinToBattleground() const
18001 // check Deserter debuff
18002 if(GetDummyAura(26013))
18003 return false;
18005 return true;
18008 bool Player::CanReportAfkDueToLimit()
18010 // a player can complain about 15 people per 5 minutes
18011 if(m_bgAfkReportedCount >= 15)
18012 return false;
18013 ++m_bgAfkReportedCount;
18014 return true;
18017 ///This player has been blamed to be inactive in a battleground
18018 void Player::ReportedAfkBy(Player* reporter)
18020 BattleGround *bg = GetBattleGround();
18021 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18022 return;
18024 // check if player has 'Idle' or 'Inactive' debuff
18025 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
18027 m_bgAfkReporter.insert(reporter->GetGUIDLow());
18028 // 3 players have to complain to apply debuff
18029 if(m_bgAfkReporter.size() >= 3)
18031 // cast 'Idle' spell
18032 CastSpell(this, 43680, true);
18033 m_bgAfkReporter.clear();
18038 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18040 // gamemaster in GM mode see all, including ghosts
18041 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18042 return true;
18044 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18045 if (InBattleGround())
18047 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18048 return false;
18049 return true;
18052 // Live player see live player or dead player with not realized corpse
18053 if(pl->isAlive() || pl->m_deathTimer > 0)
18055 return isAlive() || m_deathTimer > 0;
18058 // Ghost see other friendly ghosts, that's for sure
18059 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18060 return true;
18062 // Dead player see live players near own corpse
18063 if(isAlive())
18065 Corpse *corpse = pl->GetCorpse();
18066 if(corpse)
18068 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18069 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18070 return true;
18074 // and not see any other
18075 return false;
18078 bool Player::IsVisibleGloballyFor( Player* u ) const
18080 if(!u)
18081 return false;
18083 // Always can see self
18084 if (u==this)
18085 return true;
18087 // Visible units, always are visible for all players
18088 if (GetVisibility() == VISIBILITY_ON)
18089 return true;
18091 // GMs are visible for higher gms (or players are visible for gms)
18092 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18093 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18095 // non faction visibility non-breakable for non-GMs
18096 if (GetVisibility() == VISIBILITY_OFF)
18097 return false;
18099 // non-gm stealth/invisibility not hide from global player lists
18100 return true;
18103 void Player::UpdateVisibilityOf(WorldObject* target)
18105 if(HaveAtClient(target))
18107 if(!target->isVisibleForInState(this,true))
18109 target->DestroyForPlayer(this);
18110 m_clientGUIDs.erase(target->GetGUID());
18112 #ifdef MANGOS_DEBUG
18113 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18114 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18115 #endif
18118 else
18120 if(target->isVisibleForInState(this,false))
18122 target->SendUpdateToPlayer(this);
18123 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18124 m_clientGUIDs.insert(target->GetGUID());
18126 #ifdef MANGOS_DEBUG
18127 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18128 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18129 #endif
18131 // target aura duration for caster show only if target exist at caster client
18132 // send data at target visibility change (adding to client)
18133 if(target!=this && target->isType(TYPEMASK_UNIT))
18134 SendAurasForTarget((Unit*)target);
18136 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18137 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18142 template<class T>
18143 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18145 s64.insert(target->GetGUID());
18148 template<>
18149 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18151 if(!target->IsTransport())
18152 s64.insert(target->GetGUID());
18155 template<class T>
18156 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18158 if(HaveAtClient(target))
18160 if(!target->isVisibleForInState(this,true))
18162 target->BuildOutOfRangeUpdateBlock(&data);
18163 m_clientGUIDs.erase(target->GetGUID());
18165 #ifdef MANGOS_DEBUG
18166 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18167 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));
18168 #endif
18171 else
18173 if(target->isVisibleForInState(this,false))
18175 visibleNow.insert(target);
18176 target->BuildUpdate(data_updates);
18177 target->BuildCreateUpdateBlockForPlayer(&data, this);
18178 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18180 #ifdef MANGOS_DEBUG
18181 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18182 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));
18183 #endif
18188 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18189 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18190 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18191 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18192 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18194 void Player::InitPrimaryProffesions()
18196 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18199 void Player::SendComboPoints()
18201 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18202 if (combotarget)
18204 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18205 data.append(combotarget->GetPackGUID());
18206 data << uint8(m_comboPoints);
18207 GetSession()->SendPacket(&data);
18211 void Player::AddComboPoints(Unit* target, int8 count)
18213 if(!count)
18214 return;
18216 // without combo points lost (duration checked in aura)
18217 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18219 if(target->GetGUID() == m_comboTarget)
18221 m_comboPoints += count;
18223 else
18225 if(m_comboTarget)
18226 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18227 target->RemoveComboPointHolder(GetGUIDLow());
18229 m_comboTarget = target->GetGUID();
18230 m_comboPoints = count;
18232 target->AddComboPointHolder(GetGUIDLow());
18235 if (m_comboPoints > 5) m_comboPoints = 5;
18236 if (m_comboPoints < 0) m_comboPoints = 0;
18238 SendComboPoints();
18241 void Player::ClearComboPoints()
18243 if(!m_comboTarget)
18244 return;
18246 // without combopoints lost (duration checked in aura)
18247 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18249 m_comboPoints = 0;
18251 SendComboPoints();
18253 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18254 target->RemoveComboPointHolder(GetGUIDLow());
18256 m_comboTarget = 0;
18259 void Player::SetGroup(Group *group, int8 subgroup)
18261 if(group == NULL) m_group.unlink();
18262 else
18264 // never use SetGroup without a subgroup unless you specify NULL for group
18265 assert(subgroup >= 0);
18266 m_group.link(group, this);
18267 m_group.setSubGroup((uint8)subgroup);
18271 void Player::SendInitialPacketsBeforeAddToMap()
18273 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
18274 data << uint32(0); // unknown, may be rest state time or experience
18275 GetSession()->SendPacket(&data);
18277 // Homebind
18278 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
18279 data << m_homebindX << m_homebindY << m_homebindZ;
18280 data << (uint32) m_homebindMapId;
18281 data << (uint32) m_homebindZoneId;
18282 GetSession()->SendPacket(&data);
18284 // SMSG_SET_PROFICIENCY
18285 // SMSG_UPDATE_AURA_DURATION
18287 // tutorial stuff
18288 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
18289 for (int i = 0; i < 8; ++i)
18290 data << uint32( GetTutorialInt(i) );
18291 GetSession()->SendPacket(&data);
18293 SendInitialSpells();
18295 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18296 data << uint32(0); // count, for(count) uint32;
18297 GetSession()->SendPacket(&data);
18299 SendInitialActionButtons();
18300 SendInitialReputations();
18301 m_achievementMgr.SendAllAchievementData();
18302 UpdateZone(GetZoneId());
18303 SendInitWorldStates();
18305 // SMSG_SET_AURA_SINGLE
18307 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18308 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18309 data << (float)0.01666667f; // game speed
18310 GetSession()->SendPacket( &data );
18312 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18313 data << uint32(0x00000000); // on blizz it increments periodically
18314 GetSession()->SendPacket(&data);
18316 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18317 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18318 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18320 m_mover = this;
18323 void Player::SendInitialPacketsAfterAddToMap()
18325 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18326 data << uint32(0x00000000); // on blizz it increments periodically
18327 GetSession()->SendPacket(&data);
18329 CastSpell(this, 836, true); // LOGINEFFECT
18331 // set some aura effects that send packet to player client after add player to map
18332 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18333 // same auras state lost at far teleport, send it one more time in this case also
18334 static const AuraType auratypes[] =
18336 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18337 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18338 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18340 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18342 Unit::AuraList const& auraList = GetAurasByType(*itr);
18343 if(!auraList.empty())
18344 auraList.front()->ApplyModifier(true,true);
18347 if(HasAuraType(SPELL_AURA_MOD_STUN))
18348 SetMovement(MOVE_ROOT);
18350 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18351 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18353 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
18354 data.append(GetPackGUID());
18355 data << (uint32)2;
18356 SendMessageToSet(&data,true);
18359 SendAurasForTarget(this);
18360 SendEnchantmentDurations(); // must be after add to map
18361 SendItemDurations(); // must be after add to map
18364 void Player::SendUpdateToOutOfRangeGroupMembers()
18366 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18367 return;
18368 if(Group* group = GetGroup())
18369 group->UpdatePlayerOutOfRange(this);
18371 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18372 m_auraUpdateMask = 0;
18373 if(Pet *pet = GetPet())
18374 pet->ResetAuraUpdateMask();
18377 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18379 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18380 data << uint32(mapid);
18381 data << uint8(reason); // transfer abort reason
18382 switch(reason)
18384 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18385 case TRANSFER_ABORT_DIFFICULTY:
18386 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18387 data << uint8(arg);
18388 break;
18390 GetSession()->SendPacket(&data);
18393 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18395 // type of warning, based on the time remaining until reset
18396 uint32 type;
18397 if(time > 3600)
18398 type = RAID_INSTANCE_WELCOME;
18399 else if(time > 900 && time <= 3600)
18400 type = RAID_INSTANCE_WARNING_HOURS;
18401 else if(time > 300 && time <= 900)
18402 type = RAID_INSTANCE_WARNING_MIN;
18403 else
18404 type = RAID_INSTANCE_WARNING_MIN_SOON;
18405 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18406 data << uint32(type);
18407 data << uint32(mapid);
18408 data << uint32(time);
18409 GetSession()->SendPacket(&data);
18412 void Player::ApplyEquipCooldown( Item * pItem )
18414 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18416 _Spell const& spellData = pItem->GetProto()->Spells[i];
18418 // no spell
18419 if( !spellData.SpellId )
18420 continue;
18422 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18423 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18424 continue;
18426 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18428 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18429 data << pItem->GetGUID();
18430 data << uint32(spellData.SpellId);
18431 GetSession()->SendPacket(&data);
18435 void Player::resetSpells()
18437 // not need after this call
18438 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18440 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18441 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18444 // make full copy of map (spells removed and marked as deleted at another spell remove
18445 // and we can't use original map for safe iterative with visit each spell at loop end
18446 PlayerSpellMap smap = GetSpellMap();
18448 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18449 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18451 learnDefaultSpells();
18452 learnQuestRewardedSpells();
18455 void Player::learnDefaultSpells()
18457 // learn default race/class spells
18458 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18459 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18461 uint32 tspell = *itr;
18462 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18463 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18464 addSpell(tspell,true,true,true,false);
18465 else // but send in normal spell in game learn case
18466 learnSpell(tspell,true);
18470 void Player::learnQuestRewardedSpells(Quest const* quest)
18472 uint32 spell_id = quest->GetRewSpellCast();
18474 // skip quests without rewarded spell
18475 if( !spell_id )
18476 return;
18478 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18479 if(!spellInfo)
18480 return;
18482 // check learned spells state
18483 bool found = false;
18484 for(int i=0; i < 3; ++i)
18486 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18488 found = true;
18489 break;
18493 // skip quests with not teaching spell or already known spell
18494 if(!found)
18495 return;
18497 // prevent learn non first rank unknown profession and second specialization for same profession)
18498 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18499 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18501 // not have first rank learned (unlearned prof?)
18502 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18503 if( !HasSpell(first_spell) )
18504 return;
18506 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18507 if(!learnedInfo)
18508 return;
18510 // specialization
18511 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18513 // search other specialization for same prof
18514 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18516 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18517 continue;
18519 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18520 if(!itrInfo)
18521 return;
18523 // compare only specializations
18524 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18525 continue;
18527 // compare same chain spells
18528 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18529 continue;
18531 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18532 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18533 return;
18538 CastSpell( this, spell_id, true);
18541 void Player::learnQuestRewardedSpells()
18543 // learn spells received from quest completing
18544 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18546 // skip no rewarded quests
18547 if(!itr->second.m_rewarded)
18548 continue;
18550 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18551 if( !quest )
18552 continue;
18554 learnQuestRewardedSpells(quest);
18558 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18560 uint32 raceMask = getRaceMask();
18561 uint32 classMask = getClassMask();
18562 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18564 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18565 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18566 continue;
18567 // Check race if set
18568 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18569 continue;
18570 // Check class if set
18571 if (pAbility->classmask && !(pAbility->classmask & classMask))
18572 continue;
18574 if (sSpellStore.LookupEntry(pAbility->spellId))
18576 // need unlearn spell
18577 if (skill_value < pAbility->req_skill_value)
18578 removeSpell(pAbility->spellId);
18579 // need learn
18580 else if (!IsInWorld())
18581 addSpell(pAbility->spellId,true,true,true,false);
18582 else
18583 learnSpell(pAbility->spellId,true);
18588 void Player::SendAurasForTarget(Unit *target)
18590 if(target->GetVisibleAuras()->empty()) // speedup things
18591 return;
18593 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18594 data.append(target->GetPackGUID());
18596 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18597 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18599 for(uint32 j = 0; j < 3; ++j)
18601 if(Aura *aura = target->GetAura(itr->second, j))
18603 data << uint8(aura->GetAuraSlot());
18604 data << uint32(aura->GetId());
18606 if(aura->GetId())
18608 uint8 auraFlags = aura->GetAuraFlags();
18609 // flags
18610 data << uint8(auraFlags);
18611 // level
18612 data << uint8(aura->GetAuraLevel());
18613 // charges
18614 data << uint8(aura->GetAuraCharges());
18616 if(!(auraFlags & AFLAG_NOT_CASTER))
18618 data << uint8(0); // packed GUID of someone (caster?)
18621 if(auraFlags & AFLAG_DURATION) // include aura duration
18623 data << uint32(aura->GetAuraMaxDuration());
18624 data << uint32(aura->GetAuraDuration());
18627 break;
18632 GetSession()->SendPacket(&data);
18635 void Player::SetDailyQuestStatus( uint32 quest_id )
18637 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18639 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18641 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18642 m_lastDailyQuestTime = time(NULL); // last daily quest time
18643 m_DailyQuestChanged = true;
18644 break;
18649 void Player::ResetDailyQuestStatus()
18651 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18652 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18654 // DB data deleted in caller
18655 m_DailyQuestChanged = false;
18656 m_lastDailyQuestTime = 0;
18659 BattleGround* Player::GetBattleGround() const
18661 if(GetBattleGroundId()==0)
18662 return NULL;
18664 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18667 bool Player::InArena() const
18669 BattleGround *bg = GetBattleGround();
18670 if(!bg || !bg->isArena())
18671 return false;
18673 return true;
18676 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18678 // get a template bg instead of running one
18679 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18680 if(!bg)
18681 return false;
18683 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18684 return false;
18686 return true;
18689 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18691 //returned to hardcoded version of this function, because there is no way to code it dynamic
18692 uint32 level = getLevel();
18693 if( bgTypeId == BATTLEGROUND_AV )
18694 level--;
18696 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18697 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18699 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18700 return QUEUE_ID_MAX_LEVEL_80;
18702 return BGQueueIdBasedOnLevel(queue_id);
18705 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18707 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18708 if(!vendor_faction || !vendor_faction->faction)
18709 return 1.0f;
18711 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18712 if(rank <= REP_NEUTRAL)
18713 return 1.0f;
18715 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18718 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18720 uint32 racemask = getRaceMask();
18721 uint32 classmask = getClassMask();
18723 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18724 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18725 if(lower==upper)
18726 return true;
18728 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18730 // skip wrong race skills
18731 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18732 continue;
18734 // skip wrong class skills
18735 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18736 continue;
18738 return true;
18741 return false;
18744 bool Player::HasQuestForGO(int32 GOId) const
18746 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18748 uint32 questid = GetQuestSlotQuestId(i);
18749 if ( questid == 0 )
18750 continue;
18752 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18753 if(qs_itr == mQuestStatus.end())
18754 continue;
18756 QuestStatusData const& qs = qs_itr->second;
18758 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18760 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18761 if(!qinfo)
18762 continue;
18764 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18765 continue;
18767 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18769 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18770 continue;
18772 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18773 return true;
18777 return false;
18780 void Player::UpdateForQuestsGO()
18782 if(m_clientGUIDs.empty())
18783 return;
18785 UpdateData udata;
18786 WorldPacket packet;
18787 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18789 if(IS_GAMEOBJECT_GUID(*itr))
18791 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18792 if(obj)
18793 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18796 udata.BuildPacket(&packet);
18797 GetSession()->SendPacket(&packet);
18800 void Player::SummonIfPossible(bool agree)
18802 if(!agree)
18804 m_summon_expire = 0;
18805 return;
18808 // expire and auto declined
18809 if(m_summon_expire < time(NULL))
18810 return;
18812 // stop taxi flight at summon
18813 if(isInFlight())
18815 GetMotionMaster()->MovementExpired();
18816 m_taxi.ClearTaxiDestinations();
18819 // drop flag at summon
18820 if(BattleGround *bg = GetBattleGround())
18821 bg->EventPlayerDroppedFlag(this);
18823 m_summon_expire = 0;
18825 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18828 void Player::RemoveItemDurations( Item *item )
18830 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18832 if(*itr==item)
18834 m_itemDuration.erase(itr);
18835 break;
18840 void Player::AddItemDurations( Item *item )
18842 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18844 m_itemDuration.push_back(item);
18845 item->SendTimeUpdate(this);
18849 void Player::AutoUnequipOffhandIfNeed()
18851 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18852 if(!offItem)
18853 return;
18855 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18856 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18857 return;
18859 ItemPosCountVec off_dest;
18860 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18861 if( off_msg == EQUIP_ERR_OK )
18863 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18864 StoreItem( off_dest, offItem, true );
18866 else
18868 MailItemsInfo mi;
18869 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18870 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18871 CharacterDatabase.BeginTransaction();
18872 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18873 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18874 CharacterDatabase.CommitTransaction();
18876 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18877 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18881 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18883 if(spellInfo->EquippedItemClass < 0)
18884 return true;
18886 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18887 // for optimize check 2 used cases only
18888 switch(spellInfo->EquippedItemClass)
18890 case ITEM_CLASS_WEAPON:
18892 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18893 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18894 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18895 return true;
18896 break;
18898 case ITEM_CLASS_ARMOR:
18900 // tabard not have dependent spells
18901 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18902 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18903 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18904 return true;
18906 // shields can be equipped to offhand slot
18907 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18908 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18909 return true;
18911 // ranged slot can have some armor subclasses
18912 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18913 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18914 return true;
18916 break;
18918 default:
18919 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18920 break;
18923 return false;
18926 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18928 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18929 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18930 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18931 return true;
18933 // Check no reagent use mask
18934 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18935 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18936 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18937 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18938 return true;
18940 return false;
18943 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18945 AuraMap& auras = GetAuras();
18946 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18948 Aura* aura = itr->second;
18950 // skip passive (passive item dependent spells work in another way) and not self applied auras
18951 SpellEntry const* spellInfo = aura->GetSpellProto();
18952 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18954 ++itr;
18955 continue;
18958 // skip if not item dependent or have alternative item
18959 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18961 ++itr;
18962 continue;
18965 // no alt item, remove aura, restart check
18966 RemoveAurasDueToSpell(aura->GetId());
18967 itr = auras.begin();
18970 // currently casted spells can be dependent from item
18971 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18973 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18974 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18975 InterruptSpell(i);
18979 uint32 Player::GetResurrectionSpellId()
18981 // search priceless resurrection possibilities
18982 uint32 prio = 0;
18983 uint32 spell_id = 0;
18984 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18985 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18987 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18988 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18990 switch((*itr)->GetId())
18992 case 20707: spell_id = 3026; break; // rank 1
18993 case 20762: spell_id = 20758; break; // rank 2
18994 case 20763: spell_id = 20759; break; // rank 3
18995 case 20764: spell_id = 20760; break; // rank 4
18996 case 20765: spell_id = 20761; break; // rank 5
18997 case 27239: spell_id = 27240; break; // rank 6
18998 case 47883: spell_id = 47882; break; // rank 7
18999 default:
19000 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
19001 continue;
19004 prio = 3;
19006 // Twisting Nether // prio: 2 (max)
19007 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19009 prio = 2;
19010 spell_id = 23700;
19014 // Reincarnation (passive spell) // prio: 1
19015 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19016 spell_id = 21169;
19018 return spell_id;
19021 // Used in triggers for check "Only to targets that grant experience or honor" req
19022 bool Player::isHonorOrXPTarget(Unit* pVictim)
19024 uint32 v_level = pVictim->getLevel();
19025 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19027 // Victim level less gray level
19028 if(v_level<=k_grey)
19029 return false;
19031 if(pVictim->GetTypeId() == TYPEID_UNIT)
19033 if (((Creature*)pVictim)->isTotem() ||
19034 ((Creature*)pVictim)->isPet() ||
19035 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19036 return false;
19038 return true;
19041 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19043 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19045 // prepare data for near group iteration (PvP and !PvP cases)
19046 uint32 xp = 0;
19047 bool honored_kill = false;
19049 if(Group *pGroup = GetGroup())
19051 uint32 count = 0;
19052 uint32 sum_level = 0;
19053 Player* member_with_max_level = NULL;
19054 Player* not_gray_member_with_max_level = NULL;
19056 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19058 if(member_with_max_level)
19060 /// not get Xp in PvP or no not gray players in group
19061 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19063 /// skip in check PvP case (for speed, not used)
19064 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19065 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19066 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19068 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19070 Player* pGroupGuy = itr->getSource();
19071 if(!pGroupGuy)
19072 continue;
19074 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19075 continue; // member (alive or dead) or his corpse at req. distance
19077 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19078 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19079 honored_kill = true;
19081 // xp and reputation only in !PvP case
19082 if(!PvP)
19084 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19086 // if is in dungeon then all receive full reputation at kill
19087 // rewarded any alive/dead/near_corpse group member
19088 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19090 // XP updated only for alive group member
19091 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19092 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19094 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19096 pGroupGuy->GiveXP(itr_xp, pVictim);
19097 if(Pet* pet = pGroupGuy->GetPet())
19098 pet->GivePetXP(itr_xp/2);
19101 // quest objectives updated only for alive group member or dead but with not released body
19102 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19104 // normal creature (not pet/etc) can be only in !PvP case
19105 if(pVictim->GetTypeId()==TYPEID_UNIT)
19106 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
19112 else // if (!pGroup)
19114 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19116 // honor can be in PvP and !PvP (racial leader) cases
19117 if(RewardHonor(pVictim,1))
19118 honored_kill = true;
19120 // xp and reputation only in !PvP case
19121 if(!PvP)
19123 RewardReputation(pVictim,1);
19124 GiveXP(xp, pVictim);
19126 if(Pet* pet = GetPet())
19127 pet->GivePetXP(xp);
19129 // normal creature (not pet/etc) can be only in !PvP case
19130 if(pVictim->GetTypeId()==TYPEID_UNIT)
19131 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
19134 return xp || honored_kill;
19137 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19139 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
19140 return true;
19142 if(isAlive())
19143 return false;
19145 Corpse* corpse = GetCorpse();
19146 if(!corpse)
19147 return false;
19149 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
19152 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19154 Item* item = GetWeaponForAttack(attType,true);
19156 // unarmed only with base attack
19157 if(attType != BASE_ATTACK && !item)
19158 return 0;
19160 // weapon skill or (unarmed for base attack)
19161 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
19162 return GetBaseSkillValue(skill);
19165 void Player::ResurectUsingRequestData()
19167 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
19168 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19170 ResurrectPlayer(0.0f,false);
19172 if(GetMaxHealth() > m_resurrectHealth)
19173 SetHealth( m_resurrectHealth );
19174 else
19175 SetHealth( GetMaxHealth() );
19177 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19178 SetPower(POWER_MANA, m_resurrectMana );
19179 else
19180 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19182 SetPower(POWER_RAGE, 0 );
19184 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19186 SpawnCorpseBones();
19189 void Player::SetClientControl(Unit* target, uint8 allowMove)
19191 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19192 data.append(target->GetPackGUID());
19193 data << uint8(allowMove);
19194 GetSession()->SendPacket(&data);
19197 void Player::UpdateZoneDependentAuras( uint32 newZone )
19199 // remove new continent flight forms
19200 if( !IsAllowUseFlyMountsHere() )
19202 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
19203 RemoveSpellsCausingAura(SPELL_AURA_FLY);
19206 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19207 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
19208 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19209 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19210 if( !HasAura(itr->second->spellId,0) )
19211 CastSpell(this,itr->second->spellId,true);
19214 void Player::UpdateAreaDependentAuras( uint32 newArea )
19216 // remove auras from spells with area limitations
19217 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19219 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19220 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this)!=0)
19221 RemoveAura(iter);
19222 else
19223 ++iter;
19226 // some auras applied at subzone enter
19227 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
19228 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19229 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19230 if( !HasAura(itr->second->spellId,0) )
19231 CastSpell(this,itr->second->spellId,true);
19234 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19236 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19237 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19239 return copseReclaimDelay[0];
19242 time_t now = time(NULL);
19243 // 0..2 full period
19244 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19245 return copseReclaimDelay[count];
19248 void Player::UpdateCorpseReclaimDelay()
19250 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19252 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19253 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19254 return;
19256 time_t now = time(NULL);
19257 if(now < m_deathExpireTime)
19259 // full and partly periods 1..3
19260 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19261 if(count < MAX_DEATH_COUNT)
19262 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19263 else
19264 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19266 else
19267 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19270 void Player::SendCorpseReclaimDelay(bool load)
19272 Corpse* corpse = GetCorpse();
19273 if(!corpse)
19274 return;
19276 uint32 delay;
19277 if(load)
19279 if(corpse->GetGhostTime() > m_deathExpireTime)
19280 return;
19282 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19284 uint32 count;
19285 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19286 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19288 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19289 if(count>=MAX_DEATH_COUNT)
19290 count = MAX_DEATH_COUNT-1;
19292 else
19293 count=0;
19295 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19297 time_t now = time(NULL);
19298 if(now >= expected_time)
19299 return;
19301 delay = expected_time-now;
19303 else
19304 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19306 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19307 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19308 data << uint32(delay*IN_MILISECONDS);
19309 GetSession()->SendPacket( &data );
19312 Player* Player::GetNextRandomRaidMember(float radius)
19314 Group *pGroup = GetGroup();
19315 if(!pGroup)
19316 return NULL;
19318 std::vector<Player*> nearMembers;
19319 nearMembers.reserve(pGroup->GetMembersCount());
19321 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19323 Player* Target = itr->getSource();
19325 // IsHostileTo check duel and controlled by enemy
19326 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19327 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19328 nearMembers.push_back(Target);
19331 if (nearMembers.empty())
19332 return NULL;
19334 uint32 randTarget = urand(0,nearMembers.size()-1);
19335 return nearMembers[randTarget];
19338 PartyResult Player::CanUninviteFromGroup() const
19340 const Group* grp = GetGroup();
19341 if(!grp)
19342 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19344 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19345 return PARTY_RESULT_YOU_NOT_LEADER;
19347 if(InBattleGround())
19348 return PARTY_RESULT_INVITE_RESTRICTED;
19350 return PARTY_RESULT_OK;
19353 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19355 float water_z = m->GetWaterLevel(x,y);
19356 float terrain_z = m->GetHeight(x,y,z, false); // use .map base surface height
19357 uint8 flag1 = m->GetTerrainType(x,y);
19359 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19360 if (terrain_z <= INVALID_HEIGHT || z < (terrain_z-2) || z > (water_z - 2) )
19361 m_isunderwater &= ~UNDERWATER_INWATER;
19362 else if ((z < (water_z - 2)) && (flag1 & 0x01))
19363 m_isunderwater |= UNDERWATER_INWATER;
19365 //!in lava check, anywhere under lava level
19366 if ((terrain_z <= INVALID_HEIGHT || z < (terrain_z - 0)) && (flag1 == 0x00) && IsInWater())
19367 m_isunderwater |= UNDERWATER_INLAVA;
19368 else
19369 m_isunderwater &= ~UNDERWATER_INLAVA;
19372 void Player::SetCanParry( bool value )
19374 if(m_canParry==value)
19375 return;
19377 m_canParry = value;
19378 UpdateParryPercentage();
19381 void Player::SetCanBlock( bool value )
19383 if(m_canBlock==value)
19384 return;
19386 m_canBlock = value;
19387 UpdateBlockPercentage();
19390 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19392 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19393 if(itr->pos == pos)
19394 return true;
19396 return false;
19399 bool Player::isAllowUseBattleGroundObject()
19401 return ( //InBattleGround() && // in battleground - not need, check in other cases
19402 !IsMounted() && // not mounted
19403 !HasStealthAura() && // not stealthed
19404 !HasInvisibilityAura() && // not invisible
19405 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19406 isAlive() // live player
19410 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19412 uint32 level = getLevel();
19414 if(level > GT_MAX_LEVEL)
19415 level = GT_MAX_LEVEL; // max level in this dbc
19417 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19418 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19419 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19421 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19422 return 0;
19424 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19426 if(!bsc) // shouldn't happen
19427 return 0xFFFFFFFF;
19429 float cost = 0;
19431 if(hairstyle != newhairstyle)
19432 cost += bsc->cost; // full price
19434 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19435 cost += bsc->cost * 0.5f; // +1/2 of price
19437 if(facialhair != newfacialhair)
19438 cost += bsc->cost * 0.75f; // +3/4 of price
19440 return uint32(cost);
19443 void Player::InitGlyphsForLevel()
19445 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19446 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19447 if(gs->Order)
19448 SetGlyphSlot(gs->Order - 1, gs->Id);
19450 uint32 level = getLevel();
19451 uint32 value = 0;
19453 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19454 if(level >= 15)
19455 value |= (0x01 | 0x02);
19456 if(level >= 30)
19457 value |= 0x08;
19458 if(level >= 50)
19459 value |= 0x04;
19460 if(level >= 70)
19461 value |= 0x10;
19462 if(level >= 80)
19463 value |= 0x20;
19465 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19468 void Player::EnterVehicle(Vehicle *vehicle)
19470 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19471 if(!ve)
19472 return;
19474 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19475 if(!veSeat)
19476 return;
19478 vehicle->SetCharmerGUID(GetGUID());
19479 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19480 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19481 vehicle->setFaction(getFaction());
19483 SetCharm(vehicle); // charm
19484 SetFarSightGUID(vehicle->GetGUID()); // set view
19486 SetClientControl(vehicle, 1); // redirect controls to vehicle
19488 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19489 GetSession()->SendPacket(&data);
19491 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19492 data.append(GetPackGUID());
19493 data << uint32(0); // counter?
19494 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19495 data << uint16(0); // special flags
19496 data << uint32(getMSTime()); // time
19497 data << vehicle->GetPositionX(); // x
19498 data << vehicle->GetPositionY(); // y
19499 data << vehicle->GetPositionZ(); // z
19500 data << vehicle->GetOrientation(); // o
19501 // transport part, TODO: load/calculate seat offsets
19502 data << uint64(vehicle->GetGUID()); // transport guid
19503 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19504 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19505 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19506 data << float(0); // transport orientation
19507 data << uint32(getMSTime()); // transport time
19508 data << uint8(0); // seat
19509 // end of transport part
19510 data << uint32(0); // fall time
19511 GetSession()->SendPacket(&data);
19513 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19514 data << uint64(vehicle->GetGUID());
19515 data << uint32(0x00000000);
19516 data << uint32(0x00000000);
19517 data << uint32(0x00000101);
19519 for(uint32 i = 0; i < 10; ++i)
19520 data << uint16(0) << uint8(0) << uint8(i+8);
19522 data << uint8(0);
19523 data << uint8(0);
19524 GetSession()->SendPacket(&data);
19527 void Player::ExitVehicle(Vehicle *vehicle)
19529 vehicle->SetCharmerGUID(0);
19530 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19531 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19532 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19534 SetCharm(NULL);
19535 SetFarSightGUID(0);
19537 SetClientControl(vehicle, 0);
19539 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19540 data.append(GetPackGUID());
19541 data << uint32(0); // counter?
19542 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19543 data << uint16(0x40); // special flags
19544 data << uint32(getMSTime()); // time
19545 data << vehicle->GetPositionX(); // x
19546 data << vehicle->GetPositionY(); // y
19547 data << vehicle->GetPositionZ(); // z
19548 data << vehicle->GetOrientation(); // o
19549 data << uint32(0); // fall time
19550 GetSession()->SendPacket(&data);
19552 data.Initialize(SMSG_PET_SPELLS, 8+4);
19553 data << uint64(0);
19554 data << uint32(0);
19555 GetSession()->SendPacket(&data);
19557 // only for flyable vehicles?
19558 CastSpell(this, 45472, true); // Parachute
19561 bool Player::HasTitle(uint32 bitIndex)
19563 if (bitIndex > 128)
19564 return false;
19566 uint32 fieldIndexOffset = bitIndex/32;
19567 uint32 flag = 1 << (bitIndex%32);
19568 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19571 void Player::SetTitle(CharTitlesEntry const* title)
19573 uint32 fieldIndexOffset = title->bit_index/32;
19574 uint32 flag = 1 << (title->bit_index%32);
19575 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19578 void Player::ConvertRune(uint8 index, uint8 newType)
19580 SetCurrentRune(index, newType);
19582 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19583 data << uint8(index);
19584 data << uint8(newType);
19585 GetSession()->SendPacket(&data);
19588 void Player::ResyncRunes(uint8 count)
19590 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19591 for(uint32 i = 0; i < count; ++i)
19593 data << uint8(GetCurrentRune(i)); // rune type
19594 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19596 GetSession()->SendPacket(&data);
19599 void Player::AddRunePower(uint8 index)
19601 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19602 data << uint32(1 << index); // mask (0x00-0x3F probably)
19603 GetSession()->SendPacket(&data);
19606 void Player::InitRunes()
19608 if(getClass() != CLASS_DEATH_KNIGHT)
19609 return;
19611 m_runes = new Runes;
19613 m_runes->runeState = 0;
19615 for(uint32 i = 0; i < MAX_RUNES; ++i)
19617 SetBaseRune(i, i / 2); // init base types
19618 SetCurrentRune(i, i / 2); // init current types
19619 SetRuneCooldown(i, 0); // reset cooldowns
19620 m_runes->SetRuneState(i);
19623 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19624 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19627 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19629 Loot loot;
19630 loot.FillLoot (loot_id,store,this,true);
19632 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19633 for(uint32 i = 0; i < max_slot; ++i)
19635 LootItem* lootItem = loot.LootItemInSlot(i,this);
19637 ItemPosCountVec dest;
19638 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19639 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19640 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19641 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19642 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19643 if(msg != EQUIP_ERR_OK)
19645 SendEquipError( msg, NULL, NULL );
19646 continue;
19649 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19650 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19654 uint32 Player::CalculateTalentsPoints() const
19656 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19658 if(getClass() != CLASS_DEATH_KNIGHT)
19659 return base_talent;
19661 uint32 talentPointsForLevel =
19662 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19663 + m_questRewardTalentCount;
19665 if(talentPointsForLevel > base_talent)
19666 talentPointsForLevel = base_talent;
19668 return talentPointsForLevel;
19671 bool Player::IsAllowUseFlyMountsHere() const
19673 if (isGameMaster())
19674 return true;
19676 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19677 return v_map == 530 || v_map == 571 && HasSpell(54197);
19680 void Player::learnSpellHighRank(uint32 spellid)
19682 learnSpell(spellid,false);
19684 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19685 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19686 learnSpellHighRank(itr->second);
19689 void Player::_LoadSkills()
19691 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19693 // reset skill modifiers and set correct unlearn flags
19694 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
19696 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19698 // set correct unlearn bit
19699 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19700 if(!id) continue;
19702 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19703 if(!pSkill) continue;
19705 // enable unlearn button for primary professions only
19706 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19707 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19708 else
19709 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19711 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19713 learnSkillRewardedSpells(id, vskill);
19716 // special settings
19717 if(getClass()==CLASS_DEATH_KNIGHT)
19719 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19720 if(base_level < 1)
19721 base_level = 1;
19722 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19723 if(base_skill < 1)
19724 base_skill = 1; // skill mast be known and then > 0 in any case
19726 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19727 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19728 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19729 SetSkill(SKILL_AXES, base_skill,base_skill);
19730 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19731 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19732 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19733 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19734 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19735 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19736 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19737 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19738 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19739 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19740 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19741 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19745 uint32 Player::GetPhaseMaskForSpawn() const
19747 uint32 phase = PHASEMASK_NORMAL;
19748 if(!isGameMaster())
19749 phase = GetPhaseMask();
19750 else
19752 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19753 if(!phases.empty())
19754 phase = phases.front()->GetMiscValue();
19757 // some aura phases include 1 normal map in addition to phase itself
19758 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19759 return n_phase;
19761 return PHASEMASK_NORMAL;
19764 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19766 ItemPrototype const* pProto = pItem->GetProto();
19768 // proto based limitations
19769 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19770 return res;
19772 // check unique-equipped on gems
19773 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19775 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19776 if(!enchant_id)
19777 continue;
19778 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19779 if(!enchantEntry)
19780 continue;
19782 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19783 if(!pGem)
19784 continue;
19786 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19787 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19788 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19790 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19791 return res;
19794 return EQUIP_ERR_OK;
19797 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19799 // check unique-equipped on item
19800 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19802 // there is an equip limit on this item
19803 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19804 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19807 // check unique-equipped limit
19808 if (itemProto->ItemLimitCategory)
19810 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19811 if(!limitEntry)
19812 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19814 if(limit_count > limitEntry->maxCount)
19815 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19817 // there is an equip limit on this item
19818 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19819 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19822 return EQUIP_ERR_OK;
19825 void Player::HandleFall(MovementInfo const& movementInfo)
19827 // calculate total z distance of the fall
19828 float z_diff = m_lastFallZ - movementInfo.z;
19829 sLog.outDebug("zDiff = %f", z_diff);
19831 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19832 // 14.57 can be calculated by resolving damageperc formular below to 0
19833 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19834 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19835 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19837 //Safe fall, fall height reduction
19838 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19840 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19842 if(damageperc >0 )
19844 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19846 float height = movementInfo.z;
19847 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19849 if (damage > 0)
19851 //Prevent fall damage from being more than the player maximum health
19852 if (damage > GetMaxHealth())
19853 damage = GetMaxHealth();
19855 // Gust of Wind
19856 if (GetDummyAura(43621))
19857 damage = GetMaxHealth()/2;
19859 EnvironmentalDamage(GetGUID(), DAMAGE_FALL, damage);
19861 // recheck alive, might have died of EnvironmentalDamage
19862 if (isAlive())
19863 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19866 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19867 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.z, height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
19872 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19874 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);