[7780] Fixed Player::HasGuardianWithEntry()
[getmangos.git] / src / game / Player.cpp
blob1d9e859b6b09d9f77e18d6724235e0e68ef9cf98
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 "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.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 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 for ( int aX = 0 ; aX < 8 ; aX++ )
350 m_Tutorials[ aX ] = 0x00;
351 m_TutorialsChanged = false;
353 m_DailyQuestChanged = false;
354 m_lastDailyQuestTime = 0;
356 for (int i=0; i<MAX_TIMERS; ++i)
357 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
359 m_MirrorTimerFlags = UNDERWATER_NONE;
360 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
361 m_isInWater = false;
362 m_drunkTimer = 0;
363 m_drunk = 0;
364 m_restTime = 0;
365 m_deathTimer = 0;
366 m_deathExpireTime = 0;
368 m_swingErrorMsg = 0;
370 m_DetectInvTimer = 1*IN_MILISECONDS;
372 m_bgBattleGroundID = 0;
373 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
374 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
376 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
377 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
379 m_bgTeam = 0;
381 m_logintime = time(NULL);
382 m_Last_tick = m_logintime;
383 m_WeaponProficiency = 0;
384 m_ArmorProficiency = 0;
385 m_canParry = false;
386 m_canBlock = false;
387 m_canDualWield = false;
388 m_canTitanGrip = false;
389 m_ammoDPS = 0.0f;
391 m_temporaryUnsummonedPetNumber = 0;
392 //cache for UNIT_CREATED_BY_SPELL to allow
393 //returning reagents for temporarily removed pets
394 //when dying/logging out
395 m_oldpetspell = 0;
397 ////////////////////Rest System/////////////////////
398 time_inn_enter=0;
399 inn_pos_mapid=0;
400 inn_pos_x=0;
401 inn_pos_y=0;
402 inn_pos_z=0;
403 m_rest_bonus=0;
404 rest_type=REST_TYPE_NO;
405 ////////////////////Rest System/////////////////////
407 m_mailsLoaded = false;
408 m_mailsUpdated = false;
409 unReadMails = 0;
410 m_nextMailDelivereTime = 0;
412 m_resetTalentsCost = 0;
413 m_resetTalentsTime = 0;
414 m_itemUpdateQueueBlocked = false;
416 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
417 m_forced_speed_changes[i] = 0;
419 m_stableSlots = 0;
421 /////////////////// Instance System /////////////////////
423 m_HomebindTimer = 0;
424 m_InstanceValid = true;
425 m_dungeonDifficulty = DIFFICULTY_NORMAL;
427 m_lastPotionId = 0;
429 for (int i = 0; i < BASEMOD_END; ++i)
431 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
432 m_auraBaseMod[i][PCT_MOD] = 1.0f;
435 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
436 m_baseRatingValue[i] = 0;
438 m_baseSpellDamage = 0;
439 m_baseSpellHealing = 0;
440 m_baseFeralAP = 0;
441 m_baseManaRegen = 0;
443 // Honor System
444 m_lastHonorUpdateTime = time(NULL);
446 // Player summoning
447 m_summon_expire = 0;
448 m_summon_mapid = 0;
449 m_summon_x = 0.0f;
450 m_summon_y = 0.0f;
451 m_summon_z = 0.0f;
453 //Default movement to run mode
454 m_unit_movement_flags = 0;
456 m_mover = this;
458 m_miniPet = 0;
459 m_bgAfkReportedTimer = 0;
460 m_contestedPvPTimer = 0;
462 m_declinedname = NULL;
463 m_runes = NULL;
465 m_lastFallTime = 0;
466 m_lastFallZ = 0;
469 Player::~Player ()
471 CleanupsBeforeDelete();
473 // it must be unloaded already in PlayerLogout and accessed only for loggined player
474 //m_social = NULL;
476 // Note: buy back item already deleted from DB when player was saved
477 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
479 if(m_items[i])
480 delete m_items[i];
482 CleanupChannels();
484 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
485 delete itr->second;
487 //all mailed items should be deleted, also all mail should be deallocated
488 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
489 delete *itr;
491 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
492 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
494 delete PlayerTalkClass;
496 if (m_transport)
498 m_transport->RemovePassenger(this);
501 for(size_t x = 0; x < ItemSetEff.size(); x++)
502 if(ItemSetEff[x])
503 delete ItemSetEff[x];
505 // clean up player-instance binds, may unload some instance saves
506 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
507 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
508 itr->second.save->RemovePlayer(this);
510 delete m_declinedname;
511 delete m_runes;
514 void Player::CleanupsBeforeDelete()
516 if(m_uint32Values) // only for fully created Object
518 TradeCancel(false);
519 DuelComplete(DUEL_INTERUPTED);
521 Unit::CleanupsBeforeDelete();
524 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
526 //FIXME: outfitId not used in player creating
528 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
530 m_name = name;
532 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
533 if(!info)
535 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
536 return false;
539 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
540 m_items[i] = NULL;
542 m_race = race;
543 m_class = class_;
545 SetMapId(info->mapId);
546 Relocate(info->positionX,info->positionY,info->positionZ);
548 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
549 if(!cEntry)
551 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
552 return false;
555 uint8 powertype = cEntry->powerType;
557 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
558 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
560 switch(gender)
562 case GENDER_FEMALE:
563 SetDisplayId(info->displayId_f );
564 SetNativeDisplayId(info->displayId_f );
565 break;
566 case GENDER_MALE:
567 SetDisplayId(info->displayId_m );
568 SetNativeDisplayId(info->displayId_m );
569 break;
570 default:
571 sLog.outError("Invalid gender %u for player",gender);
572 return false;
573 break;
576 setFactionForRace(m_race);
578 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
580 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
581 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
582 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
583 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
584 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
585 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
587 // -1 is default value
588 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
590 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
591 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
592 SetByteValue(PLAYER_BYTES_3, 0, gender);
594 SetUInt32Value( PLAYER_GUILDID, 0 );
595 SetUInt32Value( PLAYER_GUILDRANK, 0 );
596 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
606 // set starting level
607 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
609 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
613 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
614 if(gm_level > start_level)
615 start_level = gm_level;
618 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
620 InitRunes();
622 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
626 // Played time
627 m_Last_tick = time(NULL);
628 m_Played_time[0] = 0;
629 m_Played_time[1] = 0;
631 // base stats and related field values
632 InitStatsForLevel();
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProffesions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
850 data << uint64(GetGUID());
851 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
852 data << uint32(damage);
853 data << uint32(absorb);
854 data << uint32(resist);
855 SendMessageToSet(&data, true);
857 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
859 if(!isAlive())
861 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
863 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
864 DurabilityLossAll(0.10f,false);
865 // durability lost message
866 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
867 GetSession()->SendPacket(&data2);
870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
874 int32 Player::getMaxTimer(MirrorTimerType timer)
876 switch (timer)
878 case FATIGUE_TIMER:
879 return MINUTE*IN_MILISECONDS;
880 case BREATH_TIMER:
882 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
883 return DISABLED_MIRROR_TIMER;
884 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
885 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
886 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
887 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
888 return UnderWaterTime;
890 case FIRE_TIMER:
892 if (!isAlive())
893 return DISABLED_MIRROR_TIMER;
894 return 1*IN_MILISECONDS;
896 default:
897 return 0;
899 return 0;
902 void Player::UpdateMirrorTimers()
904 // Desync flags for update on next HandleDrowning
905 if (m_MirrorTimerFlags)
906 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
909 void Player::HandleDrowning(uint32 time_diff)
911 if (!m_MirrorTimerFlags)
912 return;
914 // In water
915 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
917 // Breath timer not activated - activate it
918 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
920 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
921 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
923 else // If activated - do tick
925 m_MirrorTimer[BREATH_TIMER]-=time_diff;
926 // Timer limit - need deal damage
927 if (m_MirrorTimer[BREATH_TIMER] < 0)
929 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
930 // Calculate and deal damage
931 // TODO: Check this formula
932 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
933 EnvironmentalDamage(DAMAGE_DROWNING, damage);
935 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
936 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
939 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
941 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
942 // Need breath regen
943 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
944 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
945 StopMirrorTimer(BREATH_TIMER);
946 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
947 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
950 // In dark water
951 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
953 // Fatigue timer not activated - activate it
954 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
956 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
957 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
959 else
961 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
962 // Timer limit - need deal damage or teleport ghost to graveyard
963 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
965 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
966 if (isAlive()) // Calculate and deal damage
968 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
969 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
971 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
972 RepopAtGraveyard();
974 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
975 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
978 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
980 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
981 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
982 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
983 StopMirrorTimer(FATIGUE_TIMER);
984 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
985 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
988 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
990 // Breath timer not activated - activate it
991 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
992 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
993 else
995 m_MirrorTimer[FIRE_TIMER]-=time_diff;
996 if (m_MirrorTimer[FIRE_TIMER] < 0)
998 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
999 // Calculate and deal damage
1000 // TODO: Check this formula
1001 uint32 damage = urand(600, 700);
1002 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1003 EnvironmentalDamage(DAMAGE_LAVA, damage);
1004 else
1005 EnvironmentalDamage(DAMAGE_SLIME, damage);
1009 else
1010 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1012 // Recheck timers flag
1013 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1014 for (int i = 0; i< MAX_TIMERS; ++i)
1015 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1017 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1018 break;
1020 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1023 ///The player sobers by 256 every 10 seconds
1024 void Player::HandleSobering()
1026 m_drunkTimer = 0;
1028 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1029 SetDrunkValue(drunk);
1032 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1034 if(value >= 23000)
1035 return DRUNKEN_SMASHED;
1036 if(value >= 12800)
1037 return DRUNKEN_DRUNK;
1038 if(value & 0xFFFE)
1039 return DRUNKEN_TIPSY;
1040 return DRUNKEN_SOBER;
1043 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1045 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1047 m_drunk = newDrunkenValue;
1048 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1050 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1052 // special drunk invisibility detection
1053 if(newDrunkenState >= DRUNKEN_DRUNK)
1054 m_detectInvisibilityMask |= (1<<6);
1055 else
1056 m_detectInvisibilityMask &= ~(1<<6);
1058 if(newDrunkenState == oldDrunkenState)
1059 return;
1061 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1062 data << uint64(GetGUID());
1063 data << uint32(newDrunkenState);
1064 data << uint32(itemId);
1066 SendMessageToSet(&data, true);
1069 void Player::Update( uint32 p_time )
1071 if(!IsInWorld())
1072 return;
1074 // undelivered mail
1075 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1077 SendNewMail();
1078 ++unReadMails;
1080 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1081 m_nextMailDelivereTime = 0;
1084 Unit::Update( p_time );
1086 // update player only attacks
1087 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1089 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1092 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1094 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1097 time_t now = time (NULL);
1099 UpdatePvPFlag(now);
1101 UpdateContestedPvP(p_time);
1103 UpdateDuelFlag(now);
1105 CheckDuelDistance(now);
1107 UpdateAfkReport(now);
1109 // Update items that have just a limited lifetime
1110 if (now>m_Last_tick)
1111 UpdateItemDuration(uint32(now- m_Last_tick));
1113 if (!m_timedquests.empty())
1115 std::set<uint32>::iterator iter = m_timedquests.begin();
1116 while (iter != m_timedquests.end())
1118 QuestStatusData& q_status = mQuestStatus[*iter];
1119 if( q_status.m_timer <= p_time )
1121 uint32 quest_id = *iter;
1122 ++iter; // current iter will be removed in FailTimedQuest
1123 FailTimedQuest( quest_id );
1125 else
1127 q_status.m_timer -= p_time;
1128 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1129 ++iter;
1134 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1136 Unit *pVictim = getVictim();
1137 if (pVictim && !IsNonMeleeSpellCasted(false))
1139 // default combat reach 10
1140 // TODO add weapon,skill check
1142 float pldistance = ATTACK_DISTANCE;
1144 if (isAttackReady(BASE_ATTACK))
1146 if(!IsWithinDistInMap(pVictim, pldistance))
1148 setAttackTimer(BASE_ATTACK,100);
1149 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1151 SendAttackSwingNotInRange();
1152 m_swingErrorMsg = 1;
1155 //120 degrees of radiant range
1156 else if( !HasInArc( 2*M_PI/3, pVictim ))
1158 setAttackTimer(BASE_ATTACK,100);
1159 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1161 SendAttackSwingBadFacingAttack();
1162 m_swingErrorMsg = 2;
1165 else
1167 m_swingErrorMsg = 0; // reset swing error state
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 if(haveOffhandWeapon())
1172 uint32 off_att = getAttackTimer(OFF_ATTACK);
1173 if(off_att < ATTACK_DISPLAY_DELAY)
1174 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1176 AttackerStateUpdate(pVictim, BASE_ATTACK);
1177 resetAttackTimer(BASE_ATTACK);
1181 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1183 if(!IsWithinDistInMap(pVictim, pldistance))
1185 setAttackTimer(OFF_ATTACK,100);
1187 else if( !HasInArc( 2*M_PI/3, pVictim ))
1189 setAttackTimer(OFF_ATTACK,100);
1191 else
1193 // prevent base and off attack in same time, delay attack at 0.2 sec
1194 uint32 base_att = getAttackTimer(BASE_ATTACK);
1195 if(base_att < ATTACK_DISPLAY_DELAY)
1196 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1197 // do attack
1198 AttackerStateUpdate(pVictim, OFF_ATTACK);
1199 resetAttackTimer(OFF_ATTACK);
1203 Unit *owner = pVictim->GetOwner();
1204 Unit *u = owner ? owner : pVictim;
1205 if(u->IsPvP() && (!duel || duel->opponent != u))
1207 UpdatePvP(true);
1208 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1213 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1215 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1217 int time_inn = time(NULL)-GetTimeInnEnter();
1218 if (time_inn >= 10) //freeze update
1220 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1221 //speed collect rest bonus (section/in hour)
1222 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1223 UpdateInnerTime(time(NULL));
1228 if(m_regenTimer > 0)
1230 if(p_time >= m_regenTimer)
1231 m_regenTimer = 0;
1232 else
1233 m_regenTimer -= p_time;
1236 if (m_weaponChangeTimer > 0)
1238 if(p_time >= m_weaponChangeTimer)
1239 m_weaponChangeTimer = 0;
1240 else
1241 m_weaponChangeTimer -= p_time;
1244 if (m_zoneUpdateTimer > 0)
1246 if(p_time >= m_zoneUpdateTimer)
1248 uint32 newzone, newarea;
1249 GetZoneAndAreaId(newzone,newarea);
1251 if( m_zoneUpdateId != newzone )
1252 UpdateZone(newzone,newarea); // also update area
1253 else
1255 // use area updates as well
1256 // needed for free far all arenas for example
1257 if( m_areaUpdateId != newarea )
1258 UpdateArea(newarea);
1260 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1263 else
1264 m_zoneUpdateTimer -= p_time;
1267 if (isAlive())
1269 RegenerateAll();
1272 if (m_deathState == JUST_DIED)
1274 KillPlayer();
1277 if(m_nextSave > 0)
1279 if(p_time >= m_nextSave)
1281 // m_nextSave reseted in SaveToDB call
1282 SaveToDB();
1283 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1285 else
1287 m_nextSave -= p_time;
1291 //Handle Water/drowning
1292 HandleDrowning(p_time);
1294 //Handle detect stealth players
1295 if (m_DetectInvTimer > 0)
1297 if (p_time >= m_DetectInvTimer)
1299 m_DetectInvTimer = 3000;
1300 HandleStealthedUnitsDetection();
1302 else
1303 m_DetectInvTimer -= p_time;
1306 // Played time
1307 if (now > m_Last_tick)
1309 uint32 elapsed = uint32(now - m_Last_tick);
1310 m_Played_time[0] += elapsed; // Total played time
1311 m_Played_time[1] += elapsed; // Level played time
1312 m_Last_tick = now;
1315 if (m_drunk)
1317 m_drunkTimer += p_time;
1319 if (m_drunkTimer > 10*IN_MILISECONDS)
1320 HandleSobering();
1323 // not auto-free ghost from body in instances
1324 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1326 if(p_time >= m_deathTimer)
1328 m_deathTimer = 0;
1329 BuildPlayerRepop();
1330 RepopAtGraveyard();
1332 else
1333 m_deathTimer -= p_time;
1336 UpdateEnchantTime(p_time);
1337 UpdateHomebindTime(p_time);
1339 // group update
1340 SendUpdateToOutOfRangeGroupMembers();
1342 Pet* pet = GetPet();
1343 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1345 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1346 return;
1350 void Player::setDeathState(DeathState s)
1352 uint32 ressSpellId = 0;
1354 bool cur = isAlive();
1356 if(s == JUST_DIED && cur)
1358 // drunken state is cleared on death
1359 SetDrunkValue(0);
1360 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1361 ClearComboPoints();
1363 clearResurrectRequestData();
1365 // remove form before other mods to prevent incorrect stats calculation
1366 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1368 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1369 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1371 // remove uncontrolled pets
1372 RemoveMiniPet();
1373 RemoveGuardians();
1375 // save value before aura remove in Unit::setDeathState
1376 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1378 // passive spell
1379 if(!ressSpellId)
1380 ressSpellId = GetResurrectionSpellId();
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1385 Unit::setDeathState(s);
1387 // restore resurrection spell id for player after aura remove
1388 if(s == JUST_DIED && cur && ressSpellId)
1389 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1391 if(isAlive() && !cur)
1393 //clear aura case after resurrection by another way (spells will be applied before next death)
1394 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1396 // restore default warrior stance
1397 if(getClass()== CLASS_WARRIOR)
1398 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1402 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1404 Field *fields = result->Fetch();
1406 *p_data << uint64(GetGUID());
1407 *p_data << m_name;
1409 *p_data << uint8(getRace());
1410 uint8 pClass = getClass();
1411 *p_data << uint8(pClass);
1412 *p_data << uint8(getGender());
1414 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1415 *p_data << uint8(bytes);
1416 *p_data << uint8(bytes >> 8);
1417 *p_data << uint8(bytes >> 16);
1418 *p_data << uint8(bytes >> 24);
1420 bytes = GetUInt32Value(PLAYER_BYTES_2);
1421 *p_data << uint8(bytes);
1423 *p_data << uint8(getLevel()); // player level
1424 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1425 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1426 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1427 *p_data << uint32(zoneId);
1428 *p_data << uint32(GetMapId());
1430 *p_data << GetPositionX();
1431 *p_data << GetPositionY();
1432 *p_data << GetPositionZ();
1434 // guild id
1435 *p_data << (result ? fields[13].GetUInt32() : 0);
1437 uint32 char_flags = 0;
1438 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1439 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1440 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1441 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1442 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1443 char_flags |= CHARACTER_FLAG_GHOST;
1444 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1445 char_flags |= CHARACTER_FLAG_RENAME;
1446 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1447 char_flags |= CHARACTER_FLAG_DECLINED;
1449 *p_data << uint32(char_flags); // character flags
1450 // character customize (flags?)
1451 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1452 *p_data << uint8(1); // unknown
1454 // Pets info
1456 uint32 petDisplayId = 0;
1457 uint32 petLevel = 0;
1458 uint32 petFamily = 0;
1460 // show pet at selection character in character list only for non-ghost character
1461 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1463 uint32 entry = fields[10].GetUInt32();
1464 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1465 if(cInfo)
1467 petDisplayId = fields[11].GetUInt32();
1468 petLevel = fields[12].GetUInt32();
1469 petFamily = cInfo->family;
1473 *p_data << uint32(petDisplayId);
1474 *p_data << uint32(petLevel);
1475 *p_data << uint32(petFamily);
1478 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1480 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1481 uint32 item_id = GetUInt32Value(visualbase);
1482 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1483 SpellItemEnchantmentEntry const *enchant = NULL;
1485 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1487 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1488 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1489 break;
1492 if (proto != NULL)
1494 *p_data << uint32(proto->DisplayInfoID);
1495 *p_data << uint8(proto->InventoryType);
1496 *p_data << uint32(enchant ? enchant->aura_id : 0);
1498 else
1500 *p_data << uint32(0);
1501 *p_data << uint8(0);
1502 *p_data << uint32(0); // enchant?
1505 *p_data << uint32(0); // first bag display id
1506 *p_data << uint8(0); // first bag inventory type
1507 *p_data << uint32(0); // enchant?
1510 bool Player::ToggleAFK()
1512 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1514 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1516 // afk player not allowed in battleground
1517 if(state && InBattleGround())
1518 LeaveBattleground();
1520 return state;
1523 bool Player::ToggleDND()
1525 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1527 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1530 uint8 Player::chatTag() const
1532 // it's bitmask
1533 // 0x8 - ??
1534 // 0x4 - gm
1535 // 0x2 - dnd
1536 // 0x1 - afk
1537 if(isGMChat())
1538 return 4;
1539 else if(isDND())
1540 return 3;
1541 if(isAFK())
1542 return 1;
1543 else
1544 return 0;
1547 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1549 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1551 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1552 return false;
1555 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1556 Pet* pet = GetPet();
1558 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1560 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1561 // don't let gm level > 1 either
1562 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1563 return false;
1565 // client without expansion support
1566 if(GetSession()->Expansion() < mEntry->Expansion())
1568 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1570 if(GetTransport())
1571 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1573 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1575 return false; // normal client can't teleport to this map...
1577 else
1579 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1582 // if we were on a transport, leave
1583 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1585 m_transport->RemovePassenger(this);
1586 m_transport = NULL;
1587 m_movementInfo.t_x = 0.0f;
1588 m_movementInfo.t_y = 0.0f;
1589 m_movementInfo.t_z = 0.0f;
1590 m_movementInfo.t_o = 0.0f;
1591 m_movementInfo.t_time = 0;
1594 // The player was ported to another map and looses the duel immediately.
1595 // We have to perform this check before the teleport, otherwise the
1596 // ObjectAccessor won't find the flag.
1597 if (duel && GetMapId()!=mapid)
1599 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1600 if (obj)
1601 DuelComplete(DUEL_FLED);
1604 // reset movement flags at teleport, because player will continue move with these flags after teleport
1605 SetUnitMovementFlags(0);
1607 if ((GetMapId() == mapid) && (!m_transport))
1609 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1611 //same map, only remove pet if out of range for new position
1612 if(pet && pet->GetDistance(x,y,z) >= OWNER_MAX_DISTANCE)
1613 UnsummonPetTemporaryIfAny();
1616 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1617 CombatStop();
1619 // this will be used instead of the current location in SaveToDB
1620 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1621 SetFallInformation(0, z);
1623 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1624 // at client packet MSG_MOVE_TELEPORT_ACK
1625 SetSemaphoreTeleportNear(true);
1626 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1627 if(!GetSession()->PlayerLogout())
1629 WorldPacket data;
1630 BuildTeleportAckMsg(&data, x, y, z, orientation);
1631 GetSession()->SendPacket(&data);
1634 else
1636 // far teleport to another map
1637 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1638 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1640 // Check enter rights before map getting to avoid creating instance copy for player
1641 // this check not dependent from map instance copy and same for all instance copies of selected map
1642 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1643 return false;
1645 // If the map is not created, assume it is possible to enter it.
1646 // It will be created in the WorldPortAck.
1647 Map *map = MapManager::Instance().FindMap(mapid);
1648 if (!map || map->CanEnter(this))
1650 SetSelection(0);
1652 CombatStop();
1654 ResetContestedPvP();
1656 // remove player from battleground on far teleport (when changing maps)
1657 if(BattleGround const* bg = GetBattleGround())
1659 // Note: at battleground join battleground id set before teleport
1660 // and we already will found "current" battleground
1661 // just need check that this is targeted map or leave
1662 if(bg->GetMapId() != mapid)
1663 LeaveBattleground(false); // don't teleport to entry point
1666 // remove pet on map change
1667 if (pet)
1668 UnsummonPetTemporaryIfAny();
1670 // remove all dyn objects
1671 RemoveAllDynObjects();
1673 // stop spellcasting
1674 // not attempt interrupt teleportation spell at caster teleport
1675 if(!(options & TELE_TO_SPELL))
1676 if(IsNonMeleeSpellCasted(true))
1677 InterruptNonMeleeSpells(true);
1679 if(!GetSession()->PlayerLogout())
1681 // send transfer packets
1682 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1683 data << uint32(mapid);
1684 if (m_transport)
1686 data << m_transport->GetEntry() << GetMapId();
1688 GetSession()->SendPacket(&data);
1690 data.Initialize(SMSG_NEW_WORLD, (20));
1691 if (m_transport)
1693 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1695 else
1697 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1699 GetSession()->SendPacket( &data );
1700 SendSavedInstances();
1702 // remove from old map now
1703 if(oldmap) oldmap->Remove(this, false);
1706 // new final coordinates
1707 float final_x = x;
1708 float final_y = y;
1709 float final_z = z;
1710 float final_o = orientation;
1712 if(m_transport)
1714 final_x += m_movementInfo.t_x;
1715 final_y += m_movementInfo.t_y;
1716 final_z += m_movementInfo.t_z;
1717 final_o += m_movementInfo.t_o;
1720 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1721 SetFallInformation(0, final_z);
1722 // if the player is saved before worldportack (at logout for example)
1723 // this will be used instead of the current location in SaveToDB
1725 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1727 // move packet sent by client always after far teleport
1728 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1729 SetSemaphoreTeleportFar(true);
1731 else
1732 return false;
1734 return true;
1737 void Player::AddToWorld()
1739 ///- Do not add/remove the player from the object storage
1740 ///- It will crash when updating the ObjectAccessor
1741 ///- The player should only be added when logging in
1742 Unit::AddToWorld();
1744 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1746 if(m_items[i])
1747 m_items[i]->AddToWorld();
1751 void Player::RemoveFromWorld()
1753 // cleanup
1754 if(IsInWorld())
1756 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1757 Uncharm();
1758 UnsummonAllTotems();
1759 RemoveMiniPet();
1760 RemoveGuardians();
1763 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1765 if(m_items[i])
1766 m_items[i]->RemoveFromWorld();
1769 ///- Do not add/remove the player from the object storage
1770 ///- It will crash when updating the ObjectAccessor
1771 ///- The player should only be removed when logging out
1772 Unit::RemoveFromWorld();
1775 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1777 float addRage;
1779 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1781 if(attacker)
1783 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1785 // talent who gave more rage on attack
1786 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1788 else
1790 addRage = damage/rageconversion*2.5;
1792 // Berserker Rage effect
1793 if(HasAura(18499,0))
1794 addRage *= 1.3;
1797 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1799 ModifyPower(POWER_RAGE, uint32(addRage*10));
1802 void Player::RegenerateAll()
1804 if (m_regenTimer != 0)
1805 return;
1806 uint32 regenDelay = 2000;
1808 // Not in combat or they have regeneration
1809 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1810 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1812 RegenerateHealth();
1813 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1815 Regenerate(POWER_RAGE);
1816 if(getClass() == CLASS_DEATH_KNIGHT)
1817 Regenerate(POWER_RUNIC_POWER);
1821 Regenerate( POWER_ENERGY );
1823 Regenerate( POWER_MANA );
1825 if(getClass() == CLASS_DEATH_KNIGHT)
1826 Regenerate( POWER_RUNE );
1828 m_regenTimer = regenDelay;
1831 void Player::Regenerate(Powers power)
1833 uint32 curValue = GetPower(power);
1834 uint32 maxValue = GetMaxPower(power);
1836 float addvalue = 0.0f;
1838 switch (power)
1840 case POWER_MANA:
1842 bool recentCast = IsUnderLastManaUseEffect();
1843 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1844 if (recentCast)
1846 // Mangos Updates Mana in intervals of 2s, which is correct
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 else
1851 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1853 } break;
1854 case POWER_RAGE: // Regenerate rage
1856 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1857 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1858 } break;
1859 case POWER_ENERGY: // Regenerate energy (rogue)
1860 addvalue = 20;
1861 break;
1862 case POWER_RUNIC_POWER:
1864 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1865 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1866 } break;
1867 case POWER_RUNE:
1869 for(uint32 i = 0; i < MAX_RUNES; ++i)
1870 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1871 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1872 } break;
1873 case POWER_FOCUS:
1874 case POWER_HAPPINESS:
1875 case POWER_HEALTH:
1876 break;
1879 // Mana regen calculated in Player::UpdateManaRegen()
1880 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1881 if(power != POWER_MANA)
1883 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1884 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1885 if ((*i)->GetModifier()->m_miscvalue == power)
1886 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1889 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1891 curValue += uint32(addvalue);
1892 if (curValue > maxValue)
1893 curValue = maxValue;
1895 else
1897 if(curValue <= uint32(addvalue))
1898 curValue = 0;
1899 else
1900 curValue -= uint32(addvalue);
1902 SetPower(power, curValue);
1905 void Player::RegenerateHealth()
1907 uint32 curValue = GetHealth();
1908 uint32 maxValue = GetMaxHealth();
1910 if (curValue >= maxValue) return;
1912 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1914 float addvalue = 0.0f;
1916 // polymorphed case
1917 if ( IsPolymorphed() )
1918 addvalue = GetMaxHealth()/3;
1919 // normal regen case (maybe partly in combat case)
1920 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1922 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1923 if (!isInCombat())
1925 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1926 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1927 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1929 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1930 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1932 if(!IsStandState())
1933 addvalue *= 1.5;
1936 // always regeneration bonus (including combat)
1937 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1939 if(addvalue < 0)
1940 addvalue = 0;
1942 ModifyHealth(int32(addvalue));
1945 bool Player::CanInteractWithNPCs(bool alive) const
1947 if(alive && !isAlive())
1948 return false;
1949 if(isInFlight())
1950 return false;
1952 return true;
1955 Creature*
1956 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1958 // unit checks
1959 if (!guid)
1960 return NULL;
1962 if(!IsInWorld())
1963 return NULL;
1965 // exist (we need look pets also for some interaction (quest/etc)
1966 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1967 if (!unit)
1968 return NULL;
1970 // player check
1971 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1972 return NULL;
1974 // appropriate npc type
1975 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1976 return NULL;
1978 // alive or spirit healer
1979 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1980 return NULL;
1982 // not allow interaction under control, but allow with own pets
1983 if(unit->GetCharmerGUID())
1984 return NULL;
1986 // not enemy
1987 if( unit->IsHostileTo(this))
1988 return NULL;
1990 // not unfriendly
1991 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1992 if(factionTemplate->faction)
1993 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1994 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
1995 return NULL;
1997 // not too far
1998 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
1999 return NULL;
2001 return unit;
2004 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2006 if(GameObject *go = GetMap()->GetGameObject(guid))
2008 if(go->GetGoType() == type)
2010 float maxdist;
2011 switch(type)
2013 // TODO: find out how the client calculates the maximal usage distance to spellless working
2014 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2015 case GAMEOBJECT_TYPE_GUILD_BANK:
2016 case GAMEOBJECT_TYPE_MAILBOX:
2017 maxdist = 10.0f;
2018 break;
2019 case GAMEOBJECT_TYPE_FISHINGHOLE:
2020 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2021 break;
2022 default:
2023 maxdist = INTERACTION_DISTANCE;
2024 break;
2027 if (go->IsWithinDistInMap(this, maxdist))
2028 return go;
2030 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2031 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2034 return NULL;
2037 bool Player::IsUnderWater() const
2039 return IsInWater() &&
2040 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2043 void Player::SetInWater(bool apply)
2045 if(m_isInWater==apply)
2046 return;
2048 //define player in water by opcodes
2049 //move player's guid into HateOfflineList of those mobs
2050 //which can't swim and move guid back into ThreatList when
2051 //on surface.
2052 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2053 m_isInWater = apply;
2055 // remove auras that need water/land
2056 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2058 getHostilRefManager().updateThreatTables();
2061 void Player::SetGameMaster(bool on)
2063 if(on)
2065 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2066 setFaction(35);
2067 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2069 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2070 ResetContestedPvP();
2072 getHostilRefManager().setOnlineOfflineState(false);
2073 CombatStop();
2075 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2077 else
2079 // restore phase
2080 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2081 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2083 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2084 setFactionForRace(getRace());
2085 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2087 // restore FFA PvP Server state
2088 if(sWorld.IsFFAPvPRealm())
2089 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2091 // restore FFA PvP area state, remove not allowed for GM mounts
2092 UpdateArea(m_areaUpdateId);
2094 getHostilRefManager().setOnlineOfflineState(true);
2097 ObjectAccessor::UpdateVisibilityForPlayer(this);
2100 void Player::SetGMVisible(bool on)
2102 if(on)
2104 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2106 // Reapply stealth/invisibility if active or show if not any
2107 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2108 SetVisibility(VISIBILITY_GROUP_STEALTH);
2109 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2110 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2111 else
2112 SetVisibility(VISIBILITY_ON);
2114 else
2116 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2118 SetAcceptWhispers(false);
2119 SetGameMaster(true);
2121 SetVisibility(VISIBILITY_OFF);
2125 bool Player::IsGroupVisibleFor(Player* p) const
2127 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2129 default: return IsInSameGroupWith(p);
2130 case 1: return IsInSameRaidWith(p);
2131 case 2: return GetTeam()==p->GetTeam();
2135 bool Player::IsInSameGroupWith(Player const* p) const
2137 return p==this || GetGroup() != NULL &&
2138 GetGroup() == p->GetGroup() &&
2139 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2142 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2143 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2144 void Player::UninviteFromGroup()
2146 Group* group = GetGroupInvite();
2147 if(!group)
2148 return;
2150 group->RemoveInvite(this);
2152 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2154 if(group->IsCreated())
2156 group->Disband(true);
2157 objmgr.RemoveGroup(group);
2159 else
2160 group->RemoveAllInvites();
2162 delete group;
2166 void Player::RemoveFromGroup(Group* group, uint64 guid)
2168 if(group)
2170 if (group->RemoveMember(guid, 0) <= 1)
2172 // group->Disband(); already disbanded in RemoveMember
2173 objmgr.RemoveGroup(group);
2174 delete group;
2175 // removemember sets the player's group pointer to NULL
2180 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2182 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2183 data << uint64(victim ? victim->GetGUID() : 0); // guid
2184 data << uint32(GivenXP+RestXP); // given experience
2185 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2186 if(victim)
2188 data << uint32(GivenXP); // experience without rested bonus
2189 data << float(1); // 1 - none 0 - 100% group bonus output
2191 data << uint8(0); // new 2.4.0
2192 GetSession()->SendPacket(&data);
2195 void Player::GiveXP(uint32 xp, Unit* victim)
2197 if ( xp < 1 )
2198 return;
2200 if(!isAlive())
2201 return;
2203 uint32 level = getLevel();
2205 // XP to money conversion processed in Player::RewardQuest
2206 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2207 return;
2209 // handle SPELL_AURA_MOD_XP_PCT auras
2210 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2211 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2212 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2214 // XP resting bonus for kill
2215 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2217 SendLogXPGain(xp,victim,rested_bonus_xp);
2219 uint32 curXP = GetUInt32Value(PLAYER_XP);
2220 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2221 uint32 newXP = curXP + xp + rested_bonus_xp;
2223 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2225 newXP -= nextLvlXP;
2227 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2228 GiveLevel(level + 1);
2230 level = getLevel();
2231 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2234 SetUInt32Value(PLAYER_XP, newXP);
2237 // Update player to next level
2238 // Current player experience not update (must be update by caller)
2239 void Player::GiveLevel(uint32 level)
2241 if ( level == getLevel() )
2242 return;
2244 PlayerLevelInfo info;
2245 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2247 PlayerClassLevelInfo classInfo;
2248 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2250 // send levelup info to client
2251 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2252 data << uint32(level);
2253 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2254 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2255 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2256 data << uint32(0);
2257 data << uint32(0);
2258 data << uint32(0);
2259 data << uint32(0);
2260 data << uint32(0);
2261 data << uint32(0);
2262 // end for
2263 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2264 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2266 GetSession()->SendPacket(&data);
2268 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2270 //update level, max level of skills
2271 if(getLevel()!= level)
2272 m_Played_time[1] = 0; // Level Played Time reset
2273 SetLevel(level);
2274 UpdateSkillsForLevel ();
2276 // save base values (bonuses already included in stored stats
2277 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2278 SetCreateStat(Stats(i), info.stats[i]);
2280 SetCreateHealth(classInfo.basehealth);
2281 SetCreateMana(classInfo.basemana);
2283 InitTalentForLevel();
2284 InitTaxiNodesForLevel();
2285 InitGlyphsForLevel();
2287 UpdateAllStats();
2289 // set current level health and mana/energy to maximum after applying all mods.
2290 SetHealth(GetMaxHealth());
2291 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2292 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2293 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2294 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2295 SetPower(POWER_FOCUS, 0);
2296 SetPower(POWER_HAPPINESS, 0);
2298 // give level to summoned pet
2299 Pet* pet = GetPet();
2300 if(pet && pet->getPetType()==SUMMON_PET)
2301 pet->GivePetLevel(level);
2302 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2305 void Player::InitTalentForLevel()
2307 uint32 level = getLevel();
2308 // talents base at level diff ( talents = level - 9 but some can be used already)
2309 if(level < 10)
2311 // Remove all talent points
2312 if(m_usedTalentCount > 0) // Free any used talents
2314 resetTalents(true);
2315 SetFreeTalentPoints(0);
2318 else
2320 uint32 talentPointsForLevel = CalculateTalentsPoints();
2322 // if used more that have then reset
2323 if(m_usedTalentCount > talentPointsForLevel)
2325 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2326 resetTalents(true);
2327 else
2328 SetFreeTalentPoints(0);
2330 // else update amount of free points
2331 else
2332 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2336 void Player::InitStatsForLevel(bool reapplyMods)
2338 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2339 _RemoveAllStatBonuses();
2341 PlayerClassLevelInfo classInfo;
2342 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2344 PlayerLevelInfo info;
2345 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2347 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2348 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2350 UpdateSkillsForLevel ();
2352 // set default cast time multiplier
2353 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2355 // reset size before reapply auras
2356 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2358 // save base values (bonuses already included in stored stats
2359 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2360 SetCreateStat(Stats(i), info.stats[i]);
2362 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2363 SetStat(Stats(i), info.stats[i]);
2365 SetCreateHealth(classInfo.basehealth);
2367 //set create powers
2368 SetCreateMana(classInfo.basemana);
2370 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2372 InitStatBuffMods();
2374 //reset rating fields values
2375 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2376 SetUInt32Value(index, 0);
2378 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2379 for (int i = 0; i < 7; ++i)
2381 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2382 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2383 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2386 //reset attack power, damage and attack speed fields
2387 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2388 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2389 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2391 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2392 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2393 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2394 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2395 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2396 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2398 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2399 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2400 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2401 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2402 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2403 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2405 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2406 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2407 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2408 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2410 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2411 for (uint8 i = 0; i < 7; ++i)
2412 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2414 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2415 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2416 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2418 // Dodge percentage
2419 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2421 // set armor (resistance 0) to original value (create_agility*2)
2422 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2423 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2424 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2425 // set other resistance to original value (0)
2426 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2428 SetResistance(SpellSchools(i), 0);
2429 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2430 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2433 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2434 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2435 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2437 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2438 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2440 // Reset no reagent cost field
2441 for(int i = 0; i < 3; ++i)
2442 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2443 // Init data for form but skip reapply item mods for form
2444 InitDataForForm(reapplyMods);
2446 // save new stats
2447 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2448 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2450 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2452 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2453 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2455 // cleanup unit flags (will be re-applied if need at aura load).
2456 RemoveFlag( UNIT_FIELD_FLAGS,
2457 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2458 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2459 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2460 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2461 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2462 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2464 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2466 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2467 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2469 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2470 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2472 // restore if need some important flags
2473 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2475 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2476 _ApplyAllStatBonuses();
2478 // set current level health and mana/energy to maximum after applying all mods.
2479 SetHealth(GetMaxHealth());
2480 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2481 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2482 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2483 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2484 SetPower(POWER_FOCUS, 0);
2485 SetPower(POWER_HAPPINESS, 0);
2486 SetPower(POWER_RUNIC_POWER, 0);
2489 void Player::SendInitialSpells()
2491 time_t curTime = time(NULL);
2492 time_t infTime = curTime + MONTH/2;
2494 uint16 spellCount = 0;
2496 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2497 data << uint8(0);
2499 size_t countPos = data.wpos();
2500 data << uint16(spellCount); // spell count placeholder
2502 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2504 if(itr->second->state == PLAYERSPELL_REMOVED)
2505 continue;
2507 if(!itr->second->active || itr->second->disabled)
2508 continue;
2510 data << uint16(itr->first);
2511 data << uint16(0); // it's not slot id
2513 spellCount +=1;
2516 data.put<uint16>(countPos,spellCount); // write real count value
2518 uint16 spellCooldowns = m_spellCooldowns.size();
2519 data << uint16(spellCooldowns);
2520 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2522 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2523 if(!sEntry)
2524 continue;
2526 // not send infinity cooldown
2527 if(itr->second.end > infTime)
2528 continue;
2530 data << uint16(itr->first);
2532 time_t cooldown = 0;
2533 if(itr->second.end > curTime)
2534 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2536 data << uint16(itr->second.itemid); // cast item id
2537 data << uint16(sEntry->Category); // spell category
2538 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2540 data << uint32(0); // cooldown
2541 data << uint32(cooldown); // category cooldown
2543 else
2545 data << uint32(cooldown); // cooldown
2546 data << uint32(0); // category cooldown
2550 GetSession()->SendPacket(&data);
2552 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2555 void Player::RemoveMail(uint32 id)
2557 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2559 if ((*itr)->messageID == id)
2561 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2562 m_mail.erase(itr);
2563 return;
2568 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2570 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2571 data << (uint32) mailId;
2572 data << (uint32) mailAction;
2573 data << (uint32) mailError;
2574 if ( mailError == MAIL_ERR_BAG_FULL )
2575 data << (uint32) equipError;
2576 else if( mailAction == MAIL_ITEM_TAKEN )
2578 data << (uint32) item_guid; // item guid low?
2579 data << (uint32) item_count; // item count?
2581 GetSession()->SendPacket(&data);
2584 void Player::SendNewMail()
2586 // deliver undelivered mail
2587 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2588 data << (uint32) 0;
2589 GetSession()->SendPacket(&data);
2592 void Player::UpdateNextMailTimeAndUnreads()
2594 // calculate next delivery time (min. from non-delivered mails
2595 // and recalculate unReadMail
2596 time_t cTime = time(NULL);
2597 m_nextMailDelivereTime = 0;
2598 unReadMails = 0;
2599 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2601 if((*itr)->deliver_time > cTime)
2603 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2604 m_nextMailDelivereTime = (*itr)->deliver_time;
2606 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2607 ++unReadMails;
2611 void Player::AddNewMailDeliverTime(time_t deliver_time)
2613 if(deliver_time <= time(NULL)) // ready now
2615 ++unReadMails;
2616 SendNewMail();
2618 else // not ready and no have ready mails
2620 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2621 m_nextMailDelivereTime = deliver_time;
2625 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2627 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2628 if (!spellInfo)
2630 // do character spell book cleanup (all characters)
2631 if(!IsInWorld() && !learning) // spell load case
2633 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2634 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2636 else
2637 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2639 return false;
2642 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2644 // do character spell book cleanup (all characters)
2645 if(!IsInWorld() && !learning) // spell load case
2647 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2648 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2650 else
2651 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2653 return false;
2656 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2658 bool dependent_set = false;
2659 bool disabled_case = false;
2660 bool superceded_old = false;
2662 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2663 if (itr != m_spells.end())
2665 uint32 next_active_spell_id = 0;
2666 // fix activate state for non-stackable low rank (and find next spell for !active case)
2667 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2669 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2670 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2672 if(HasSpell(next_itr->second))
2674 // high rank already known so this must !active
2675 active = false;
2676 next_active_spell_id = next_itr->second;
2677 break;
2682 // not do anything if already known in expected state
2683 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2684 itr->second->dependent == dependent && itr->second->disabled == disabled)
2686 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2687 itr->second->state = PLAYERSPELL_UNCHANGED;
2689 return false;
2692 // dependent spell known as not dependent, overwrite state
2693 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2695 itr->second->dependent = dependent;
2696 if (itr->second->state != PLAYERSPELL_NEW)
2697 itr->second->state = PLAYERSPELL_CHANGED;
2698 dependent_set = true;
2701 // update active state for known spell
2702 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2704 itr->second->active = active;
2706 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2707 itr->second->state = PLAYERSPELL_UNCHANGED;
2708 else if(itr->second->state != PLAYERSPELL_NEW)
2709 itr->second->state = PLAYERSPELL_CHANGED;
2711 if(active)
2713 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2714 CastSpell (this,spell_id,true);
2716 else if(IsInWorld())
2718 if(next_active_spell_id)
2720 // update spell ranks in spellbook and action bar
2721 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2722 data << uint16(spell_id);
2723 data << uint16(next_active_spell_id);
2724 GetSession()->SendPacket( &data );
2726 else
2728 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2729 data << uint16(spell_id);
2730 GetSession()->SendPacket(&data);
2734 return active; // learn (show in spell book if active now)
2737 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2739 if(itr->second->state != PLAYERSPELL_NEW)
2740 itr->second->state = PLAYERSPELL_CHANGED;
2741 itr->second->disabled = disabled;
2743 if(disabled)
2744 return false;
2746 disabled_case = true;
2748 else switch(itr->second->state)
2750 case PLAYERSPELL_UNCHANGED: // known saved spell
2751 return false;
2752 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2754 delete itr->second;
2755 m_spells.erase(itr);
2756 state = PLAYERSPELL_CHANGED;
2757 break; // need re-add
2759 default: // known not saved yet spell (new or modified)
2761 // can be in case spell loading but learned at some previous spell loading
2762 if(!IsInWorld() && !learning && !dependent_set)
2763 itr->second->state = PLAYERSPELL_UNCHANGED;
2765 return false;
2770 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2772 // talent: unlearn all other talent ranks (high and low)
2773 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2775 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2777 for(int i=0; i < MAX_TALENT_RANK; ++i)
2779 // skip learning spell and no rank spell case
2780 uint32 rankSpellId = talentInfo->RankID[i];
2781 if(!rankSpellId || rankSpellId==spell_id)
2782 continue;
2784 removeSpell(rankSpellId);
2788 // non talent spell: learn low ranks (recursive call)
2789 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2791 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2792 addSpell(prev_spell,active,true,true,disabled);
2793 else // at normal learning
2794 learnSpell(prev_spell,true);
2797 PlayerSpell *newspell = new PlayerSpell;
2798 newspell->state = state;
2799 newspell->active = active;
2800 newspell->dependent = dependent;
2801 newspell->disabled = disabled;
2803 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2804 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2806 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2808 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2809 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2810 if(!i_spellInfo) continue;
2812 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2814 if(itr2->second->active)
2816 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2818 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2820 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2821 data << uint16(itr2->first);
2822 data << uint16(spell_id);
2823 GetSession()->SendPacket( &data );
2826 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2827 itr2->second->active = false;
2828 if(itr2->second->state != PLAYERSPELL_NEW)
2829 itr2->second->state = PLAYERSPELL_CHANGED;
2830 superceded_old = true; // new spell replace old in action bars and spell book.
2832 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2834 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2836 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2837 data << uint16(spell_id);
2838 data << uint16(itr2->first);
2839 GetSession()->SendPacket( &data );
2842 // mark new spell as disable (not learned yet for client and will not learned)
2843 newspell->active = false;
2844 if(newspell->state != PLAYERSPELL_NEW)
2845 newspell->state = PLAYERSPELL_CHANGED;
2852 m_spells[spell_id] = newspell;
2854 // return false if spell disabled
2855 if (newspell->disabled)
2856 return false;
2859 uint32 talentCost = GetTalentSpellCost(spell_id);
2861 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2862 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2863 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2865 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2866 CastSpell(this, spell_id, true);
2868 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2869 else if (IsPassiveSpell(spell_id))
2871 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2872 CastSpell(this, spell_id, true);
2874 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2876 CastSpell(this, spell_id, true);
2877 return false;
2880 // update used talent points count
2881 m_usedTalentCount += talentCost;
2883 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2884 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2886 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2887 SetFreePrimaryProffesions(freeProfs-1);
2890 // add dependent skills
2891 uint16 maxskill = GetMaxSkillValueForLevel();
2893 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2895 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2896 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2898 if(spellLearnSkill)
2900 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2901 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2903 if(skill_value < spellLearnSkill->value)
2904 skill_value = spellLearnSkill->value;
2906 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2908 if(skill_max_value < new_skill_max_value)
2909 skill_max_value = new_skill_max_value;
2911 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2913 else
2915 // not ranked skills
2916 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2918 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2919 if(!pSkill)
2920 continue;
2922 if(HasSkill(pSkill->id))
2923 continue;
2925 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2926 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2927 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2929 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2931 case SKILL_RANGE_LANGUAGE:
2932 SetSkill(pSkill->id, 300, 300 );
2933 break;
2934 case SKILL_RANGE_LEVEL:
2935 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2936 break;
2937 case SKILL_RANGE_MONO:
2938 SetSkill(pSkill->id, 1, 1 );
2939 break;
2940 default:
2941 break;
2947 // learn dependent spells
2948 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2949 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2951 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2953 if(!itr2->second.autoLearned)
2955 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2956 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2957 else // at normal learning
2958 learnSpell(itr2->second.spell,true);
2962 if(!GetSession()->PlayerLoading())
2964 // not ranked skills
2965 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2967 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
2968 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
2971 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2974 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2975 return active && !disabled && !superceded_old;
2978 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2980 bool need_cast = false;
2982 switch(spellInfo->Id)
2984 // some spells not have stance data expacted cast at form change or present
2985 case 5420: need_cast = (m_form == FORM_TREE); break;
2986 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2987 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2988 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2989 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2990 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2991 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2992 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2993 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2994 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2995 // another spells have proper stance data
2996 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2999 //Check CasterAuraStates
3000 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3003 void Player::learnSpell(uint32 spell_id, bool dependent)
3005 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3007 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3008 bool active = disabled ? itr->second->active : true;
3010 bool learning = addSpell(spell_id,active,true,dependent,false);
3012 // learn all disabled higher ranks (recursive)
3013 if(disabled)
3015 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3016 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3018 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3019 if (iter != m_spells.end() && iter->second->disabled)
3020 learnSpell(i->second,false);
3024 // prevent duplicated entires in spell book, also not send if not in world (loading)
3025 if(!learning || !IsInWorld ())
3026 return;
3028 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3029 data << uint32(spell_id);
3030 GetSession()->SendPacket(&data);
3033 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3035 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3036 if (itr == m_spells.end())
3037 return;
3039 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3040 return;
3042 // unlearn non talent higher ranks (recursive)
3043 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3044 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3045 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3046 removeSpell(itr2->second,disabled);
3048 bool cur_active = itr->second->active;
3049 bool cur_dependent = itr->second->dependent;
3051 if (disabled)
3053 itr->second->disabled = disabled;
3054 if(itr->second->state != PLAYERSPELL_NEW)
3055 itr->second->state = PLAYERSPELL_CHANGED;
3057 else
3059 if(itr->second->state == PLAYERSPELL_NEW)
3061 delete itr->second;
3062 m_spells.erase(itr);
3064 else
3065 itr->second->state = PLAYERSPELL_REMOVED;
3068 RemoveAurasDueToSpell(spell_id);
3070 // remove pet auras
3071 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3072 RemovePetAura(petSpell);
3074 // free talent points
3075 uint32 talentCosts = GetTalentSpellCost(spell_id);
3076 if(talentCosts > 0)
3078 if(talentCosts < m_usedTalentCount)
3079 m_usedTalentCount -= talentCosts;
3080 else
3081 m_usedTalentCount = 0;
3084 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3085 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3087 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3088 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3089 SetFreePrimaryProffesions(freeProfs);
3092 // remove dependent skill
3093 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3094 if(spellLearnSkill)
3096 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3097 if(!prev_spell) // first rank, remove skill
3098 SetSkill(spellLearnSkill->skill,0,0);
3099 else
3101 // search prev. skill setting by spell ranks chain
3102 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3103 while(!prevSkill && prev_spell)
3105 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3106 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3109 if(!prevSkill) // not found prev skill setting, remove skill
3110 SetSkill(spellLearnSkill->skill,0,0);
3111 else // set to prev. skill setting values
3113 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3114 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3116 if(skill_value > prevSkill->value)
3117 skill_value = prevSkill->value;
3119 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3121 if(skill_max_value > new_skill_max_value)
3122 skill_max_value = new_skill_max_value;
3124 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3129 else
3131 // not ranked skills
3132 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3133 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3135 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3137 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3138 if(!pSkill)
3139 continue;
3141 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3142 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3143 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3145 // not reset skills for professions and racial abilities
3146 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3147 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3148 continue;
3150 SetSkill(pSkill->id, 0, 0 );
3155 // remove dependent spells
3156 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3157 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3159 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3160 removeSpell(itr2->second.spell, disabled);
3162 // activate lesser rank in spellbook/action bar, and cast it if need
3163 bool prev_activate = false;
3165 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3167 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3169 // if talent then lesser rank also talent and need learn
3170 if(talentCosts)
3171 learnSpell (prev_id,false);
3172 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3173 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3175 // need manually update dependence state (learn spell ignore like attempts)
3176 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3177 if (prev_itr != m_spells.end())
3179 if(prev_itr->second->dependent != cur_dependent)
3181 prev_itr->second->dependent = cur_dependent;
3182 if(prev_itr->second->state != PLAYERSPELL_NEW)
3183 prev_itr->second->state = PLAYERSPELL_CHANGED;
3186 // now re-learn if need re-activate
3187 if(cur_active && !prev_itr->second->active)
3189 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3191 if(update_action_bar_for_low_rank)
3193 // downgrade spell ranks in spellbook and action bar
3194 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3195 data << uint16(spell_id);
3196 data << uint16(prev_id);
3197 GetSession()->SendPacket( &data );
3198 prev_activate = true;
3206 // remove from spell book if not replaced by lesser rank
3207 if(!prev_activate)
3209 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3210 data << uint16(spell_id);
3211 GetSession()->SendPacket(&data);
3215 void Player::RemoveArenaSpellCooldowns()
3217 // remove cooldowns on spells that has < 15 min CD
3218 SpellCooldowns::iterator itr, next;
3219 // iterate spell cooldowns
3220 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3222 next = itr;
3223 ++next;
3224 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3225 // check if spellentry is present and if the cooldown is less than 15 mins
3226 if( entry &&
3227 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3228 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3230 // notify player
3231 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3232 data << uint32(itr->first);
3233 data << uint64(GetGUID());
3234 GetSession()->SendPacket(&data);
3235 // remove cooldown
3236 m_spellCooldowns.erase(itr);
3241 void Player::RemoveAllSpellCooldown()
3243 if(!m_spellCooldowns.empty())
3245 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3247 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3248 data << uint32(itr->first);
3249 data << uint64(GetGUID());
3250 GetSession()->SendPacket(&data);
3252 m_spellCooldowns.clear();
3256 void Player::_LoadSpellCooldowns(QueryResult *result)
3258 // some cooldowns can be already set at aura loading...
3260 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3262 if(result)
3264 time_t curTime = time(NULL);
3268 Field *fields = result->Fetch();
3270 uint32 spell_id = fields[0].GetUInt32();
3271 uint32 item_id = fields[1].GetUInt32();
3272 time_t db_time = (time_t)fields[2].GetUInt64();
3274 if(!sSpellStore.LookupEntry(spell_id))
3276 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3277 continue;
3280 // skip outdated cooldown
3281 if(db_time <= curTime)
3282 continue;
3284 AddSpellCooldown(spell_id, item_id, db_time);
3286 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3288 while( result->NextRow() );
3290 delete result;
3294 void Player::_SaveSpellCooldowns()
3296 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3298 time_t curTime = time(NULL);
3299 time_t infTime = curTime + MONTH/2;
3301 // remove outdated and save active
3302 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3304 if(itr->second.end <= curTime)
3305 m_spellCooldowns.erase(itr++);
3306 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3308 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));
3309 ++itr;
3311 else
3312 ++itr;
3316 uint32 Player::resetTalentsCost() const
3318 // The first time reset costs 1 gold
3319 if(m_resetTalentsCost < 1*GOLD)
3320 return 1*GOLD;
3321 // then 5 gold
3322 else if(m_resetTalentsCost < 5*GOLD)
3323 return 5*GOLD;
3324 // After that it increases in increments of 5 gold
3325 else if(m_resetTalentsCost < 10*GOLD)
3326 return 10*GOLD;
3327 else
3329 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3330 if(months > 0)
3332 // This cost will be reduced by a rate of 5 gold per month
3333 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3334 // to a minimum of 10 gold.
3335 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3337 else
3339 // After that it increases in increments of 5 gold
3340 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3341 // until it hits a cap of 50 gold.
3342 if(new_cost > 50*GOLD)
3343 new_cost = 50*GOLD;
3344 return new_cost;
3349 bool Player::resetTalents(bool no_cost)
3351 // not need after this call
3352 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3354 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3355 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3358 uint32 talentPointsForLevel = CalculateTalentsPoints();
3360 if (m_usedTalentCount == 0)
3362 SetFreeTalentPoints(talentPointsForLevel);
3363 return false;
3366 uint32 cost = 0;
3368 if(!no_cost)
3370 cost = resetTalentsCost();
3372 if (GetMoney() < cost)
3374 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3375 return false;
3379 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3381 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3383 if (!talentInfo) continue;
3385 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3387 if(!talentTabInfo)
3388 continue;
3390 // unlearn only talents for character class
3391 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3392 // to prevent unexpected lost normal learned spell skip another class talents
3393 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3394 continue;
3396 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3398 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3400 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3402 ++itr;
3403 continue;
3406 // remove learned spells (all ranks)
3407 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3409 // unlearn if first rank is talent or learned by talent
3410 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3412 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3413 itr = GetSpellMap().begin();
3414 continue;
3416 else
3417 ++itr;
3422 SetFreeTalentPoints(talentPointsForLevel);
3424 if(!no_cost)
3426 ModifyMoney(-(int32)cost);
3427 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3428 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3430 m_resetTalentsCost = cost;
3431 m_resetTalentsTime = time(NULL);
3434 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3435 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3437 if(m_canTitanGrip)
3439 m_canTitanGrip = false;
3440 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3441 AutoUnequipOffhandIfNeed();
3444 return true;
3447 Mail* Player::GetMail(uint32 id)
3449 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3451 if ((*itr)->messageID == id)
3453 return (*itr);
3456 return NULL;
3459 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3461 if(target == this)
3463 Object::_SetCreateBits(updateMask, target);
3465 else
3467 for(uint16 index = 0; index < m_valuesCount; index++)
3469 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3470 updateMask->SetBit(index);
3475 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3477 if(target == this)
3479 Object::_SetUpdateBits(updateMask, target);
3481 else
3483 Object::_SetUpdateBits(updateMask, target);
3484 *updateMask &= updateVisualBits;
3488 void Player::InitVisibleBits()
3490 updateVisualBits.SetCount(PLAYER_END);
3492 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3493 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3494 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3495 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3496 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3497 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3498 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3499 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3500 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3501 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3502 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3503 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3504 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3505 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3506 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3507 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3508 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3509 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3510 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3511 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3512 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3513 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3514 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3515 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3516 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3517 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3518 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3519 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3520 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3521 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3522 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3523 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3524 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3525 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3526 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3527 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3528 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3529 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3530 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3531 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3532 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3533 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3534 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3535 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3536 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3537 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3538 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3539 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3540 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3541 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3542 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3543 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3544 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3545 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3546 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3548 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3549 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3550 updateVisualBits.SetBit(PLAYER_FLAGS);
3551 updateVisualBits.SetBit(PLAYER_GUILDID);
3552 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3553 updateVisualBits.SetBit(PLAYER_BYTES);
3554 updateVisualBits.SetBit(PLAYER_BYTES_2);
3555 updateVisualBits.SetBit(PLAYER_BYTES_3);
3556 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3557 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3559 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3560 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3561 updateVisualBits.SetBit(i);
3563 // Players visible items are not inventory stuff
3564 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3566 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3568 // item creator
3569 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3570 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3572 // item entry
3573 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3575 // item enchantments
3576 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3577 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3579 // random properties
3580 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3581 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3582 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3585 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3588 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3590 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3592 if(m_items[i] == NULL)
3593 continue;
3595 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3598 if(target == this)
3600 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3602 if(m_items[i] == NULL)
3603 continue;
3605 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3607 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3609 if(m_items[i] == NULL)
3610 continue;
3612 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3616 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3619 void Player::DestroyForPlayer( Player *target ) const
3621 Unit::DestroyForPlayer( target );
3623 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3625 if(m_items[i] == NULL)
3626 continue;
3628 m_items[i]->DestroyForPlayer( target );
3631 if(target == this)
3633 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3635 if(m_items[i] == NULL)
3636 continue;
3638 m_items[i]->DestroyForPlayer( target );
3640 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3642 if(m_items[i] == NULL)
3643 continue;
3645 m_items[i]->DestroyForPlayer( target );
3650 bool Player::HasSpell(uint32 spell) const
3652 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3653 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3654 !itr->second->disabled);
3657 bool Player::HasActiveSpell(uint32 spell) const
3659 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3660 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3661 itr->second->active && !itr->second->disabled);
3664 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3666 if (!trainer_spell)
3667 return TRAINER_SPELL_RED;
3669 if (!trainer_spell->learnedSpell)
3670 return TRAINER_SPELL_RED;
3672 // known spell
3673 if(HasSpell(trainer_spell->learnedSpell))
3674 return TRAINER_SPELL_GRAY;
3676 // check race/class requirement
3677 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3678 return TRAINER_SPELL_RED;
3680 // check level requirement
3681 if(getLevel() < trainer_spell->reqLevel)
3682 return TRAINER_SPELL_RED;
3684 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3686 // check prev.rank requirement
3687 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3688 return TRAINER_SPELL_RED;
3690 // check additional spell requirement
3691 if(spell_chain->req && !HasSpell(spell_chain->req))
3692 return TRAINER_SPELL_RED;
3695 // check skill requirement
3696 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3697 return TRAINER_SPELL_RED;
3699 // exist, already checked at loading
3700 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3702 // secondary prof. or not prof. spell
3703 uint32 skill = spell->EffectMiscValue[1];
3705 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3706 return TRAINER_SPELL_GREEN;
3708 // check primary prof. limit
3709 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3710 return TRAINER_SPELL_GREEN_DISABLED;
3712 return TRAINER_SPELL_GREEN;
3715 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3717 uint32 guid = GUID_LOPART(playerguid);
3719 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3720 // bones will be deleted by corpse/bones deleting thread shortly
3721 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3723 // remove from guild
3724 uint32 guildId = GetGuildIdFromDB(playerguid);
3725 if(guildId != 0)
3727 Guild* guild = objmgr.GetGuildById(guildId);
3728 if(guild)
3729 guild->DelMember(guid);
3732 // remove from arena teams
3733 LeaveAllArenaTeams(playerguid);
3735 // the player was uninvited already on logout so just remove from group
3736 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3737 if(resultGroup)
3739 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3740 delete resultGroup;
3741 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3742 if(group)
3744 RemoveFromGroup(group, playerguid);
3748 // remove signs from petitions (also remove petitions if owner);
3749 RemovePetitionsAndSigns(playerguid, 10);
3751 // return back all mails with COD and Item 0 1 2 3 4 5 6
3752 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);
3753 if(resultMail)
3757 Field *fields = resultMail->Fetch();
3759 uint32 mail_id = fields[0].GetUInt32();
3760 uint16 mailTemplateId= fields[1].GetUInt16();
3761 uint32 sender = fields[2].GetUInt32();
3762 std::string subject = fields[3].GetCppString();
3763 uint32 itemTextId = fields[4].GetUInt32();
3764 uint32 money = fields[5].GetUInt32();
3765 bool has_items = fields[6].GetBool();
3767 //we can return mail now
3768 //so firstly delete the old one
3769 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3771 MailItemsInfo mi;
3772 if(has_items)
3774 // data needs to be at first place for Item::LoadFromDB
3775 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);
3776 if(resultItems)
3780 Field *fields2 = resultItems->Fetch();
3782 uint32 item_guidlow = fields2[1].GetUInt32();
3783 uint32 item_template = fields2[2].GetUInt32();
3785 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3786 if(!itemProto)
3788 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3789 continue;
3792 Item *pItem = NewItemOrBag(itemProto);
3793 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3795 pItem->FSetState(ITEM_REMOVED);
3796 pItem->SaveToDB(); // it also deletes item object !
3797 continue;
3800 mi.AddItem(item_guidlow, item_template, pItem);
3802 while (resultItems->NextRow());
3804 delete resultItems;
3808 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3810 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3812 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3814 while (resultMail->NextRow());
3816 delete resultMail;
3819 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3820 // Get guids of character's pets, will deleted in transaction
3821 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3823 // NOW we can finally clear other DB data related to character
3824 CharacterDatabase.BeginTransaction();
3825 if (resultPets)
3829 Field *fields3 = resultPets->Fetch();
3830 uint32 petguidlow = fields3[0].GetUInt32();
3831 Pet::DeleteFromDB(petguidlow);
3832 } while (resultPets->NextRow());
3833 delete resultPets;
3836 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3837 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3838 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3839 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3840 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3841 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3842 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3843 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3844 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3845 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3846 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3847 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3848 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3849 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3850 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3851 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3852 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3853 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3854 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3855 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3856 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3857 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3858 CharacterDatabase.CommitTransaction();
3860 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3861 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3864 void Player::SetMovement(PlayerMovementType pType)
3866 WorldPacket data;
3867 switch(pType)
3869 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3870 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3871 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3872 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3873 default:
3874 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3875 return;
3877 data.append(GetPackGUID());
3878 data << uint32(0);
3879 GetSession()->SendPacket( &data );
3882 /* Preconditions:
3883 - a resurrectable corpse must not be loaded for the player (only bones)
3884 - the player must be in world
3886 void Player::BuildPlayerRepop()
3888 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3889 data.append(GetPackGUID());
3890 GetSession()->SendPacket(&data);
3892 if(getRace() == RACE_NIGHTELF)
3893 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)
3894 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3896 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3897 // there must be SMSG.STOP_MIRROR_TIMER
3898 // there we must send 888 opcode
3900 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3901 if(GetCorpse())
3903 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3904 assert(false);
3907 // create a corpse and place it at the player's location
3908 CreateCorpse();
3909 Corpse *corpse = GetCorpse();
3910 if(!corpse)
3912 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3913 return;
3915 GetMap()->Add(corpse);
3917 // convert player body to ghost
3918 SetHealth( 1 );
3920 SetMovement(MOVE_WATER_WALK);
3921 if(!GetSession()->isLogingOut())
3922 SetMovement(MOVE_UNROOT);
3924 // BG - remove insignia related
3925 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3927 SendCorpseReclaimDelay();
3929 // to prevent cheating
3930 corpse->ResetGhostTime();
3932 StopMirrorTimers(); //disable timers(bars)
3934 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3936 // set and clear other
3937 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3940 void Player::SendDelayResponse(const uint32 ml_seconds)
3942 //FIXME: is this delay time arg really need? 50msec by default in code
3943 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3944 data << (uint32)time(NULL);
3945 data << (uint32)0;
3946 GetSession()->SendPacket( &data );
3949 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3951 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3952 data << uint32(-1);
3953 data << float(0);
3954 data << float(0);
3955 data << float(0);
3956 GetSession()->SendPacket(&data);
3958 // speed change, land walk
3960 // remove death flag + set aura
3961 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3962 if(getRace() == RACE_NIGHTELF)
3963 RemoveAurasDueToSpell(20584); // speed bonuses
3964 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3966 setDeathState(ALIVE);
3968 SetMovement(MOVE_LAND_WALK);
3969 SetMovement(MOVE_UNROOT);
3971 m_deathTimer = 0;
3973 // set health/powers (0- will be set in caller)
3974 if(restore_percent>0.0f)
3976 SetHealth(uint32(GetMaxHealth()*restore_percent));
3977 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3978 SetPower(POWER_RAGE, 0);
3979 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3982 // trigger update zone for alive state zone updates
3983 uint32 newzone, newarea;
3984 GetZoneAndAreaId(newzone,newarea);
3985 UpdateZone(newzone,newarea);
3987 // update visibility
3988 ObjectAccessor::UpdateVisibilityForPlayer(this);
3990 if(!applySickness)
3991 return;
3993 //Characters from level 1-10 are not affected by resurrection sickness.
3994 //Characters from level 11-19 will suffer from one minute of sickness
3995 //for each level they are above 10.
3996 //Characters level 20 and up suffer from ten minutes of sickness.
3997 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3999 if(int32(getLevel()) >= startLevel)
4001 // set resurrection sickness
4002 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4004 // not full duration
4005 if(int32(getLevel()) < startLevel+9)
4007 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4009 for(int i =0; i < 3; ++i)
4011 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4013 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4014 Aur->SendAuraUpdate(false);
4021 void Player::KillPlayer()
4023 SetMovement(MOVE_ROOT);
4025 StopMirrorTimers(); //disable timers(bars)
4027 setDeathState(CORPSE);
4028 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4030 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4031 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4033 // 6 minutes until repop at graveyard
4034 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4036 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4038 // don't create corpse at this moment, player might be falling
4040 // update visibility
4041 ObjectAccessor::UpdateObjectVisibility(this);
4044 void Player::CreateCorpse()
4046 // prevent existence 2 corpse for player
4047 SpawnCorpseBones();
4049 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4051 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4052 SetPvPDeath(false);
4054 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4056 delete corpse;
4057 return;
4060 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4061 _pb = GetUInt32Value(PLAYER_BYTES);
4062 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4064 uint8 race = (uint8)(_uf);
4065 uint8 skin = (uint8)(_pb);
4066 uint8 face = (uint8)(_pb >> 8);
4067 uint8 hairstyle = (uint8)(_pb >> 16);
4068 uint8 haircolor = (uint8)(_pb >> 24);
4069 uint8 facialhair = (uint8)(_pb2);
4071 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4072 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4074 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4075 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4077 uint32 flags = CORPSE_FLAG_UNK2;
4078 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4079 flags |= CORPSE_FLAG_HIDE_HELM;
4080 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4081 flags |= CORPSE_FLAG_HIDE_CLOAK;
4082 if(InBattleGround() && !InArena())
4083 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4084 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4086 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4088 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4090 uint32 iDisplayID;
4091 uint16 iIventoryType;
4092 uint32 _cfi;
4093 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4095 if(m_items[i])
4097 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4098 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4100 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4101 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4105 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4106 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4107 assert(entry);
4108 if(entry->map_type != MAP_BATTLEGROUND)
4109 corpse->SaveToDB();
4111 // register for player, but not show
4112 ObjectAccessor::Instance().AddCorpse(corpse);
4115 void Player::SpawnCorpseBones()
4117 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4118 SaveToDB(); // prevent loading as ghost without corpse
4121 Corpse* Player::GetCorpse() const
4123 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4126 void Player::DurabilityLossAll(double percent, bool inventory)
4128 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4129 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4130 DurabilityLoss(pItem,percent);
4132 if(inventory)
4134 // bags not have durability
4135 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4137 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4138 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4139 DurabilityLoss(pItem,percent);
4141 // keys not have durability
4142 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4144 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4145 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4146 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4147 if(Item* pItem = GetItemByPos( i, j ))
4148 DurabilityLoss(pItem,percent);
4152 void Player::DurabilityLoss(Item* item, double percent)
4154 if(!item )
4155 return;
4157 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4159 if(!pMaxDurability)
4160 return;
4162 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4164 if(pDurabilityLoss < 1 )
4165 pDurabilityLoss = 1;
4167 DurabilityPointsLoss(item,pDurabilityLoss);
4170 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4172 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4173 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4174 DurabilityPointsLoss(pItem,points);
4176 if(inventory)
4178 // bags not have durability
4179 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4181 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4182 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4183 DurabilityPointsLoss(pItem,points);
4185 // keys not have durability
4186 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4188 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4189 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4190 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4191 if(Item* pItem = GetItemByPos( i, j ))
4192 DurabilityPointsLoss(pItem,points);
4196 void Player::DurabilityPointsLoss(Item* item, int32 points)
4198 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4199 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4200 int32 pNewDurability = pOldDurability - points;
4202 if (pNewDurability < 0)
4203 pNewDurability = 0;
4204 else if (pNewDurability > pMaxDurability)
4205 pNewDurability = pMaxDurability;
4207 if (pOldDurability != pNewDurability)
4209 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4210 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4211 _ApplyItemMods(item,item->GetSlot(), false);
4213 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4215 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4216 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4217 _ApplyItemMods(item,item->GetSlot(), true);
4219 item->SetState(ITEM_CHANGED, this);
4223 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4225 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4226 DurabilityPointsLoss(pItem,1);
4229 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4231 uint32 TotalCost = 0;
4232 // equipped, backpack, bags itself
4233 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4234 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4236 // bank, buyback and keys not repaired
4238 // items in inventory bags
4239 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4240 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4241 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4242 return TotalCost;
4245 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4247 Item* item = GetItemByPos(pos);
4249 uint32 TotalCost = 0;
4250 if(!item)
4251 return TotalCost;
4253 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4254 if(!maxDurability)
4255 return TotalCost;
4257 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4259 if(cost)
4261 uint32 LostDurability = maxDurability - curDurability;
4262 if(LostDurability>0)
4264 ItemPrototype const *ditemProto = item->GetProto();
4266 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4267 if(!dcost)
4269 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4270 return TotalCost;
4273 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4274 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4275 if(!dQualitymodEntry)
4277 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4278 return TotalCost;
4281 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4282 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4284 costs = uint32(costs * discountMod);
4286 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4287 costs = 1;
4289 if (guildBank)
4291 if (GetGuildId()==0)
4293 DEBUG_LOG("You are not member of a guild");
4294 return TotalCost;
4297 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4298 if (!pGuild)
4299 return TotalCost;
4301 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4303 DEBUG_LOG("You do not have rights to withdraw for repairs");
4304 return TotalCost;
4307 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4309 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4310 return TotalCost;
4313 if (pGuild->GetGuildBankMoney() < costs)
4315 DEBUG_LOG("There is not enough money in bank");
4316 return TotalCost;
4319 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4320 TotalCost = costs;
4322 else if (GetMoney() < costs)
4324 DEBUG_LOG("You do not have enough money");
4325 return TotalCost;
4327 else
4328 ModifyMoney( -int32(costs) );
4332 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4333 item->SetState(ITEM_CHANGED, this);
4335 // reapply mods for total broken and repaired item if equipped
4336 if(IsEquipmentPos(pos) && !curDurability)
4337 _ApplyItemMods(item,pos & 255, true);
4338 return TotalCost;
4341 void Player::RepopAtGraveyard()
4343 // note: this can be called also when the player is alive
4344 // for example from WorldSession::HandleMovementOpcodes
4346 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4348 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4349 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4351 ResurrectPlayer(0.5f);
4352 SpawnCorpseBones();
4355 WorldSafeLocsEntry const *ClosestGrave = NULL;
4357 // Special handle for battleground maps
4358 if( BattleGround *bg = GetBattleGround() )
4359 ClosestGrave = bg->GetClosestGraveYard(this);
4360 else
4361 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4363 // stop countdown until repop
4364 m_deathTimer = 0;
4366 // if no grave found, stay at the current location
4367 // and don't show spirit healer location
4368 if(ClosestGrave)
4370 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4371 if(isDead()) // not send if alive, because it used in TeleportTo()
4373 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4374 data << ClosestGrave->map_id;
4375 data << ClosestGrave->x;
4376 data << ClosestGrave->y;
4377 data << ClosestGrave->z;
4378 GetSession()->SendPacket(&data);
4383 void Player::JoinedChannel(Channel *c)
4385 m_channels.push_back(c);
4388 void Player::LeftChannel(Channel *c)
4390 m_channels.remove(c);
4393 void Player::CleanupChannels()
4395 while(!m_channels.empty())
4397 Channel* ch = *m_channels.begin();
4398 m_channels.erase(m_channels.begin()); // remove from player's channel list
4399 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4400 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4401 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4404 sLog.outDebug("Player: channels cleaned up!");
4407 void Player::UpdateLocalChannels(uint32 newZone )
4409 if(m_channels.empty())
4410 return;
4412 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4413 if(!current_zone)
4414 return;
4416 ChannelMgr* cMgr = channelMgr(GetTeam());
4417 if(!cMgr)
4418 return;
4420 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4422 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4424 next = i; ++next;
4426 // skip non built-in channels
4427 if(!(*i)->IsConstant())
4428 continue;
4430 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4431 if(!ch)
4432 continue;
4434 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4435 continue;
4437 // new channel
4438 char new_channel_name_buf[100];
4439 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4440 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4442 if((*i)!=new_channel)
4444 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4446 // leave old channel
4447 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4448 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4449 LeftChannel(*i); // remove from player's channel list
4450 cMgr->LeftChannel(name); // delete if empty
4453 sLog.outDebug("Player: channels cleaned up!");
4456 void Player::LeaveLFGChannel()
4458 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4460 if((*i)->IsLFG())
4462 (*i)->Leave(GetGUID());
4463 break;
4468 void Player::UpdateDefense()
4470 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4472 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4474 // update dependent from defense skill part
4475 UpdateDefenseBonusesMod();
4479 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4481 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4483 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4484 return;
4487 float val = 1.0f;
4489 switch(modType)
4491 case FLAT_MOD:
4492 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4493 break;
4494 case PCT_MOD:
4495 if(amount <= -100.0f)
4496 amount = -200.0f;
4498 val = (100.0f + amount) / 100.0f;
4499 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4500 break;
4503 if(!CanModifyStats())
4504 return;
4506 switch(modGroup)
4508 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4509 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4510 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4511 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4512 default: break;
4516 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4518 if(modGroup >= BASEMOD_END || modType > MOD_END)
4520 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4521 return 0.0f;
4524 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4525 return 0.0f;
4527 return m_auraBaseMod[modGroup][modType];
4530 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4532 if(modGroup >= BASEMOD_END)
4534 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4535 return 0.0f;
4538 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4539 return 0.0f;
4541 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4544 uint32 Player::GetShieldBlockValue() const
4546 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4548 value = (value < 0) ? 0 : value;
4550 return uint32(value);
4553 float Player::GetMeleeCritFromAgility()
4555 uint32 level = getLevel();
4556 uint32 pclass = getClass();
4558 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4560 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4561 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4562 if (critBase==NULL || critRatio==NULL)
4563 return 0.0f;
4565 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4566 return crit*100.0f;
4569 float Player::GetDodgeFromAgility()
4571 // Table for base dodge values
4572 float dodge_base[MAX_CLASSES] = {
4573 0.0075f, // Warrior
4574 0.00652f, // Paladin
4575 -0.0545f, // Hunter
4576 -0.0059f, // Rogue
4577 0.03183f, // Priest
4578 0.0114f, // DK
4579 0.0167f, // Shaman
4580 0.034575f, // Mage
4581 0.02011f, // Warlock
4582 0.0f, // ??
4583 -0.0187f // Druid
4585 // Crit/agility to dodge/agility coefficient multipliers
4586 float crit_to_dodge[MAX_CLASSES] = {
4587 1.1f, // Warrior
4588 1.0f, // Paladin
4589 1.6f, // Hunter
4590 2.0f, // Rogue
4591 1.0f, // Priest
4592 1.0f, // DK?
4593 1.0f, // Shaman
4594 1.0f, // Mage
4595 1.0f, // Warlock
4596 0.0f, // ??
4597 1.7f // Druid
4600 uint32 level = getLevel();
4601 uint32 pclass = getClass();
4603 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4605 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4606 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4607 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4608 return 0.0f;
4610 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4611 return dodge*100.0f;
4614 float Player::GetSpellCritFromIntellect()
4616 uint32 level = getLevel();
4617 uint32 pclass = getClass();
4619 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4621 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4622 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4623 if (critBase==NULL || critRatio==NULL)
4624 return 0.0f;
4626 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4627 return crit*100.0f;
4630 float Player::GetRatingCoefficient(CombatRating cr) const
4632 uint32 level = getLevel();
4634 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4636 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4637 if (Rating == NULL)
4638 return 1.0f; // By default use minimum coefficient (not must be called)
4640 return Rating->ratio;
4643 float Player::GetRatingBonusValue(CombatRating cr) const
4645 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4648 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4650 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4651 if (melee>33.0f) melee = 33.0f;
4652 return uint32 (melee * damage /100.0f);
4655 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4657 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4658 if (ranged>33.0f) ranged=33.0f;
4659 return uint32 (ranged * damage /100.0f);
4662 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4664 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4665 // In wow script resilience limited to 33%
4666 if (spell>33.0f)
4667 spell = 33.0f;
4668 return uint32 (spell * damage / 100.0f);
4671 uint32 Player::GetDotDamageReduction(uint32 damage) const
4673 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4674 // Dot resilience not limited (limit it by 100%)
4675 if (spellDot > 100.0f)
4676 spellDot = 100.0f;
4677 return uint32 (spellDot * damage / 100.0f);
4680 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4682 switch (attType)
4684 case BASE_ATTACK:
4685 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4686 case OFF_ATTACK:
4687 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4688 default:
4689 break;
4691 return 0.0f;
4694 float Player::OCTRegenHPPerSpirit()
4696 uint32 level = getLevel();
4697 uint32 pclass = getClass();
4699 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4701 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4702 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4703 if (baseRatio==NULL || moreRatio==NULL)
4704 return 0.0f;
4706 // Formula from PaperDollFrame script
4707 float spirit = GetStat(STAT_SPIRIT);
4708 float baseSpirit = spirit;
4709 if (baseSpirit>50) baseSpirit = 50;
4710 float moreSpirit = spirit - baseSpirit;
4711 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4712 return regen;
4715 float Player::OCTRegenMPPerSpirit()
4717 uint32 level = getLevel();
4718 uint32 pclass = getClass();
4720 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4722 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4723 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4724 if (moreRatio==NULL)
4725 return 0.0f;
4727 // Formula get from PaperDollFrame script
4728 float spirit = GetStat(STAT_SPIRIT);
4729 float regen = spirit * moreRatio->ratio;
4730 return regen;
4733 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4735 m_baseRatingValue[cr]+=(apply ? value : -value);
4737 int32 amount = uint32(m_baseRatingValue[cr]);
4738 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4739 // stat used stored in miscValueB for this aura
4740 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4741 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4742 if ((*i)->GetMiscValue() & (1<<cr))
4743 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4744 if (amount < 0)
4745 amount = 0;
4746 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4748 float RatingCoeffecient = GetRatingCoefficient(cr);
4749 float RatingChange = 0.0f;
4751 bool affectStats = CanModifyStats();
4753 switch (cr)
4755 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4756 case CR_DEFENSE_SKILL:
4757 UpdateDefenseBonusesMod();
4758 break;
4759 case CR_DODGE:
4760 UpdateDodgePercentage();
4761 break;
4762 case CR_PARRY:
4763 UpdateParryPercentage();
4764 break;
4765 case CR_BLOCK:
4766 UpdateBlockPercentage();
4767 break;
4768 case CR_HIT_MELEE:
4769 UpdateMeleeHitChances();
4770 break;
4771 case CR_HIT_RANGED:
4772 UpdateRangedHitChances();
4773 break;
4774 case CR_HIT_SPELL:
4775 UpdateSpellHitChances();
4776 break;
4777 case CR_CRIT_MELEE:
4778 if(affectStats)
4780 UpdateCritPercentage(BASE_ATTACK);
4781 UpdateCritPercentage(OFF_ATTACK);
4783 break;
4784 case CR_CRIT_RANGED:
4785 if(affectStats)
4786 UpdateCritPercentage(RANGED_ATTACK);
4787 break;
4788 case CR_CRIT_SPELL:
4789 if(affectStats)
4790 UpdateAllSpellCritChances();
4791 break;
4792 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4793 case CR_HIT_TAKEN_RANGED:
4794 break;
4795 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4796 break;
4797 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4798 case CR_CRIT_TAKEN_RANGED:
4799 break;
4800 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4801 break;
4802 case CR_HASTE_MELEE:
4803 RatingChange = value / RatingCoeffecient;
4804 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4805 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4806 break;
4807 case CR_HASTE_RANGED:
4808 RatingChange = value / RatingCoeffecient;
4809 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4810 break;
4811 case CR_HASTE_SPELL:
4812 RatingChange = value / RatingCoeffecient;
4813 ApplyCastTimePercentMod(RatingChange,apply);
4814 break;
4815 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4816 case CR_WEAPON_SKILL_OFFHAND:
4817 case CR_WEAPON_SKILL_RANGED:
4818 break;
4819 case CR_EXPERTISE:
4820 if(affectStats)
4822 UpdateExpertise(BASE_ATTACK);
4823 UpdateExpertise(OFF_ATTACK);
4825 break;
4826 case CR_ARMOR_PENETRATION:
4827 break;
4831 void Player::SetRegularAttackTime()
4833 for(int i = 0; i < MAX_ATTACK; ++i)
4835 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4836 if(tmpitem && !tmpitem->IsBroken())
4838 ItemPrototype const *proto = tmpitem->GetProto();
4839 if(proto->Delay)
4840 SetAttackTime(WeaponAttackType(i), proto->Delay);
4841 else
4842 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4847 //skill+step, checking for max value
4848 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4850 if(!skill_id)
4851 return false;
4853 uint16 i=0;
4854 for (; i < PLAYER_MAX_SKILLS; ++i)
4855 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4856 break;
4858 if(i>=PLAYER_MAX_SKILLS)
4859 return false;
4861 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4862 uint32 value = SKILL_VALUE(data);
4863 uint32 max = SKILL_MAX(data);
4865 if ((!max) || (!value) || (value >= max))
4866 return false;
4868 if (value*512 < max*urand(0,512))
4870 uint32 new_value = value+step;
4871 if(new_value > max)
4872 new_value = max;
4874 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4875 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4876 return true;
4879 return false;
4882 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4884 if ( SkillValue >= GrayLevel )
4885 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4886 if ( SkillValue >= GreenLevel )
4887 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4888 if ( SkillValue >= YellowLevel )
4889 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4890 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4893 bool Player::UpdateCraftSkill(uint32 spellid)
4895 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4897 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4898 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4900 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4902 if(_spell_idx->second->skillId)
4904 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4906 // Alchemy Discoveries here
4907 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4908 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4910 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4911 learnSpell(discoveredSpell,false);
4914 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4916 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4917 _spell_idx->second->max_value,
4918 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4919 _spell_idx->second->min_value),
4920 craft_skill_gain);
4923 return false;
4926 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4928 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4930 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4932 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4933 switch (SkillId)
4935 case SKILL_HERBALISM:
4936 case SKILL_LOCKPICKING:
4937 case SKILL_JEWELCRAFTING:
4938 case SKILL_INSCRIPTION:
4939 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4940 case SKILL_SKINNING:
4941 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4942 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4943 else
4944 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4945 case SKILL_MINING:
4946 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4947 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4948 else
4949 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4951 return false;
4954 bool Player::UpdateFishingSkill()
4956 sLog.outDebug("UpdateFishingSkill");
4958 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4960 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4962 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4964 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4967 // levels sync. with spell requirement for skill levels to learn
4968 // bonus abilities in sSkillLineAbilityStore
4969 // Used only to avoid scan DBC at each skill grow
4970 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4972 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4974 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4975 if ( !SkillId )
4976 return false;
4978 if(Chance <= 0) // speedup in 0 chance case
4980 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4981 return false;
4984 uint16 i=0;
4985 for (; i < PLAYER_MAX_SKILLS; ++i)
4986 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4987 if ( i >= PLAYER_MAX_SKILLS )
4988 return false;
4990 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4991 uint16 SkillValue = SKILL_VALUE(data);
4992 uint16 MaxValue = SKILL_MAX(data);
4994 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4995 return false;
4997 int32 Roll = irand(1,1000);
4999 if ( Roll <= Chance )
5001 uint32 new_value = SkillValue+step;
5002 if(new_value > MaxValue)
5003 new_value = MaxValue;
5005 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5006 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5008 if((SkillValue < *bsl && new_value >= *bsl))
5010 learnSkillRewardedSpells( SkillId, new_value);
5011 break;
5014 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5015 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5016 return true;
5019 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5020 return false;
5023 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5025 // no skill gain in pvp
5026 Unit *pVictim = getVictim();
5027 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5028 return;
5030 if(IsInFeralForm())
5031 return; // always maximized SKILL_FERAL_COMBAT in fact
5033 if(m_form == FORM_TREE)
5034 return; // use weapon but not skill up
5036 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5038 switch(attType)
5040 case BASE_ATTACK:
5042 Item *tmpitem = GetWeaponForAttack(attType,true);
5044 if (!tmpitem)
5045 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5046 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5047 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5048 break;
5050 case OFF_ATTACK:
5051 case RANGED_ATTACK:
5053 Item *tmpitem = GetWeaponForAttack(attType,true);
5054 if (tmpitem)
5055 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5056 break;
5059 UpdateAllCritPercentages();
5062 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5064 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5065 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5066 uint32 moblevel = pVictim->getLevelForTarget(this);
5067 if(moblevel < greylevel)
5068 return;
5070 if (moblevel > plevel + 5)
5071 moblevel = plevel + 5;
5073 uint32 lvldif = moblevel - greylevel;
5074 if(lvldif < 3)
5075 lvldif = 3;
5077 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5078 if(skilldif <= 0)
5079 return;
5081 float chance = float(3 * lvldif * skilldif) / plevel;
5082 if(!defence)
5084 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5085 chance *= 0.1f * GetStat(STAT_INTELLECT);
5088 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5090 if(roll_chance_f(chance))
5092 if(defence)
5093 UpdateDefense();
5094 else
5095 UpdateWeaponSkill(attType);
5097 else
5098 return;
5101 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5103 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5104 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5106 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5107 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5108 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5110 if(talent) // permanent bonus stored in high part
5111 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5112 else // temporary/item bonus stored in low part
5113 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5114 return;
5118 void Player::UpdateSkillsForLevel()
5120 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5121 uint32 maxSkill = GetMaxSkillValueForLevel();
5123 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5125 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5126 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5128 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5130 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5131 if(!pSkill)
5132 continue;
5134 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5135 continue;
5137 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5138 uint32 max = SKILL_MAX(data);
5139 uint32 val = SKILL_VALUE(data);
5141 /// update only level dependent max skill values
5142 if(max!=1)
5144 /// miximize skill always
5145 if(alwaysMaxSkill)
5146 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5147 /// update max skill value if current max skill not maximized
5148 else if(max != maxconfskill)
5149 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5154 void Player::UpdateSkillsToMaxSkillsForLevel()
5156 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5157 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5159 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5160 if( IsProfessionOrRidingSkill(pskill))
5161 continue;
5162 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5164 uint32 max = SKILL_MAX(data);
5166 if(max > 1)
5167 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5169 if(pskill == SKILL_DEFENSE)
5170 UpdateDefenseBonusesMod();
5174 // This functions sets a skill line value (and adds if doesn't exist yet)
5175 // To "remove" a skill line, set it's values to zero
5176 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5178 if(!id)
5179 return;
5181 uint16 i=0;
5182 for (; i < PLAYER_MAX_SKILLS; ++i)
5183 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5185 if(i<PLAYER_MAX_SKILLS) //has skill
5187 if(currVal)
5189 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5190 learnSkillRewardedSpells(id, currVal);
5191 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5192 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5194 else //remove
5196 // clear skill fields
5197 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5198 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5199 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5201 // remove all spells that related to this skill
5202 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5203 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5204 if (pAbility->skillId==id)
5205 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5208 else if(currVal) //add
5210 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5211 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5213 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5214 if(!pSkill)
5216 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5217 return;
5219 // enable unlearn button for primary professions only
5220 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5221 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5222 else
5223 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5224 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5225 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5226 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5228 // apply skill bonuses
5229 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5231 // temporary bonuses
5232 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5233 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5234 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5235 (*j)->ApplyModifier(true);
5237 // permanent bonuses
5238 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5239 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5240 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5241 (*j)->ApplyModifier(true);
5243 // Learn all spells for skill
5244 learnSkillRewardedSpells(id, currVal);
5245 return;
5250 bool Player::HasSkill(uint32 skill) const
5252 if(!skill)return false;
5253 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5255 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5257 return true;
5260 return false;
5263 uint16 Player::GetSkillValue(uint32 skill) const
5265 if(!skill)
5266 return 0;
5268 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5270 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5272 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5274 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5275 result += SKILL_TEMP_BONUS(bonus);
5276 result += SKILL_PERM_BONUS(bonus);
5277 return result < 0 ? 0 : result;
5280 return 0;
5283 uint16 Player::GetMaxSkillValue(uint32 skill) const
5285 if(!skill)return 0;
5286 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5288 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5290 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5292 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5293 result += SKILL_TEMP_BONUS(bonus);
5294 result += SKILL_PERM_BONUS(bonus);
5295 return result < 0 ? 0 : result;
5298 return 0;
5301 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5303 if(!skill)return 0;
5304 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5306 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5308 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5311 return 0;
5314 uint16 Player::GetBaseSkillValue(uint32 skill) const
5316 if(!skill)return 0;
5317 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5319 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5321 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5322 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5323 return result < 0 ? 0 : result;
5326 return 0;
5329 uint16 Player::GetPureSkillValue(uint32 skill) const
5331 if(!skill)return 0;
5332 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5334 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5336 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5339 return 0;
5342 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5344 if(!skill)
5345 return 0;
5347 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5349 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5351 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5355 return 0;
5358 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5360 if(!skill)
5361 return 0;
5363 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5365 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5367 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5371 return 0;
5374 void Player::SendInitialActionButtons() const
5376 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5378 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5379 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5381 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5382 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5384 data << uint16(itr->second.action);
5385 data << uint8(itr->second.misc);
5386 data << uint8(itr->second.type);
5388 else
5390 data << uint32(0);
5394 GetSession()->SendPacket( &data );
5395 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5398 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5400 if(button >= MAX_ACTION_BUTTONS)
5402 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5403 return false;
5406 // check cheating with adding non-known spells to action bar
5407 if(type==ACTION_BUTTON_SPELL)
5409 if(!sSpellStore.LookupEntry(action))
5411 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5412 return false;
5415 if(!HasSpell(action))
5417 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5418 return false;
5422 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5424 if (buttonItr==m_actionButtons.end())
5425 { // just add new button
5426 m_actionButtons[button] = ActionButton(action,type,misc);
5428 else
5429 { // change state of current button
5430 ActionButtonUpdateState uState = buttonItr->second.uState;
5431 buttonItr->second = ActionButton(action,type,misc);
5432 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5435 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5436 return true;
5439 void Player::removeActionButton(uint8 button)
5441 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5442 if (buttonItr==m_actionButtons.end())
5443 return;
5445 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5446 m_actionButtons.erase(buttonItr); // new and not saved
5447 else
5448 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5450 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5453 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5455 // prevent crash when a bad coord is sent by the client
5456 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5458 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5459 return false;
5462 Map *m = GetMap();
5464 const float old_x = GetPositionX();
5465 const float old_y = GetPositionY();
5466 const float old_z = GetPositionZ();
5467 const float old_r = GetOrientation();
5469 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5471 if (teleport || old_x != x || old_y != y || old_z != z)
5472 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5473 else
5474 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5476 // move and update visible state if need
5477 m->PlayerRelocation(this, x, y, z, orientation);
5479 // reread after Map::Relocation
5480 m = GetMap();
5481 x = GetPositionX();
5482 y = GetPositionY();
5483 z = GetPositionZ();
5485 // group update
5486 if(GetGroup() && (old_x != x || old_y != y))
5487 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5490 // code block for underwater state update
5491 UpdateUnderwaterState(m, x, y, z);
5493 CheckExploreSystem();
5495 return true;
5498 void Player::SaveRecallPosition()
5500 m_recallMap = GetMapId();
5501 m_recallX = GetPositionX();
5502 m_recallY = GetPositionY();
5503 m_recallZ = GetPositionZ();
5504 m_recallO = GetOrientation();
5507 void Player::SendMessageToSet(WorldPacket *data, bool self)
5509 GetMap()->MessageBroadcast(this, data, self);
5512 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5514 GetMap()->MessageDistBroadcast(this, data, dist, self);
5517 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5519 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5522 void Player::SendDirectMessage(WorldPacket *data)
5524 GetSession()->SendPacket(data);
5527 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5529 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5530 data << uint32(CinematicSequenceId);
5531 SendDirectMessage(&data);
5534 void Player::SendMovieStart(uint32 MovieId)
5536 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5537 data << uint32(MovieId);
5538 SendDirectMessage(&data);
5541 void Player::CheckExploreSystem()
5543 if (!isAlive())
5544 return;
5546 if (isInFlight())
5547 return;
5549 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5550 if(areaFlag==0xffff)
5551 return;
5552 int offset = areaFlag / 32;
5554 if(offset >= 128)
5556 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5557 return;
5560 uint32 val = (uint32)(1 << (areaFlag % 32));
5561 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5563 if( !(currFields & val) )
5565 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5567 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5569 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5570 if(!p)
5572 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5574 else if(p->area_level > 0)
5576 uint32 area = p->ID;
5577 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5579 SendExplorationExperience(area,0);
5581 else
5583 int32 diff = int32(getLevel()) - p->area_level;
5584 uint32 XP = 0;
5585 if (diff < -5)
5587 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5589 else if (diff > 5)
5591 int32 exploration_percent = (100-((diff-5)*5));
5592 if (exploration_percent > 100)
5593 exploration_percent = 100;
5594 else if (exploration_percent < 0)
5595 exploration_percent = 0;
5597 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5599 else
5601 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5604 GiveXP( XP, NULL );
5605 SendExplorationExperience(area,XP);
5607 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5612 uint32 Player::TeamForRace(uint8 race)
5614 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5615 if(!rEntry)
5617 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5618 return ALLIANCE;
5621 switch(rEntry->TeamID)
5623 case 7: return ALLIANCE;
5624 case 1: return HORDE;
5627 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5628 return ALLIANCE;
5631 uint32 Player::getFactionForRace(uint8 race)
5633 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5634 if(!rEntry)
5636 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5637 return 0;
5640 return rEntry->FactionID;
5643 void Player::setFactionForRace(uint8 race)
5645 m_team = TeamForRace(race);
5646 setFaction( getFactionForRace(race) );
5649 ReputationRank Player::GetReputationRank(uint32 faction) const
5651 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5652 return GetReputationMgr().GetRank(factionEntry);
5655 //Calculate total reputation percent player gain with quest/creature level
5656 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5658 float percent = 100.0f;
5660 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5662 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5663 percent *= rate;
5665 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5667 percent += rep > 0 ? repMod : -repMod;
5669 if(percent <= 0.0f)
5670 return 0;
5672 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5675 //Calculates how many reputation points player gains in victim's enemy factions
5676 void Player::RewardReputation(Unit *pVictim, float rate)
5678 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5679 return;
5681 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5683 if(!Rep)
5684 return;
5686 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5688 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5689 donerep1 = int32(donerep1*rate);
5690 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5691 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5692 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5693 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5695 // Wiki: Team factions value divided by 2
5696 if (factionEntry1 && Rep->is_teamaward1)
5698 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5699 if(team1_factionEntry)
5700 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5704 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5706 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5707 donerep2 = int32(donerep2*rate);
5708 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5709 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5710 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5711 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5713 // Wiki: Team factions value divided by 2
5714 if (factionEntry2 && Rep->is_teamaward2)
5716 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5717 if(team2_factionEntry)
5718 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5723 //Calculate how many reputation points player gain with the quest
5724 void Player::RewardReputation(Quest const *pQuest)
5726 // quest reputation reward/loss
5727 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5729 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5731 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5732 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5733 if(factionEntry)
5734 GetReputationMgr().ModifyReputation(factionEntry, rep);
5738 // TODO: implement reputation spillover
5741 void Player::UpdateArenaFields(void)
5743 /* arena calcs go here */
5746 void Player::UpdateHonorFields()
5748 /// called when rewarding honor and at each save
5749 uint64 now = time(NULL);
5750 uint64 today = uint64(time(NULL) / DAY) * DAY;
5752 if(m_lastHonorUpdateTime < today)
5754 uint64 yesterday = today - DAY;
5756 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5758 // update yesterday's contribution
5759 if(m_lastHonorUpdateTime >= yesterday )
5761 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5763 // this is the first update today, reset today's contribution
5764 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5765 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5767 else
5769 // no honor/kills yesterday or today, reset
5770 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5771 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5775 m_lastHonorUpdateTime = now;
5778 ///Calculate the amount of honor gained based on the victim
5779 ///and the size of the group for which the honor is divided
5780 ///An exact honor value can also be given (overriding the calcs)
5781 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5783 // do not reward honor in arenas, but enable onkill spellproc
5784 if(InArena())
5786 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5787 return false;
5789 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5790 return false;
5792 return true;
5795 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5796 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5797 return false;
5799 uint64 victim_guid = 0;
5800 uint32 victim_rank = 0;
5802 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5803 UpdateHonorFields();
5805 if(honor <= 0)
5807 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5808 return false;
5810 victim_guid = uVictim->GetGUID();
5812 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5814 Player *pVictim = (Player *)uVictim;
5816 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5817 return false;
5819 float f = 1; //need for total kills (?? need more info)
5820 uint32 k_grey = 0;
5821 uint32 k_level = getLevel();
5822 uint32 v_level = pVictim->getLevel();
5825 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5826 // [0] Just name
5827 // [1..14] Alliance honor titles and player name
5828 // [15..28] Horde honor titles and player name
5829 // [29..38] Other title and player name
5830 // [39+] Nothing
5831 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5832 // Get Killer titles, CharTitlesEntry::bit_index
5833 // Ranks:
5834 // title[1..14] -> rank[5..18]
5835 // title[15..28] -> rank[5..18]
5836 // title[other] -> 0
5837 if (victim_title == 0)
5838 victim_guid = 0; // Don't show HK: <rank> message, only log.
5839 else if (victim_title < 15)
5840 victim_rank = victim_title + 4;
5841 else if (victim_title < 29)
5842 victim_rank = victim_title - 14 + 4;
5843 else
5844 victim_guid = 0; // Don't show HK: <rank> message, only log.
5847 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5849 if(v_level<=k_grey)
5850 return false;
5852 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5854 int32 v_rank =1; //need more info
5856 honor = ((f * diff_level * (190 + v_rank*10))/6);
5857 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5859 // count the number of playerkills in one day
5860 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5861 // and those in a lifetime
5862 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5863 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5864 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5865 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5867 else
5869 Creature *cVictim = (Creature *)uVictim;
5871 if (!cVictim->isRacialLeader())
5872 return false;
5874 honor = 100; // ??? need more info
5875 victim_rank = 19; // HK: Leader
5879 if (uVictim != NULL)
5881 honor *= sWorld.getRate(RATE_HONOR);
5883 if(groupsize > 1)
5884 honor /= groupsize;
5886 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5889 // honor - for show honor points in log
5890 // victim_guid - for show victim name in log
5891 // victim_rank [1..4] HK: <dishonored rank>
5892 // victim_rank [5..19] HK: <alliance\horde rank>
5893 // victim_rank [0,20+] HK: <>
5894 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5895 data << (uint32) honor;
5896 data << (uint64) victim_guid;
5897 data << (uint32) victim_rank;
5899 GetSession()->SendPacket(&data);
5901 // add honor points
5902 ModifyHonorPoints(int32(honor));
5904 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5905 return true;
5908 void Player::ModifyHonorPoints( int32 value )
5910 if(value < 0)
5912 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5913 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5914 else
5915 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5917 else
5918 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5921 void Player::ModifyArenaPoints( int32 value )
5923 if(value < 0)
5925 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5926 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5927 else
5928 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5930 else
5931 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5934 uint32 Player::GetGuildIdFromDB(uint64 guid)
5936 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5937 if(!result)
5938 return 0;
5940 uint32 id = result->Fetch()[0].GetUInt32();
5941 delete result;
5942 return id;
5945 uint32 Player::GetRankFromDB(uint64 guid)
5947 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5948 if( result )
5950 uint32 v = result->Fetch()[0].GetUInt32();
5951 delete result;
5952 return v;
5954 else
5955 return 0;
5958 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5960 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);
5961 if(!result)
5962 return 0;
5964 uint32 id = (*result)[0].GetUInt32();
5965 delete result;
5966 return id;
5969 uint32 Player::GetZoneIdFromDB(uint64 guid)
5971 uint32 guidLow = GUID_LOPART(guid);
5972 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5973 if (!result)
5974 return 0;
5975 Field* fields = result->Fetch();
5976 uint32 zone = fields[0].GetUInt32();
5977 delete result;
5979 if (!zone)
5981 // stored zone is zero, use generic and slow zone detection
5982 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5983 if( !result )
5984 return 0;
5985 fields = result->Fetch();
5986 uint32 map = fields[0].GetUInt32();
5987 float posx = fields[1].GetFloat();
5988 float posy = fields[2].GetFloat();
5989 float posz = fields[3].GetFloat();
5990 delete result;
5992 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5994 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5997 return zone;
6000 void Player::UpdateArea(uint32 newArea)
6002 // FFA_PVP flags are area and not zone id dependent
6003 // so apply them accordingly
6004 m_areaUpdateId = newArea;
6006 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6008 if(area && (area->flags & AREA_FLAG_ARENA))
6010 if(!isGameMaster())
6011 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6013 else
6015 // remove ffa flag only if not ffapvp realm
6016 // removal in sanctuaries and capitals is handled in zone update
6017 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6018 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6021 UpdateAreaDependentAuras(newArea);
6024 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6026 if(m_zoneUpdateId != newZone)
6027 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6029 m_zoneUpdateId = newZone;
6030 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6032 // zone changed, so area changed as well, update it
6033 UpdateArea(newArea);
6035 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6036 if(!zone)
6037 return;
6039 if (sWorld.getConfig(CONFIG_WEATHER))
6041 Weather *wth = sWorld.FindWeather(zone->ID);
6042 if(wth)
6044 wth->SendWeatherUpdateToPlayer(this);
6046 else
6048 if(!sWorld.AddWeather(zone->ID))
6050 // send fine weather packet to remove old zone's weather
6051 Weather::SendFineWeatherUpdateToPlayer(this);
6056 pvpInfo.inHostileArea =
6057 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6058 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6059 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6060 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6062 if(pvpInfo.inHostileArea) // in hostile area
6064 if(!IsPvP() || pvpInfo.endTimer != 0)
6065 UpdatePvP(true, true);
6067 else // in friendly area
6069 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6070 pvpInfo.endTimer = time(0); // start toggle-off
6073 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6075 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6076 if(sWorld.IsFFAPvPRealm())
6077 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6079 else
6081 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6084 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6086 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6087 SetRestType(REST_TYPE_IN_CITY);
6088 InnEnter(time(0),GetMapId(),0,0,0);
6090 if(sWorld.IsFFAPvPRealm())
6091 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6093 else // anywhere else
6095 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6097 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6099 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6101 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6102 SetRestType(REST_TYPE_NO);
6104 if(sWorld.IsFFAPvPRealm())
6105 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6108 else // not in tavern (leave city then)
6110 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6111 SetRestType(REST_TYPE_NO);
6113 // Set player to FFA PVP when not in rested environment.
6114 if(sWorld.IsFFAPvPRealm())
6115 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6120 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6121 // if player resurrected at teleport this will be applied in resurrect code
6122 if(isAlive())
6123 DestroyZoneLimitedItem( true, newZone );
6125 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6126 AutoUnequipOffhandIfNeed();
6128 // recent client version not send leave/join channel packets for built-in local channels
6129 UpdateLocalChannels( newZone );
6131 // group update
6132 if(GetGroup())
6133 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6135 UpdateZoneDependentAuras(newZone);
6138 //If players are too far way of duel flag... then player loose the duel
6139 void Player::CheckDuelDistance(time_t currTime)
6141 if(!duel)
6142 return;
6144 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6145 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6146 if(!obj)
6147 return;
6149 if(duel->outOfBound == 0)
6151 if(!IsWithinDistInMap(obj, 50))
6153 duel->outOfBound = currTime;
6155 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6156 GetSession()->SendPacket(&data);
6159 else
6161 if(IsWithinDistInMap(obj, 40))
6163 duel->outOfBound = 0;
6165 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6166 GetSession()->SendPacket(&data);
6168 else if(currTime >= (duel->outOfBound+10))
6170 DuelComplete(DUEL_FLED);
6175 void Player::DuelComplete(DuelCompleteType type)
6177 // duel not requested
6178 if(!duel)
6179 return;
6181 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6182 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6183 GetSession()->SendPacket(&data);
6184 duel->opponent->GetSession()->SendPacket(&data);
6186 if(type != DUEL_INTERUPTED)
6188 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6189 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6190 data << duel->opponent->GetName();
6191 data << GetName();
6192 SendMessageToSet(&data,true);
6195 if (type == DUEL_WON)
6197 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6198 if (duel->opponent)
6199 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6202 // cool-down duel spell
6203 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6205 data<<GetGUID();
6206 data<<uint8(0x0);
6208 data<<(uint32)7266;
6209 data<<uint32(0x0);
6210 GetSession()->SendPacket(&data);
6211 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6212 data<<duel->opponent->GetGUID();
6213 data<<uint8(0x0);
6214 data<<(uint32)7266;
6215 data<<uint32(0x0);
6216 duel->opponent->GetSession()->SendPacket(&data);*/
6218 //Remove Duel Flag object
6219 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6220 if(obj)
6221 duel->initiator->RemoveGameObject(obj,true);
6223 /* remove auras */
6224 std::vector<uint32> auras2remove;
6225 AuraMap const& vAuras = duel->opponent->GetAuras();
6226 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6228 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6229 auras2remove.push_back(i->second->GetId());
6232 for(size_t i=0; i<auras2remove.size(); ++i)
6233 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6235 auras2remove.clear();
6236 AuraMap const& auras = GetAuras();
6237 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6239 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6240 auras2remove.push_back(i->second->GetId());
6242 for(size_t i=0; i<auras2remove.size(); ++i)
6243 RemoveAurasDueToSpell(auras2remove[i]);
6245 // cleanup combo points
6246 if(GetComboTarget()==duel->opponent->GetGUID())
6247 ClearComboPoints();
6248 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6249 ClearComboPoints();
6251 if(duel->opponent->GetComboTarget()==GetGUID())
6252 duel->opponent->ClearComboPoints();
6253 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6254 duel->opponent->ClearComboPoints();
6256 //cleanups
6257 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6258 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6259 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6260 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6262 delete duel->opponent->duel;
6263 duel->opponent->duel = NULL;
6264 delete duel;
6265 duel = NULL;
6268 //---------------------------------------------------------//
6270 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6272 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6273 return;
6275 // not apply/remove mods for broken item
6276 if(item->IsBroken())
6277 return;
6279 ItemPrototype const *proto = item->GetProto();
6281 if(!proto)
6282 return;
6284 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6286 uint32 attacktype = Player::GetAttackBySlot(slot);
6287 if(attacktype < MAX_ATTACK)
6288 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6290 _ApplyItemBonuses(proto,slot,apply);
6292 if( slot==EQUIPMENT_SLOT_RANGED )
6293 _ApplyAmmoBonuses();
6295 ApplyItemEquipSpell(item,apply);
6296 ApplyEnchantment(item, apply);
6298 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6299 CorrectMetaGemEnchants(slot, apply);
6301 sLog.outDebug("_ApplyItemMods complete.");
6304 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6306 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6307 return;
6309 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6311 uint32 statType = 0;
6312 int32 val = 0;
6314 if(proto->ScalingStatDistribution)
6316 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6318 statType = ssd->StatMod[i];
6320 if(uint32 modifier = ssd->Modifier[i])
6322 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6323 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6325 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6326 val = (multiplier * modifier) / 10000;
6331 else
6333 statType = proto->ItemStat[i].ItemStatType;
6334 val = proto->ItemStat[i].ItemStatValue;
6337 if(val == 0)
6338 continue;
6340 switch (statType)
6342 case ITEM_MOD_MANA:
6343 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6344 break;
6345 case ITEM_MOD_HEALTH: // modify HP
6346 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6347 break;
6348 case ITEM_MOD_AGILITY: // modify agility
6349 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6350 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6351 break;
6352 case ITEM_MOD_STRENGTH: //modify strength
6353 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6354 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6355 break;
6356 case ITEM_MOD_INTELLECT: //modify intellect
6357 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6358 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6359 break;
6360 case ITEM_MOD_SPIRIT: //modify spirit
6361 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6362 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6363 break;
6364 case ITEM_MOD_STAMINA: //modify stamina
6365 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6366 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6367 break;
6368 case ITEM_MOD_DEFENSE_SKILL_RATING:
6369 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6370 break;
6371 case ITEM_MOD_DODGE_RATING:
6372 ApplyRatingMod(CR_DODGE, int32(val), apply);
6373 break;
6374 case ITEM_MOD_PARRY_RATING:
6375 ApplyRatingMod(CR_PARRY, int32(val), apply);
6376 break;
6377 case ITEM_MOD_BLOCK_RATING:
6378 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6379 break;
6380 case ITEM_MOD_HIT_MELEE_RATING:
6381 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6382 break;
6383 case ITEM_MOD_HIT_RANGED_RATING:
6384 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6385 break;
6386 case ITEM_MOD_HIT_SPELL_RATING:
6387 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6388 break;
6389 case ITEM_MOD_CRIT_MELEE_RATING:
6390 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6391 break;
6392 case ITEM_MOD_CRIT_RANGED_RATING:
6393 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6394 break;
6395 case ITEM_MOD_CRIT_SPELL_RATING:
6396 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6397 break;
6398 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6399 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6400 break;
6401 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6402 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6403 break;
6404 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6405 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6406 break;
6407 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6408 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6409 break;
6410 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6411 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6412 break;
6413 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6414 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6415 break;
6416 case ITEM_MOD_HASTE_MELEE_RATING:
6417 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6418 break;
6419 case ITEM_MOD_HASTE_RANGED_RATING:
6420 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6421 break;
6422 case ITEM_MOD_HASTE_SPELL_RATING:
6423 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6424 break;
6425 case ITEM_MOD_HIT_RATING:
6426 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6427 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6428 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6429 break;
6430 case ITEM_MOD_CRIT_RATING:
6431 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6432 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6433 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6434 break;
6435 case ITEM_MOD_HIT_TAKEN_RATING:
6436 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6437 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6438 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6439 break;
6440 case ITEM_MOD_CRIT_TAKEN_RATING:
6441 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6442 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6443 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6444 break;
6445 case ITEM_MOD_RESILIENCE_RATING:
6446 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6447 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6448 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6449 break;
6450 case ITEM_MOD_HASTE_RATING:
6451 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6452 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6453 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6454 break;
6455 case ITEM_MOD_EXPERTISE_RATING:
6456 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6457 break;
6458 case ITEM_MOD_ATTACK_POWER:
6459 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6460 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6461 break;
6462 case ITEM_MOD_RANGED_ATTACK_POWER:
6463 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6464 break;
6465 case ITEM_MOD_FERAL_ATTACK_POWER:
6466 ApplyFeralAPBonus(int32(val), apply);
6467 break;
6468 case ITEM_MOD_SPELL_HEALING_DONE:
6469 ApplySpellHealingBonus(int32(val), apply);
6470 break;
6471 case ITEM_MOD_SPELL_DAMAGE_DONE:
6472 ApplySpellDamageBonus(int32(val), apply);
6473 break;
6474 case ITEM_MOD_MANA_REGENERATION:
6475 ApplyManaRegenBonus(int32(val), apply);
6476 break;
6477 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6478 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6479 break;
6480 case ITEM_MOD_SPELL_POWER:
6481 ApplySpellHealingBonus(int32(val), apply);
6482 ApplySpellDamageBonus(int32(val), apply);
6483 break;
6487 if (proto->Armor)
6488 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6490 if (proto->Block)
6491 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6493 if (proto->HolyRes)
6494 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6496 if (proto->FireRes)
6497 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6499 if (proto->NatureRes)
6500 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6502 if (proto->FrostRes)
6503 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6505 if (proto->ShadowRes)
6506 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6508 if (proto->ArcaneRes)
6509 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6511 WeaponAttackType attType = BASE_ATTACK;
6512 float damage = 0.0f;
6514 if( slot == EQUIPMENT_SLOT_RANGED && (
6515 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6516 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6518 attType = RANGED_ATTACK;
6520 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6522 attType = OFF_ATTACK;
6525 if (proto->Damage[0].DamageMin > 0 )
6527 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6528 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6529 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6532 if (proto->Damage[0].DamageMax > 0 )
6534 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6535 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6538 // Druids get feral AP bonus from weapon dps
6539 if(getClass() == CLASS_DRUID)
6541 int32 feral_bonus = proto->getFeralBonus();
6542 if (feral_bonus > 0)
6543 ApplyFeralAPBonus(feral_bonus, apply);
6546 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6547 return;
6549 if (proto->Delay)
6551 if(slot == EQUIPMENT_SLOT_RANGED)
6552 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6553 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6554 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6555 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6556 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6559 if(CanModifyStats() && (damage || proto->Delay))
6560 UpdateDamagePhysical(attType);
6563 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6565 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6566 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6567 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6569 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6570 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6571 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6573 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6574 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6575 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6578 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6580 // generic not weapon specific case processes in aura code
6581 if(aura->GetSpellProto()->EquippedItemClass == -1)
6582 return;
6584 BaseModGroup mod = BASEMOD_END;
6585 switch(attackType)
6587 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6588 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6589 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6590 default: return;
6593 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6595 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6599 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6601 // ignore spell mods for not wands
6602 Modifier const* modifier = aura->GetModifier();
6603 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6604 return;
6606 // generic not weapon specific case processes in aura code
6607 if(aura->GetSpellProto()->EquippedItemClass == -1)
6608 return;
6610 UnitMods unitMod = UNIT_MOD_END;
6611 switch(attackType)
6613 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6614 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6615 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6616 default: return;
6619 UnitModifierType unitModType = TOTAL_VALUE;
6620 switch(modifier->m_auraname)
6622 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6623 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6624 default: return;
6627 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6629 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6633 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6635 if(!item)
6636 return;
6638 ItemPrototype const *proto = item->GetProto();
6639 if(!proto)
6640 return;
6642 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6644 _Spell const& spellData = proto->Spells[i];
6646 // no spell
6647 if(!spellData.SpellId )
6648 continue;
6650 // wrong triggering type
6651 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6652 continue;
6654 // check if it is valid spell
6655 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6656 if(!spellproto)
6657 continue;
6659 ApplyEquipSpell(spellproto,item,apply,form_change);
6663 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6665 if(apply)
6667 // Cannot be used in this stance/form
6668 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6669 return;
6671 if(form_change) // check aura active state from other form
6673 bool found = false;
6674 for (int k=0; k < 3; ++k)
6676 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6677 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6679 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6681 found = true;
6682 break;
6685 if(found)
6686 break;
6689 if(found) // and skip re-cast already active aura at form change
6690 return;
6693 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6695 CastSpell(this,spellInfo,true,item);
6697 else
6699 if(form_change) // check aura compatibility
6701 // Cannot be used in this stance/form
6702 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6703 return; // and remove only not compatible at form change
6706 if(item)
6707 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6708 else
6709 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6713 void Player::UpdateEquipSpellsAtFormChange()
6715 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6717 if(m_items[i] && !m_items[i]->IsBroken())
6719 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6720 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6724 // item set bonuses not dependent from item broken state
6725 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6727 ItemSetEffect* eff = ItemSetEff[setindex];
6728 if(!eff)
6729 continue;
6731 for(uint32 y=0;y<8; ++y)
6733 SpellEntry const* spellInfo = eff->spells[y];
6734 if(!spellInfo)
6735 continue;
6737 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6738 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6743 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6745 if(!item || item->IsBroken())
6746 return;
6748 ItemPrototype const *proto = item->GetProto();
6749 if(!proto)
6750 return;
6752 if (!Target || Target == this )
6753 return;
6755 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6757 _Spell const& spellData = proto->Spells[i];
6759 // no spell
6760 if(!spellData.SpellId )
6761 continue;
6763 // wrong triggering type
6764 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6765 continue;
6767 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6768 if(!spellInfo)
6770 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6771 continue;
6774 // not allow proc extra attack spell at extra attack
6775 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6776 return;
6778 float chance = spellInfo->procChance;
6780 if(spellData.SpellPPMRate)
6782 uint32 WeaponSpeed = GetAttackTime(attType);
6783 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6785 else if(chance > 100.0f)
6787 chance = GetWeaponProcChance();
6790 if (roll_chance_f(chance))
6791 CastSpell(Target, spellInfo->Id, true, item);
6794 // item combat enchantments
6795 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6797 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6798 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6799 if(!pEnchant) continue;
6800 for (int s=0;s<3;s++)
6802 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6803 continue;
6805 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6806 if (!spellInfo)
6808 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6809 continue;
6812 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6813 if (roll_chance_f(chance))
6815 if(IsPositiveSpell(pEnchant->spellid[s]))
6816 CastSpell(this, pEnchant->spellid[s], true, item);
6817 else
6818 CastSpell(Target, pEnchant->spellid[s], true, item);
6824 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6826 ItemPrototype const* proto = item->GetProto();
6827 // special learning case
6828 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6830 uint32 learn_spell_id = proto->Spells[0].SpellId;
6831 uint32 learning_spell_id = proto->Spells[1].SpellId;
6833 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6834 if(!spellInfo)
6836 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6837 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6838 return;
6841 Spell *spell = new Spell(this, spellInfo, false);
6842 spell->m_CastItem = item;
6843 spell->m_cast_count = cast_count; //set count of casts
6844 spell->m_currentBasePoints[0] = learning_spell_id;
6845 spell->prepare(&targets);
6846 return;
6849 // use triggered flag only for items with many spell casts and for not first cast
6850 int count = 0;
6852 // item spells casted at use
6853 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6855 _Spell const& spellData = proto->Spells[i];
6857 // no spell
6858 if(!spellData.SpellId)
6859 continue;
6861 // wrong triggering type
6862 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6863 continue;
6865 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6866 if(!spellInfo)
6868 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6869 continue;
6872 Spell *spell = new Spell(this, spellInfo, (count > 0));
6873 spell->m_CastItem = item;
6874 spell->m_cast_count = cast_count; // set count of casts
6875 spell->m_glyphIndex = glyphIndex; // glyph index
6876 spell->prepare(&targets);
6878 ++count;
6881 // Item enchantments spells casted at use
6882 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6884 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6885 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6886 if(!pEnchant) continue;
6887 for (int s=0;s<3;s++)
6889 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6890 continue;
6892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6893 if (!spellInfo)
6895 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6896 continue;
6899 Spell *spell = new Spell(this, spellInfo, (count > 0));
6900 spell->m_CastItem = item;
6901 spell->m_cast_count = cast_count; // set count of casts
6902 spell->m_glyphIndex = glyphIndex; // glyph index
6903 spell->prepare(&targets);
6905 ++count;
6910 void Player::_RemoveAllItemMods()
6912 sLog.outDebug("_RemoveAllItemMods start.");
6914 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6916 if(m_items[i])
6918 ItemPrototype const *proto = m_items[i]->GetProto();
6919 if(!proto)
6920 continue;
6922 // item set bonuses not dependent from item broken state
6923 if(proto->ItemSet)
6924 RemoveItemsSetItem(this,proto);
6926 if(m_items[i]->IsBroken())
6927 continue;
6929 ApplyItemEquipSpell(m_items[i],false);
6930 ApplyEnchantment(m_items[i], false);
6934 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6936 if(m_items[i])
6938 if(m_items[i]->IsBroken())
6939 continue;
6940 ItemPrototype const *proto = m_items[i]->GetProto();
6941 if(!proto)
6942 continue;
6944 uint32 attacktype = Player::GetAttackBySlot(i);
6945 if(attacktype < MAX_ATTACK)
6946 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6948 _ApplyItemBonuses(proto,i, false);
6950 if( i == EQUIPMENT_SLOT_RANGED )
6951 _ApplyAmmoBonuses();
6955 sLog.outDebug("_RemoveAllItemMods complete.");
6958 void Player::_ApplyAllItemMods()
6960 sLog.outDebug("_ApplyAllItemMods start.");
6962 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6964 if(m_items[i])
6966 if(m_items[i]->IsBroken())
6967 continue;
6969 ItemPrototype const *proto = m_items[i]->GetProto();
6970 if(!proto)
6971 continue;
6973 uint32 attacktype = Player::GetAttackBySlot(i);
6974 if(attacktype < MAX_ATTACK)
6975 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6977 _ApplyItemBonuses(proto,i, true);
6979 if( i == EQUIPMENT_SLOT_RANGED )
6980 _ApplyAmmoBonuses();
6984 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6986 if(m_items[i])
6988 ItemPrototype const *proto = m_items[i]->GetProto();
6989 if(!proto)
6990 continue;
6992 // item set bonuses not dependent from item broken state
6993 if(proto->ItemSet)
6994 AddItemsSetItem(this,m_items[i]);
6996 if(m_items[i]->IsBroken())
6997 continue;
6999 ApplyItemEquipSpell(m_items[i],true);
7000 ApplyEnchantment(m_items[i], true);
7004 sLog.outDebug("_ApplyAllItemMods complete.");
7007 void Player::_ApplyAmmoBonuses()
7009 // check ammo
7010 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7011 if(!ammo_id)
7012 return;
7014 float currentAmmoDPS;
7016 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7017 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7018 currentAmmoDPS = 0.0f;
7019 else
7020 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7022 if(currentAmmoDPS == GetAmmoDPS())
7023 return;
7025 m_ammoDPS = currentAmmoDPS;
7027 if(CanModifyStats())
7028 UpdateDamagePhysical(RANGED_ATTACK);
7031 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7033 if(!ammo_proto)
7034 return false;
7036 // check ranged weapon
7037 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7038 if(!weapon || weapon->IsBroken() )
7039 return false;
7041 ItemPrototype const* weapon_proto = weapon->GetProto();
7042 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7043 return false;
7045 // check ammo ws. weapon compatibility
7046 switch(weapon_proto->SubClass)
7048 case ITEM_SUBCLASS_WEAPON_BOW:
7049 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7050 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7051 return false;
7052 break;
7053 case ITEM_SUBCLASS_WEAPON_GUN:
7054 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7055 return false;
7056 break;
7057 default:
7058 return false;
7061 return true;
7064 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7065 Called by remove insignia spell effect */
7066 void Player::RemovedInsignia(Player* looterPlr)
7068 if (!GetBattleGroundId())
7069 return;
7071 // If not released spirit, do it !
7072 if(m_deathTimer > 0)
7074 m_deathTimer = 0;
7075 BuildPlayerRepop();
7076 RepopAtGraveyard();
7079 Corpse *corpse = GetCorpse();
7080 if (!corpse)
7081 return;
7083 // We have to convert player corpse to bones, not to be able to resurrect there
7084 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7085 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7086 if (!bones)
7087 return;
7089 // Now we must make bones lootable, and send player loot
7090 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7092 // We store the level of our player in the gold field
7093 // We retrieve this information at Player::SendLoot()
7094 bones->loot.gold = getLevel();
7095 bones->lootRecipient = looterPlr;
7096 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7099 void Player::SendLootRelease( uint64 guid )
7101 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7102 data << uint64(guid) << uint8(1);
7103 SendDirectMessage( &data );
7106 void Player::SendLoot(uint64 guid, LootType loot_type)
7108 if (uint64 lguid = GetLootGUID())
7109 m_session->DoLootRelease(lguid);
7111 Loot *loot = 0;
7112 PermissionTypes permission = ALL_PERMISSION;
7114 sLog.outDebug("Player::SendLoot");
7115 if (IS_GAMEOBJECT_GUID(guid))
7117 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7118 GameObject *go = GetMap()->GetGameObject(guid);
7120 // not check distance for GO in case owned GO (fishing bobber case, for example)
7121 // And permit out of range GO with no owner in case fishing hole
7122 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7124 SendLootRelease(guid);
7125 return;
7128 loot = &go->loot;
7130 if (go->getLootState() == GO_READY)
7132 uint32 lootid = go->GetLootId();
7134 if (lootid)
7136 sLog.outDebug(" if(lootid)");
7137 loot->clear();
7138 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7141 if (loot_type == LOOT_FISHING)
7142 go->getFishLoot(loot,this);
7144 go->SetLootState(GO_ACTIVATED);
7147 else if (IS_ITEM_GUID(guid))
7149 Item *item = GetItemByGuid( guid );
7151 if (!item)
7153 SendLootRelease(guid);
7154 return;
7157 loot = &item->loot;
7159 if (!item->m_lootGenerated)
7161 item->m_lootGenerated = true;
7162 loot->clear();
7164 switch(loot_type)
7166 case LOOT_DISENCHANTING:
7167 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7168 break;
7169 case LOOT_PROSPECTING:
7170 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7171 break;
7172 case LOOT_MILLING:
7173 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7174 break;
7175 default:
7176 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7177 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7178 break;
7182 else if (IS_CORPSE_GUID(guid)) // remove insignia
7184 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7186 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7188 SendLootRelease(guid);
7189 return;
7192 loot = &bones->loot;
7194 if (!bones->lootForBody)
7196 bones->lootForBody = true;
7197 uint32 pLevel = bones->loot.gold;
7198 bones->loot.clear();
7199 // It may need a better formula
7200 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7201 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7204 if (bones->lootRecipient != this)
7205 permission = NONE_PERMISSION;
7207 else
7209 Creature *creature = GetMap()->GetCreature(guid);
7211 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7212 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7214 SendLootRelease(guid);
7215 return;
7218 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7220 SendLootRelease(guid);
7221 return;
7224 loot = &creature->loot;
7226 if (loot_type == LOOT_PICKPOCKETING)
7228 if (!creature->lootForPickPocketed)
7230 creature->lootForPickPocketed = true;
7231 loot->clear();
7233 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7234 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7236 // Generate extra money for pick pocket loot
7237 const uint32 a = urand(0, creature->getLevel()/2);
7238 const uint32 b = urand(0, getLevel()/2);
7239 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7242 else
7244 // the player whose group may loot the corpse
7245 Player *recipient = creature->GetLootRecipient();
7246 if (!recipient)
7248 creature->SetLootRecipient(this);
7249 recipient = this;
7252 if (creature->lootForPickPocketed)
7254 creature->lootForPickPocketed = false;
7255 loot->clear();
7258 if (!creature->lootForBody)
7260 creature->lootForBody = true;
7261 loot->clear();
7263 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7264 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7266 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7268 if (Group* group = recipient->GetGroup())
7270 group->UpdateLooterGuid(creature,true);
7272 switch (group->GetLootMethod())
7274 case GROUP_LOOT:
7275 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7276 group->GroupLoot(recipient->GetGUID(), loot, creature);
7277 break;
7278 case NEED_BEFORE_GREED:
7279 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7280 break;
7281 case MASTER_LOOT:
7282 group->MasterLoot(recipient->GetGUID(), loot, creature);
7283 break;
7284 default:
7285 break;
7290 // possible only if creature->lootForBody && loot->empty() at spell cast check
7291 if (loot_type == LOOT_SKINNING)
7293 loot->clear();
7294 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7296 // set group rights only for loot_type != LOOT_SKINNING
7297 else
7299 if(Group* group = GetGroup())
7301 if (group == recipient->GetGroup())
7303 if (group->GetLootMethod() == FREE_FOR_ALL)
7304 permission = ALL_PERMISSION;
7305 else if (group->GetLooterGuid() == GetGUID())
7307 if (group->GetLootMethod() == MASTER_LOOT)
7308 permission = MASTER_PERMISSION;
7309 else
7310 permission = ALL_PERMISSION;
7312 else
7313 permission = GROUP_PERMISSION;
7315 else
7316 permission = NONE_PERMISSION;
7318 else if (recipient == this)
7319 permission = ALL_PERMISSION;
7320 else
7321 permission = NONE_PERMISSION;
7326 SetLootGUID(guid);
7328 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7329 switch(loot_type)
7331 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7332 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7333 default: break;
7336 // need know merged fishing/corpse loot type for achievements
7337 loot->loot_type = loot_type;
7339 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7341 data << uint64(guid);
7342 data << uint8(loot_type);
7343 data << LootView(*loot, this, permission);
7345 SendDirectMessage(&data);
7347 // add 'this' player as one of the players that are looting 'loot'
7348 if (permission != NONE_PERMISSION)
7349 loot->AddLooter(GetGUID());
7351 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7352 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7355 void Player::SendNotifyLootMoneyRemoved()
7357 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7358 GetSession()->SendPacket( &data );
7361 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7363 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7364 data << uint8(lootSlot);
7365 GetSession()->SendPacket( &data );
7368 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7370 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7371 data << Field;
7372 data << Value;
7373 GetSession()->SendPacket(&data);
7376 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7378 // data depends on zoneid/mapid...
7379 BattleGround* bg = GetBattleGround();
7380 uint16 NumberOfFields = 0;
7381 uint32 mapid = GetMapId();
7383 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7385 // may be exist better way to do this...
7386 switch(zoneid)
7388 case 0:
7389 case 1:
7390 case 4:
7391 case 8:
7392 case 10:
7393 case 11:
7394 case 12:
7395 case 36:
7396 case 38:
7397 case 40:
7398 case 41:
7399 case 51:
7400 case 267:
7401 case 1519:
7402 case 1537:
7403 case 2257:
7404 case 2918:
7405 NumberOfFields = 8;
7406 break;
7407 case 139:
7408 NumberOfFields = 41;
7409 break;
7410 case 1377:
7411 NumberOfFields = 15;
7412 break;
7413 case 2597:
7414 NumberOfFields = 83;
7415 break;
7416 case 3277:
7417 NumberOfFields = 16;
7418 break;
7419 case 3358:
7420 case 3820:
7421 NumberOfFields = 40;
7422 break;
7423 case 3483:
7424 NumberOfFields = 27;
7425 break;
7426 case 3518:
7427 NumberOfFields = 39;
7428 break;
7429 case 3519:
7430 NumberOfFields = 38;
7431 break;
7432 case 3521:
7433 NumberOfFields = 37;
7434 break;
7435 case 3698:
7436 case 3702:
7437 case 3968:
7438 NumberOfFields = 11;
7439 break;
7440 case 3703:
7441 NumberOfFields = 11;
7442 break;
7443 default:
7444 NumberOfFields = 12;
7445 break;
7448 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7449 data << uint32(mapid); // mapid
7450 data << uint32(zoneid); // zone id
7451 data << uint32(areaid); // area id, new 2.1.0
7452 data << uint16(NumberOfFields); // count of uint64 blocks
7453 data << uint32(0x8d8) << uint32(0x0); // 1
7454 data << uint32(0x8d7) << uint32(0x0); // 2
7455 data << uint32(0x8d6) << uint32(0x0); // 3
7456 data << uint32(0x8d5) << uint32(0x0); // 4
7457 data << uint32(0x8d4) << uint32(0x0); // 5
7458 data << uint32(0x8d3) << uint32(0x0); // 6
7459 // 7 1 - Arena season in progress, 0 - end of season
7460 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7461 // 8 Arena season id
7462 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7463 if(mapid == 530) // Outland
7465 data << uint32(0x9bf) << uint32(0x0); // 7
7466 data << uint32(0x9bd) << uint32(0xF); // 8
7467 data << uint32(0x9bb) << uint32(0xF); // 9
7469 switch(zoneid)
7471 case 1:
7472 case 11:
7473 case 12:
7474 case 38:
7475 case 40:
7476 case 51:
7477 case 1519:
7478 case 1537:
7479 case 2257:
7480 break;
7481 case 2597: // AV
7482 data << uint32(0x7ae) << uint32(0x1); // 7
7483 data << uint32(0x532) << uint32(0x1); // 8
7484 data << uint32(0x531) << uint32(0x0); // 9
7485 data << uint32(0x52e) << uint32(0x0); // 10
7486 data << uint32(0x571) << uint32(0x0); // 11
7487 data << uint32(0x570) << uint32(0x0); // 12
7488 data << uint32(0x567) << uint32(0x1); // 13
7489 data << uint32(0x566) << uint32(0x1); // 14
7490 data << uint32(0x550) << uint32(0x1); // 15
7491 data << uint32(0x544) << uint32(0x0); // 16
7492 data << uint32(0x536) << uint32(0x0); // 17
7493 data << uint32(0x535) << uint32(0x1); // 18
7494 data << uint32(0x518) << uint32(0x0); // 19
7495 data << uint32(0x517) << uint32(0x0); // 20
7496 data << uint32(0x574) << uint32(0x0); // 21
7497 data << uint32(0x573) << uint32(0x0); // 22
7498 data << uint32(0x572) << uint32(0x0); // 23
7499 data << uint32(0x56f) << uint32(0x0); // 24
7500 data << uint32(0x56e) << uint32(0x0); // 25
7501 data << uint32(0x56d) << uint32(0x0); // 26
7502 data << uint32(0x56c) << uint32(0x0); // 27
7503 data << uint32(0x56b) << uint32(0x0); // 28
7504 data << uint32(0x56a) << uint32(0x1); // 29
7505 data << uint32(0x569) << uint32(0x1); // 30
7506 data << uint32(0x568) << uint32(0x1); // 13
7507 data << uint32(0x565) << uint32(0x0); // 32
7508 data << uint32(0x564) << uint32(0x0); // 33
7509 data << uint32(0x563) << uint32(0x0); // 34
7510 data << uint32(0x562) << uint32(0x0); // 35
7511 data << uint32(0x561) << uint32(0x0); // 36
7512 data << uint32(0x560) << uint32(0x0); // 37
7513 data << uint32(0x55f) << uint32(0x0); // 38
7514 data << uint32(0x55e) << uint32(0x0); // 39
7515 data << uint32(0x55d) << uint32(0x0); // 40
7516 data << uint32(0x3c6) << uint32(0x4); // 41
7517 data << uint32(0x3c4) << uint32(0x6); // 42
7518 data << uint32(0x3c2) << uint32(0x4); // 43
7519 data << uint32(0x516) << uint32(0x1); // 44
7520 data << uint32(0x515) << uint32(0x0); // 45
7521 data << uint32(0x3b6) << uint32(0x6); // 46
7522 data << uint32(0x55c) << uint32(0x0); // 47
7523 data << uint32(0x55b) << uint32(0x0); // 48
7524 data << uint32(0x55a) << uint32(0x0); // 49
7525 data << uint32(0x559) << uint32(0x0); // 50
7526 data << uint32(0x558) << uint32(0x0); // 51
7527 data << uint32(0x557) << uint32(0x0); // 52
7528 data << uint32(0x556) << uint32(0x0); // 53
7529 data << uint32(0x555) << uint32(0x0); // 54
7530 data << uint32(0x554) << uint32(0x1); // 55
7531 data << uint32(0x553) << uint32(0x1); // 56
7532 data << uint32(0x552) << uint32(0x1); // 57
7533 data << uint32(0x551) << uint32(0x1); // 58
7534 data << uint32(0x54f) << uint32(0x0); // 59
7535 data << uint32(0x54e) << uint32(0x0); // 60
7536 data << uint32(0x54d) << uint32(0x1); // 61
7537 data << uint32(0x54c) << uint32(0x0); // 62
7538 data << uint32(0x54b) << uint32(0x0); // 63
7539 data << uint32(0x545) << uint32(0x0); // 64
7540 data << uint32(0x543) << uint32(0x1); // 65
7541 data << uint32(0x542) << uint32(0x0); // 66
7542 data << uint32(0x540) << uint32(0x0); // 67
7543 data << uint32(0x53f) << uint32(0x0); // 68
7544 data << uint32(0x53e) << uint32(0x0); // 69
7545 data << uint32(0x53d) << uint32(0x0); // 70
7546 data << uint32(0x53c) << uint32(0x0); // 71
7547 data << uint32(0x53b) << uint32(0x0); // 72
7548 data << uint32(0x53a) << uint32(0x1); // 73
7549 data << uint32(0x539) << uint32(0x0); // 74
7550 data << uint32(0x538) << uint32(0x0); // 75
7551 data << uint32(0x537) << uint32(0x0); // 76
7552 data << uint32(0x534) << uint32(0x0); // 77
7553 data << uint32(0x533) << uint32(0x0); // 78
7554 data << uint32(0x530) << uint32(0x0); // 79
7555 data << uint32(0x52f) << uint32(0x0); // 80
7556 data << uint32(0x52d) << uint32(0x1); // 81
7557 break;
7558 case 3277: // WS
7559 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7560 bg->FillInitialWorldStates(data);
7561 else
7563 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7564 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7565 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7566 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7567 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7568 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7569 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7570 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7572 break;
7573 case 3358: // AB
7574 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7575 bg->FillInitialWorldStates(data);
7576 else
7578 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7579 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7580 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7581 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7582 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7583 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7584 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7585 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7586 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7587 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7588 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7589 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7590 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7591 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7592 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7593 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7594 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7595 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7596 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7597 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7598 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7599 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7600 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7601 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7602 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7603 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7604 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7605 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7606 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7607 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7608 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7609 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7611 break;
7612 case 3820: // EY
7613 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7614 bg->FillInitialWorldStates(data);
7615 else
7617 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7618 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7619 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7620 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7621 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7622 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7623 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7624 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7625 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7626 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7627 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7628 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7629 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7630 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7631 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7632 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7633 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7634 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7635 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7636 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7637 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7638 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7639 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7640 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7641 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7642 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7643 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7644 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7645 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7646 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7647 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7648 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7649 // and some more ... unknown
7651 break;
7652 case 3483: // Hellfire Peninsula
7653 data << uint32(0x9ba) << uint32(0x1); // 10
7654 data << uint32(0x9b9) << uint32(0x1); // 11
7655 data << uint32(0x9b5) << uint32(0x0); // 12
7656 data << uint32(0x9b4) << uint32(0x1); // 13
7657 data << uint32(0x9b3) << uint32(0x0); // 14
7658 data << uint32(0x9b2) << uint32(0x0); // 15
7659 data << uint32(0x9b1) << uint32(0x1); // 16
7660 data << uint32(0x9b0) << uint32(0x0); // 17
7661 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7662 data << uint32(0x9ac) << uint32(0x0); // 19
7663 data << uint32(0x9a8) << uint32(0x0); // 20
7664 data << uint32(0x9a7) << uint32(0x0); // 21
7665 data << uint32(0x9a6) << uint32(0x1); // 22
7666 break;
7667 case 3519: // Terokkar Forest
7668 data << uint32(0xa41) << uint32(0x0); // 10
7669 data << uint32(0xa40) << uint32(0x14); // 11
7670 data << uint32(0xa3f) << uint32(0x0); // 12
7671 data << uint32(0xa3e) << uint32(0x0); // 13
7672 data << uint32(0xa3d) << uint32(0x5); // 14
7673 data << uint32(0xa3c) << uint32(0x0); // 15
7674 data << uint32(0xa87) << uint32(0x0); // 16
7675 data << uint32(0xa86) << uint32(0x0); // 17
7676 data << uint32(0xa85) << uint32(0x0); // 18
7677 data << uint32(0xa84) << uint32(0x0); // 19
7678 data << uint32(0xa83) << uint32(0x0); // 20
7679 data << uint32(0xa82) << uint32(0x0); // 21
7680 data << uint32(0xa81) << uint32(0x0); // 22
7681 data << uint32(0xa80) << uint32(0x0); // 23
7682 data << uint32(0xa7e) << uint32(0x0); // 24
7683 data << uint32(0xa7d) << uint32(0x0); // 25
7684 data << uint32(0xa7c) << uint32(0x0); // 26
7685 data << uint32(0xa7b) << uint32(0x0); // 27
7686 data << uint32(0xa7a) << uint32(0x0); // 28
7687 data << uint32(0xa79) << uint32(0x0); // 29
7688 data << uint32(0x9d0) << uint32(0x5); // 30
7689 data << uint32(0x9ce) << uint32(0x0); // 31
7690 data << uint32(0x9cd) << uint32(0x0); // 32
7691 data << uint32(0x9cc) << uint32(0x0); // 33
7692 data << uint32(0xa88) << uint32(0x0); // 34
7693 data << uint32(0xad0) << uint32(0x0); // 35
7694 data << uint32(0xacf) << uint32(0x1); // 36
7695 break;
7696 case 3521: // Zangarmarsh
7697 data << uint32(0x9e1) << uint32(0x0); // 10
7698 data << uint32(0x9e0) << uint32(0x0); // 11
7699 data << uint32(0x9df) << uint32(0x0); // 12
7700 data << uint32(0xa5d) << uint32(0x1); // 13
7701 data << uint32(0xa5c) << uint32(0x0); // 14
7702 data << uint32(0xa5b) << uint32(0x1); // 15
7703 data << uint32(0xa5a) << uint32(0x0); // 16
7704 data << uint32(0xa59) << uint32(0x1); // 17
7705 data << uint32(0xa58) << uint32(0x0); // 18
7706 data << uint32(0xa57) << uint32(0x0); // 19
7707 data << uint32(0xa56) << uint32(0x0); // 20
7708 data << uint32(0xa55) << uint32(0x1); // 21
7709 data << uint32(0xa54) << uint32(0x0); // 22
7710 data << uint32(0x9e7) << uint32(0x0); // 23
7711 data << uint32(0x9e6) << uint32(0x0); // 24
7712 data << uint32(0x9e5) << uint32(0x0); // 25
7713 data << uint32(0xa00) << uint32(0x0); // 26
7714 data << uint32(0x9ff) << uint32(0x1); // 27
7715 data << uint32(0x9fe) << uint32(0x0); // 28
7716 data << uint32(0x9fd) << uint32(0x0); // 29
7717 data << uint32(0x9fc) << uint32(0x1); // 30
7718 data << uint32(0x9fb) << uint32(0x0); // 31
7719 data << uint32(0xa62) << uint32(0x0); // 32
7720 data << uint32(0xa61) << uint32(0x1); // 33
7721 data << uint32(0xa60) << uint32(0x1); // 34
7722 data << uint32(0xa5f) << uint32(0x0); // 35
7723 break;
7724 case 3698: // Nagrand Arena
7725 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7726 bg->FillInitialWorldStates(data);
7727 else
7729 data << uint32(0xa0f) << uint32(0x0); // 7
7730 data << uint32(0xa10) << uint32(0x0); // 8
7731 data << uint32(0xa11) << uint32(0x0); // 9 show
7733 break;
7734 case 3702: // Blade's Edge Arena
7735 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7736 bg->FillInitialWorldStates(data);
7737 else
7739 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7740 data << uint32(0x9f1) << uint32(0x0); // 8 green
7741 data << uint32(0x9f3) << uint32(0x0); // 9 show
7743 break;
7744 case 3968: // Ruins of Lordaeron
7745 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7746 bg->FillInitialWorldStates(data);
7747 else
7749 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7750 data << uint32(0xbb9) << uint32(0x0); // 8 green
7751 data << uint32(0xbba) << uint32(0x0); // 9 show
7753 break;
7754 case 3703: // Shattrath City
7755 break;
7756 default:
7757 data << uint32(0x914) << uint32(0x0); // 7
7758 data << uint32(0x913) << uint32(0x0); // 8
7759 data << uint32(0x912) << uint32(0x0); // 9
7760 data << uint32(0x915) << uint32(0x0); // 10
7761 break;
7763 GetSession()->SendPacket(&data);
7766 uint32 Player::GetXPRestBonus(uint32 xp)
7768 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7770 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7771 rested_bonus = xp;
7773 SetRestBonus( GetRestBonus() - rested_bonus);
7775 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7776 return rested_bonus;
7779 void Player::SetBindPoint(uint64 guid)
7781 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7782 data << uint64(guid);
7783 GetSession()->SendPacket( &data );
7786 void Player::SendTalentWipeConfirm(uint64 guid)
7788 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7789 data << uint64(guid);
7790 data << uint32(resetTalentsCost());
7791 GetSession()->SendPacket( &data );
7794 void Player::SendPetSkillWipeConfirm()
7796 Pet* pet = GetPet();
7797 if(!pet)
7798 return;
7799 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7800 data << pet->GetGUID();
7801 data << uint32(pet->resetTalentsCost());
7802 GetSession()->SendPacket( &data );
7805 /*********************************************************/
7806 /*** STORAGE SYSTEM ***/
7807 /*********************************************************/
7809 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7811 assert(i < 3);
7812 if(i < 2 && item)
7814 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7815 return;
7816 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7817 if(charges == 0)
7818 return;
7819 if(charges > 1)
7820 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7821 else if(charges <= 1)
7823 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7824 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7829 void Player::SetSheath( uint32 sheathed )
7831 switch (sheathed)
7833 case SHEATH_STATE_UNARMED: // no prepared weapon
7834 SetVirtualItemSlot(0,NULL);
7835 SetVirtualItemSlot(1,NULL);
7836 SetVirtualItemSlot(2,NULL);
7837 break;
7838 case SHEATH_STATE_MELEE: // prepared melee weapon
7840 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7841 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7842 SetVirtualItemSlot(2,NULL);
7843 }; break;
7844 case SHEATH_STATE_RANGED: // prepared ranged weapon
7845 SetVirtualItemSlot(0,NULL);
7846 SetVirtualItemSlot(1,NULL);
7847 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7848 break;
7849 default:
7850 SetVirtualItemSlot(0,NULL);
7851 SetVirtualItemSlot(1,NULL);
7852 SetVirtualItemSlot(2,NULL);
7853 break;
7855 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7858 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7860 uint8 pClass = getClass();
7862 uint8 slots[4];
7863 slots[0] = NULL_SLOT;
7864 slots[1] = NULL_SLOT;
7865 slots[2] = NULL_SLOT;
7866 slots[3] = NULL_SLOT;
7867 switch( proto->InventoryType )
7869 case INVTYPE_HEAD:
7870 slots[0] = EQUIPMENT_SLOT_HEAD;
7871 break;
7872 case INVTYPE_NECK:
7873 slots[0] = EQUIPMENT_SLOT_NECK;
7874 break;
7875 case INVTYPE_SHOULDERS:
7876 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7877 break;
7878 case INVTYPE_BODY:
7879 slots[0] = EQUIPMENT_SLOT_BODY;
7880 break;
7881 case INVTYPE_CHEST:
7882 slots[0] = EQUIPMENT_SLOT_CHEST;
7883 break;
7884 case INVTYPE_ROBE:
7885 slots[0] = EQUIPMENT_SLOT_CHEST;
7886 break;
7887 case INVTYPE_WAIST:
7888 slots[0] = EQUIPMENT_SLOT_WAIST;
7889 break;
7890 case INVTYPE_LEGS:
7891 slots[0] = EQUIPMENT_SLOT_LEGS;
7892 break;
7893 case INVTYPE_FEET:
7894 slots[0] = EQUIPMENT_SLOT_FEET;
7895 break;
7896 case INVTYPE_WRISTS:
7897 slots[0] = EQUIPMENT_SLOT_WRISTS;
7898 break;
7899 case INVTYPE_HANDS:
7900 slots[0] = EQUIPMENT_SLOT_HANDS;
7901 break;
7902 case INVTYPE_FINGER:
7903 slots[0] = EQUIPMENT_SLOT_FINGER1;
7904 slots[1] = EQUIPMENT_SLOT_FINGER2;
7905 break;
7906 case INVTYPE_TRINKET:
7907 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7908 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7909 break;
7910 case INVTYPE_CLOAK:
7911 slots[0] = EQUIPMENT_SLOT_BACK;
7912 break;
7913 case INVTYPE_WEAPON:
7915 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7917 // suggest offhand slot only if know dual wielding
7918 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7919 if(CanDualWield())
7920 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7921 break;
7923 case INVTYPE_SHIELD:
7924 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7925 break;
7926 case INVTYPE_RANGED:
7927 slots[0] = EQUIPMENT_SLOT_RANGED;
7928 break;
7929 case INVTYPE_2HWEAPON:
7930 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7931 if (CanDualWield() && CanTitanGrip())
7932 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7933 break;
7934 case INVTYPE_TABARD:
7935 slots[0] = EQUIPMENT_SLOT_TABARD;
7936 break;
7937 case INVTYPE_WEAPONMAINHAND:
7938 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7939 break;
7940 case INVTYPE_WEAPONOFFHAND:
7941 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7942 break;
7943 case INVTYPE_HOLDABLE:
7944 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7945 break;
7946 case INVTYPE_THROWN:
7947 slots[0] = EQUIPMENT_SLOT_RANGED;
7948 break;
7949 case INVTYPE_RANGEDRIGHT:
7950 slots[0] = EQUIPMENT_SLOT_RANGED;
7951 break;
7952 case INVTYPE_BAG:
7953 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7954 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7955 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7956 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7957 break;
7958 case INVTYPE_RELIC:
7960 switch(proto->SubClass)
7962 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7963 if (pClass == CLASS_PALADIN)
7964 slots[0] = EQUIPMENT_SLOT_RANGED;
7965 break;
7966 case ITEM_SUBCLASS_ARMOR_IDOL:
7967 if (pClass == CLASS_DRUID)
7968 slots[0] = EQUIPMENT_SLOT_RANGED;
7969 break;
7970 case ITEM_SUBCLASS_ARMOR_TOTEM:
7971 if (pClass == CLASS_SHAMAN)
7972 slots[0] = EQUIPMENT_SLOT_RANGED;
7973 break;
7974 case ITEM_SUBCLASS_ARMOR_MISC:
7975 if (pClass == CLASS_WARLOCK)
7976 slots[0] = EQUIPMENT_SLOT_RANGED;
7977 break;
7978 case ITEM_SUBCLASS_ARMOR_SIGIL:
7979 if (pClass == CLASS_DEATH_KNIGHT)
7980 slots[0] = EQUIPMENT_SLOT_RANGED;
7981 break;
7983 break;
7985 default :
7986 return NULL_SLOT;
7989 if( slot != NULL_SLOT )
7991 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7993 for (int i = 0; i < 4; ++i)
7995 if ( slots[i] == slot )
7996 return slot;
8000 else
8002 // search free slot at first
8003 for (int i = 0; i < 4; ++i)
8005 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8007 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8008 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8009 return slots[i];
8013 // if not found free and can swap return first appropriate from used
8014 for (int i = 0; i < 4; ++i)
8016 if ( slots[i] != NULL_SLOT && swap )
8017 return slots[i];
8021 // no free position
8022 return NULL_SLOT;
8025 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8027 Item *pItem;
8028 uint32 tempcount = 0;
8030 uint8 res = EQUIP_ERR_OK;
8032 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8034 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8035 if( pItem && pItem->GetEntry() == item )
8037 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8038 if(ires==EQUIP_ERR_OK)
8040 tempcount += pItem->GetCount();
8041 if( tempcount >= count )
8042 return EQUIP_ERR_OK;
8044 else
8045 res = ires;
8048 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8050 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8051 if( pItem && pItem->GetEntry() == item )
8053 tempcount += pItem->GetCount();
8054 if( tempcount >= count )
8055 return EQUIP_ERR_OK;
8058 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8060 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8061 if( pItem && pItem->GetEntry() == item )
8063 tempcount += pItem->GetCount();
8064 if( tempcount >= count )
8065 return EQUIP_ERR_OK;
8068 Bag *pBag;
8069 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8071 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8072 if( pBag )
8074 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8076 pItem = GetItemByPos( i, j );
8077 if( pItem && pItem->GetEntry() == item )
8079 tempcount += pItem->GetCount();
8080 if( tempcount >= count )
8081 return EQUIP_ERR_OK;
8087 // not found req. item count and have unequippable items
8088 return res;
8091 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8093 uint32 count = 0;
8094 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8096 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8097 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8098 count += pItem->GetCount();
8100 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8102 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8103 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8104 count += pItem->GetCount();
8106 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8108 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8109 if( pBag )
8110 count += pBag->GetItemCount(item,skipItem);
8113 if(skipItem && skipItem->GetProto()->GemProperties)
8115 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8117 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8118 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8119 count += pItem->GetGemCountWithID(item);
8123 if(inBankAlso)
8125 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8127 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8128 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8129 count += pItem->GetCount();
8131 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8133 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8134 if( pBag )
8135 count += pBag->GetItemCount(item,skipItem);
8138 if(skipItem && skipItem->GetProto()->GemProperties)
8140 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8142 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8143 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8144 count += pItem->GetGemCountWithID(item);
8149 return count;
8152 Item* Player::GetItemByGuid( uint64 guid ) const
8154 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8156 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8157 if( pItem && pItem->GetGUID() == guid )
8158 return pItem;
8160 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8162 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8163 if( pItem && pItem->GetGUID() == guid )
8164 return pItem;
8167 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8169 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8170 if( pBag )
8172 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8174 Item* pItem = pBag->GetItemByPos( j );
8175 if( pItem && pItem->GetGUID() == guid )
8176 return pItem;
8180 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8182 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8183 if( pBag )
8185 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8187 Item* pItem = pBag->GetItemByPos( j );
8188 if( pItem && pItem->GetGUID() == guid )
8189 return pItem;
8194 return NULL;
8197 Item* Player::GetItemByPos( uint16 pos ) const
8199 uint8 bag = pos >> 8;
8200 uint8 slot = pos & 255;
8201 return GetItemByPos( bag, slot );
8204 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8206 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8207 return m_items[slot];
8208 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8209 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8211 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8212 if ( pBag )
8213 return pBag->GetItemByPos(slot);
8215 return NULL;
8218 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8220 uint16 slot;
8221 switch (attackType)
8223 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8224 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8225 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8226 default: return NULL;
8229 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8230 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8231 return NULL;
8233 if(!useable)
8234 return item;
8236 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8237 return NULL;
8239 return item;
8242 Item* Player::GetShield(bool useable) const
8244 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8245 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8246 return NULL;
8248 if(!useable)
8249 return item;
8251 if( item->IsBroken())
8252 return NULL;
8254 return item;
8257 uint32 Player::GetAttackBySlot( uint8 slot )
8259 switch(slot)
8261 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8262 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8263 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8264 default: return MAX_ATTACK;
8268 bool Player::HasBankBagSlot( uint8 slot ) const
8270 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8271 if( slot < maxslot )
8272 return true;
8273 return false;
8276 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8278 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8279 return true;
8280 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8281 return true;
8282 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8283 return true;
8284 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8285 return true;
8286 return false;
8289 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8291 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8292 return true;
8293 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8294 return true;
8295 return false;
8298 bool Player::IsBankPos( uint8 bag, uint8 slot )
8300 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8301 return true;
8302 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8303 return true;
8304 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8305 return true;
8306 return false;
8309 bool Player::IsBagPos( uint16 pos )
8311 uint8 bag = pos >> 8;
8312 uint8 slot = pos & 255;
8313 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8314 return true;
8315 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8316 return true;
8317 return false;
8320 bool Player::IsValidPos( uint8 bag, uint8 slot )
8322 // post selected
8323 if(bag == NULL_BAG)
8324 return true;
8326 if (bag == INVENTORY_SLOT_BAG_0)
8328 // any post selected
8329 if (slot == NULL_SLOT)
8330 return true;
8332 // equipment
8333 if (slot < EQUIPMENT_SLOT_END)
8334 return true;
8336 // bag equip slots
8337 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8338 return true;
8340 // backpack slots
8341 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8342 return true;
8344 // keyring slots
8345 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8346 return true;
8348 // bank main slots
8349 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8350 return true;
8352 // bank bag slots
8353 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8354 return true;
8356 return false;
8359 // bag content slots
8360 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8362 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8363 if(!pBag)
8364 return false;
8366 // any post selected
8367 if (slot == NULL_SLOT)
8368 return true;
8370 return slot < pBag->GetBagSize();
8373 // bank bag content slots
8374 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8376 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8377 if(!pBag)
8378 return false;
8380 // any post selected
8381 if (slot == NULL_SLOT)
8382 return true;
8384 return slot < pBag->GetBagSize();
8387 // where this?
8388 return false;
8392 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8394 uint32 tempcount = 0;
8395 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8397 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8398 if( pItem && pItem->GetEntry() == item )
8400 tempcount += pItem->GetCount();
8401 if( tempcount >= count )
8402 return true;
8405 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8407 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8408 if( pItem && pItem->GetEntry() == item )
8410 tempcount += pItem->GetCount();
8411 if( tempcount >= count )
8412 return true;
8415 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8417 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8419 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8421 Item* pItem = GetItemByPos( i, j );
8422 if( pItem && pItem->GetEntry() == item )
8424 tempcount += pItem->GetCount();
8425 if( tempcount >= count )
8426 return true;
8432 if(inBankAlso)
8434 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8436 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8437 if( pItem && pItem->GetEntry() == item )
8439 tempcount += pItem->GetCount();
8440 if( tempcount >= count )
8441 return true;
8444 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8446 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8448 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8450 Item* pItem = GetItemByPos( i, j );
8451 if( pItem && pItem->GetEntry() == item )
8453 tempcount += pItem->GetCount();
8454 if( tempcount >= count )
8455 return true;
8462 return false;
8465 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8467 uint32 tempcount = 0;
8468 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8470 if(i==int(except_slot))
8471 continue;
8473 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8474 if( pItem && pItem->GetEntry() == item)
8476 tempcount += pItem->GetCount();
8477 if( tempcount >= count )
8478 return true;
8482 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8483 if (pProto && pProto->GemProperties)
8485 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8487 if(i==int(except_slot))
8488 continue;
8490 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8491 if( pItem && pItem->GetProto()->Socket[0].Color)
8493 tempcount += pItem->GetGemCountWithID(item);
8494 if( tempcount >= count )
8495 return true;
8500 return false;
8503 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8505 uint32 tempcount = 0;
8506 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8508 if(i==int(except_slot))
8509 continue;
8511 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8512 if (!pItem)
8513 continue;
8515 ItemPrototype const *pProto = pItem->GetProto();
8516 if (!pProto)
8517 continue;
8519 if (pProto->ItemLimitCategory == limitCategory)
8521 tempcount += pItem->GetCount();
8522 if( tempcount >= count )
8523 return true;
8526 if( pProto->Socket[0].Color)
8528 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8529 if( tempcount >= count )
8530 return true;
8534 return false;
8537 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8539 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8540 if( !pProto )
8542 if(no_space_count)
8543 *no_space_count = count;
8544 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8547 // no maximum
8548 if(pProto->MaxCount <= 0)
8549 return EQUIP_ERR_OK;
8551 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8553 if (curcount + count > uint32(pProto->MaxCount))
8555 if(no_space_count)
8556 *no_space_count = count +curcount - pProto->MaxCount;
8557 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8560 return EQUIP_ERR_OK;
8563 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8565 Item *pItem;
8566 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8568 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8569 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8570 return true;
8572 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8574 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8575 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8576 return true;
8578 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8580 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8582 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8584 pItem = GetItemByPos( i, j );
8585 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8586 return true;
8590 return false;
8593 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8595 Item* pItem2 = GetItemByPos( bag, slot );
8597 // ignore move item (this slot will be empty at move)
8598 if(pItem2==pSrcItem)
8599 pItem2 = NULL;
8601 uint32 need_space;
8603 // empty specific slot - check item fit to slot
8604 if( !pItem2 || swap )
8606 if( bag == INVENTORY_SLOT_BAG_0 )
8608 // keyring case
8609 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8610 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8612 // vanitypet case (not use, vanity pets stored as spells)
8613 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8614 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8616 // currencytoken case (disabled until proper implement)
8617 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8618 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8620 // guestbag case (not use)
8621 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END)
8622 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8624 // prevent cheating
8625 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8626 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8628 else
8630 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8631 if( !pBag )
8632 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8634 ItemPrototype const* pBagProto = pBag->GetProto();
8635 if( !pBagProto )
8636 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8638 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8639 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8642 // non empty stack with space
8643 need_space = pProto->GetMaxStackSize();
8645 // non empty slot, check item type
8646 else
8648 // check item type
8649 if(pItem2->GetEntry() != pProto->ItemId)
8650 return EQUIP_ERR_ITEM_CANT_STACK;
8652 // check free space
8653 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8654 return EQUIP_ERR_ITEM_CANT_STACK;
8656 // free stack space or infinity
8657 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8660 if(need_space > count)
8661 need_space = count;
8663 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8664 if(!newPosition.isContainedIn(dest))
8666 dest.push_back(newPosition);
8667 count -= need_space;
8669 return EQUIP_ERR_OK;
8672 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
8674 // skip specific bag already processed in first called _CanStoreItem_InBag
8675 if(bag==skip_bag)
8676 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8678 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8679 if( !pBag )
8680 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8682 ItemPrototype const* pBagProto = pBag->GetProto();
8683 if( !pBagProto )
8684 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8686 // specialized bag mode or non-specilized
8687 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8688 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8690 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8691 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8693 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8695 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8696 if(j==skip_slot)
8697 continue;
8699 Item* pItem2 = GetItemByPos( bag, j );
8701 // ignore move item (this slot will be empty at move)
8702 if(pItem2==pSrcItem)
8703 pItem2 = NULL;
8705 // if merge skip empty, if !merge skip non-empty
8706 if((pItem2!=NULL)!=merge)
8707 continue;
8709 if( pItem2 )
8711 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8713 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8714 if(need_space > count)
8715 need_space = count;
8717 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8718 if(!newPosition.isContainedIn(dest))
8720 dest.push_back(newPosition);
8721 count -= need_space;
8723 if(count==0)
8724 return EQUIP_ERR_OK;
8728 else
8730 uint32 need_space = pProto->GetMaxStackSize();
8731 if(need_space > count)
8732 need_space = count;
8734 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8735 if(!newPosition.isContainedIn(dest))
8737 dest.push_back(newPosition);
8738 count -= need_space;
8740 if(count==0)
8741 return EQUIP_ERR_OK;
8745 return EQUIP_ERR_OK;
8748 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
8750 for(uint32 j = slot_begin; j < slot_end; ++j)
8752 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8753 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8754 continue;
8756 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8758 // ignore move item (this slot will be empty at move)
8759 if(pItem2==pSrcItem)
8760 pItem2 = NULL;
8762 // if merge skip empty, if !merge skip non-empty
8763 if((pItem2!=NULL)!=merge)
8764 continue;
8766 if( pItem2 )
8768 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8770 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8771 if(need_space > count)
8772 need_space = count;
8773 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8774 if(!newPosition.isContainedIn(dest))
8776 dest.push_back(newPosition);
8777 count -= need_space;
8779 if(count==0)
8780 return EQUIP_ERR_OK;
8784 else
8786 uint32 need_space = pProto->GetMaxStackSize();
8787 if(need_space > count)
8788 need_space = count;
8790 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8791 if(!newPosition.isContainedIn(dest))
8793 dest.push_back(newPosition);
8794 count -= need_space;
8796 if(count==0)
8797 return EQUIP_ERR_OK;
8801 return EQUIP_ERR_OK;
8804 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8806 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8808 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8809 if( !pProto )
8811 if(no_space_count)
8812 *no_space_count = count;
8813 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8816 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8818 if(no_space_count)
8819 *no_space_count = count;
8820 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8823 // check count of items (skip for auto move for same player from bank)
8824 uint32 no_similar_count = 0; // can't store this amount similar items
8825 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8826 if(res!=EQUIP_ERR_OK)
8828 if(count==no_similar_count)
8830 if(no_space_count)
8831 *no_space_count = no_similar_count;
8832 return res;
8834 count -= no_similar_count;
8837 // in specific slot
8838 if( bag != NULL_BAG && slot != NULL_SLOT )
8840 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8841 if(res!=EQUIP_ERR_OK)
8843 if(no_space_count)
8844 *no_space_count = count + no_similar_count;
8845 return res;
8848 if(count==0)
8850 if(no_similar_count==0)
8851 return EQUIP_ERR_OK;
8853 if(no_space_count)
8854 *no_space_count = count + no_similar_count;
8855 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8859 // not specific slot or have space for partly store only in specific slot
8861 // in specific bag
8862 if( bag != NULL_BAG )
8864 // search stack in bag for merge to
8865 if( pProto->Stackable != 1 )
8867 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8869 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8870 if(res!=EQUIP_ERR_OK)
8872 if(no_space_count)
8873 *no_space_count = count + no_similar_count;
8874 return res;
8877 if(count==0)
8879 if(no_similar_count==0)
8880 return EQUIP_ERR_OK;
8882 if(no_space_count)
8883 *no_space_count = count + no_similar_count;
8884 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8887 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8888 if(res!=EQUIP_ERR_OK)
8890 if(no_space_count)
8891 *no_space_count = count + no_similar_count;
8892 return res;
8895 if(count==0)
8897 if(no_similar_count==0)
8898 return EQUIP_ERR_OK;
8900 if(no_space_count)
8901 *no_space_count = count + no_similar_count;
8902 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8905 else // equipped bag
8907 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8908 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8909 if(res!=EQUIP_ERR_OK)
8910 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8912 if(res!=EQUIP_ERR_OK)
8914 if(no_space_count)
8915 *no_space_count = count + no_similar_count;
8916 return res;
8919 if(count==0)
8921 if(no_similar_count==0)
8922 return EQUIP_ERR_OK;
8924 if(no_space_count)
8925 *no_space_count = count + no_similar_count;
8926 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8931 // search free slot in bag for place to
8932 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8934 // search free slot - keyring case
8935 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8937 uint32 keyringSize = GetMaxKeyringSize();
8938 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8939 if(res!=EQUIP_ERR_OK)
8941 if(no_space_count)
8942 *no_space_count = count + no_similar_count;
8943 return res;
8946 if(count==0)
8948 if(no_similar_count==0)
8949 return EQUIP_ERR_OK;
8951 if(no_space_count)
8952 *no_space_count = count + no_similar_count;
8953 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8956 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8957 if(res!=EQUIP_ERR_OK)
8959 if(no_space_count)
8960 *no_space_count = count + no_similar_count;
8961 return res;
8964 if(count==0)
8966 if(no_similar_count==0)
8967 return EQUIP_ERR_OK;
8969 if(no_space_count)
8970 *no_space_count = count + no_similar_count;
8971 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8974 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8976 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8977 if(res!=EQUIP_ERR_OK)
8979 if(no_space_count)
8980 *no_space_count = count + no_similar_count;
8981 return res;
8984 if(count==0)
8986 if(no_similar_count==0)
8987 return EQUIP_ERR_OK;
8989 if(no_space_count)
8990 *no_space_count = count + no_similar_count;
8991 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8995 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8996 if(res!=EQUIP_ERR_OK)
8998 if(no_space_count)
8999 *no_space_count = count + no_similar_count;
9000 return res;
9003 if(count==0)
9005 if(no_similar_count==0)
9006 return EQUIP_ERR_OK;
9008 if(no_space_count)
9009 *no_space_count = count + no_similar_count;
9010 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9013 else // equipped bag
9015 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9016 if(res!=EQUIP_ERR_OK)
9017 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9019 if(res!=EQUIP_ERR_OK)
9021 if(no_space_count)
9022 *no_space_count = count + no_similar_count;
9023 return res;
9026 if(count==0)
9028 if(no_similar_count==0)
9029 return EQUIP_ERR_OK;
9031 if(no_space_count)
9032 *no_space_count = count + no_similar_count;
9033 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9038 // not specific bag or have space for partly store only in specific bag
9040 // search stack for merge to
9041 if( pProto->Stackable != 1 )
9043 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9044 if(res!=EQUIP_ERR_OK)
9046 if(no_space_count)
9047 *no_space_count = count + no_similar_count;
9048 return res;
9051 if(count==0)
9053 if(no_similar_count==0)
9054 return EQUIP_ERR_OK;
9056 if(no_space_count)
9057 *no_space_count = count + no_similar_count;
9058 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9061 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9062 if(res!=EQUIP_ERR_OK)
9064 if(no_space_count)
9065 *no_space_count = count + no_similar_count;
9066 return res;
9069 if(count==0)
9071 if(no_similar_count==0)
9072 return EQUIP_ERR_OK;
9074 if(no_space_count)
9075 *no_space_count = count + no_similar_count;
9076 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9079 if( pProto->BagFamily )
9081 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9083 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9084 if(res!=EQUIP_ERR_OK)
9085 continue;
9087 if(count==0)
9089 if(no_similar_count==0)
9090 return EQUIP_ERR_OK;
9092 if(no_space_count)
9093 *no_space_count = count + no_similar_count;
9094 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9099 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9101 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9102 if(res!=EQUIP_ERR_OK)
9103 continue;
9105 if(count==0)
9107 if(no_similar_count==0)
9108 return EQUIP_ERR_OK;
9110 if(no_space_count)
9111 *no_space_count = count + no_similar_count;
9112 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9117 // search free slot - special bag case
9118 if( pProto->BagFamily )
9120 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9122 uint32 keyringSize = GetMaxKeyringSize();
9123 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9124 if(res!=EQUIP_ERR_OK)
9126 if(no_space_count)
9127 *no_space_count = count + no_similar_count;
9128 return res;
9131 if(count==0)
9133 if(no_similar_count==0)
9134 return EQUIP_ERR_OK;
9136 if(no_space_count)
9137 *no_space_count = count + no_similar_count;
9138 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9141 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9143 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9144 if(res!=EQUIP_ERR_OK)
9146 if(no_space_count)
9147 *no_space_count = count + no_similar_count;
9148 return res;
9151 if(count==0)
9153 if(no_similar_count==0)
9154 return EQUIP_ERR_OK;
9156 if(no_space_count)
9157 *no_space_count = count + no_similar_count;
9158 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9162 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9164 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9165 if(res!=EQUIP_ERR_OK)
9166 continue;
9168 if(count==0)
9170 if(no_similar_count==0)
9171 return EQUIP_ERR_OK;
9173 if(no_space_count)
9174 *no_space_count = count + no_similar_count;
9175 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9180 // search free slot
9181 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9182 if(res!=EQUIP_ERR_OK)
9184 if(no_space_count)
9185 *no_space_count = count + no_similar_count;
9186 return res;
9189 if(count==0)
9191 if(no_similar_count==0)
9192 return EQUIP_ERR_OK;
9194 if(no_space_count)
9195 *no_space_count = count + no_similar_count;
9196 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9199 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9201 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9202 if(res!=EQUIP_ERR_OK)
9203 continue;
9205 if(count==0)
9207 if(no_similar_count==0)
9208 return EQUIP_ERR_OK;
9210 if(no_space_count)
9211 *no_space_count = count + no_similar_count;
9212 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9216 if(no_space_count)
9217 *no_space_count = count + no_similar_count;
9219 return EQUIP_ERR_INVENTORY_FULL;
9222 //////////////////////////////////////////////////////////////////////////
9223 uint8 Player::CanStoreItems( Item **pItems,int count) const
9225 Item *pItem2;
9227 // fill space table
9228 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9229 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9230 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9231 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9233 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9234 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9235 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9236 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9238 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9240 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9242 if (pItem2 && !pItem2->IsInTrade())
9244 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9248 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9250 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9252 if (pItem2 && !pItem2->IsInTrade())
9254 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9258 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9260 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9262 if (pItem2 && !pItem2->IsInTrade())
9264 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9268 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9270 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9272 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9274 pItem2 = GetItemByPos( i, j );
9275 if (pItem2 && !pItem2->IsInTrade())
9277 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9283 // check free space for all items
9284 for (int k=0;k<count;k++)
9286 Item *pItem = pItems[k];
9288 // no item
9289 if (!pItem) continue;
9291 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9292 ItemPrototype const *pProto = pItem->GetProto();
9294 // strange item
9295 if( !pProto )
9296 return EQUIP_ERR_ITEM_NOT_FOUND;
9298 // item it 'bind'
9299 if(pItem->IsBindedNotWith(GetGUID()))
9300 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9302 Bag *pBag;
9303 ItemPrototype const *pBagProto;
9305 // item is 'one item only'
9306 uint8 res = CanTakeMoreSimilarItems(pItem);
9307 if(res != EQUIP_ERR_OK)
9308 return res;
9310 // search stack for merge to
9311 if( pProto->Stackable != 1 )
9313 bool b_found = false;
9315 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9317 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9318 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9320 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9321 b_found = true;
9322 break;
9325 if (b_found) continue;
9327 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9329 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9330 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9332 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9333 b_found = true;
9334 break;
9337 if (b_found) continue;
9339 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9341 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9342 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9344 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9345 b_found = true;
9346 break;
9349 if (b_found) continue;
9351 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9353 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9354 if( pBag )
9356 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9358 pItem2 = GetItemByPos( t, j );
9359 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9361 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9362 b_found = true;
9363 break;
9368 if (b_found) continue;
9371 // special bag case
9372 if( pProto->BagFamily )
9374 bool b_found = false;
9375 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9377 uint32 keyringSize = GetMaxKeyringSize();
9378 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9380 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9382 inv_keys[t-KEYRING_SLOT_START] = 1;
9383 b_found = true;
9384 break;
9389 if (b_found) continue;
9391 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9393 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9395 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9397 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9398 b_found = true;
9399 break;
9404 if (b_found) continue;
9406 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9408 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9409 if( pBag )
9411 pBagProto = pBag->GetProto();
9413 // not plain container check
9414 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9415 ItemCanGoIntoBag(pProto,pBagProto) )
9417 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9419 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9421 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9422 b_found = true;
9423 break;
9429 if (b_found) continue;
9432 // search free slot
9433 bool b_found = false;
9434 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9436 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9438 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9439 b_found = true;
9440 break;
9443 if (b_found) continue;
9445 // search free slot in bags
9446 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9448 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9449 if( pBag )
9451 pBagProto = pBag->GetProto();
9453 // special bag already checked
9454 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9455 continue;
9457 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9459 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9461 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9462 b_found = true;
9463 break;
9469 // no free slot found?
9470 if (!b_found)
9471 return EQUIP_ERR_INVENTORY_FULL;
9474 return EQUIP_ERR_OK;
9477 //////////////////////////////////////////////////////////////////////////
9478 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9480 dest = 0;
9481 Item *pItem = Item::CreateItem( item, 1, this );
9482 if( pItem )
9484 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9485 delete pItem;
9486 return result;
9489 return EQUIP_ERR_ITEM_NOT_FOUND;
9492 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9494 dest = 0;
9495 if( pItem )
9497 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9498 ItemPrototype const *pProto = pItem->GetProto();
9499 if( pProto )
9501 if(pItem->IsBindedNotWith(GetGUID()))
9502 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9504 // check count of items (skip for auto move for same player from bank)
9505 uint8 res = CanTakeMoreSimilarItems(pItem);
9506 if(res != EQUIP_ERR_OK)
9507 return res;
9509 // check this only in game
9510 if(not_loading)
9512 // May be here should be more stronger checks; STUNNED checked
9513 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9514 if (hasUnitState(UNIT_STAT_STUNNED))
9515 return EQUIP_ERR_YOU_ARE_STUNNED;
9517 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9518 // - combat
9519 // - in-progress arenas
9520 if( !pProto->CanChangeEquipStateInCombat() )
9522 if( isInCombat() )
9523 return EQUIP_ERR_NOT_IN_COMBAT;
9525 if(BattleGround* bg = GetBattleGround())
9526 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9527 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9530 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9531 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9533 if(IsNonMeleeSpellCasted(false))
9534 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9537 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9538 if( eslot == NULL_SLOT )
9539 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9541 uint8 msg = CanUseItem( pItem , not_loading );
9542 if( msg != EQUIP_ERR_OK )
9543 return msg;
9544 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9545 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9547 // if swap ignore item (equipped also)
9548 if(uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9549 return res2;
9551 // check unique-equipped special item classes
9552 if (pProto->Class == ITEM_CLASS_QUIVER)
9554 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9556 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9558 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9560 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9562 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9563 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9564 else
9565 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9572 uint32 type = pProto->InventoryType;
9574 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9576 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9578 if(!CanDualWield())
9579 return EQUIP_ERR_CANT_DUAL_WIELD;
9581 else if (type == INVTYPE_2HWEAPON)
9583 if(!CanDualWield() || !CanTitanGrip())
9584 return EQUIP_ERR_CANT_DUAL_WIELD;
9587 if(IsTwoHandUsed())
9588 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9591 // equip two-hand weapon case (with possible unequip 2 items)
9592 if( type == INVTYPE_2HWEAPON )
9594 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9596 if (!CanTitanGrip())
9597 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9599 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9600 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9602 if (!CanTitanGrip())
9604 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9605 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9606 ItemPosCountVec off_dest;
9607 if( offItem && (!not_loading ||
9608 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9609 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9610 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9613 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9614 return EQUIP_ERR_OK;
9617 if( !swap )
9618 return EQUIP_ERR_ITEM_NOT_FOUND;
9619 else
9620 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9623 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9625 // Applied only to equipped items and bank bags
9626 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9627 return EQUIP_ERR_OK;
9629 Item* pItem = GetItemByPos(pos);
9631 // Applied only to existed equipped item
9632 if( !pItem )
9633 return EQUIP_ERR_OK;
9635 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9637 ItemPrototype const *pProto = pItem->GetProto();
9638 if( !pProto )
9639 return EQUIP_ERR_ITEM_NOT_FOUND;
9641 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9642 // - combat
9643 // - in-progress arenas
9644 if( !pProto->CanChangeEquipStateInCombat() )
9646 if( isInCombat() )
9647 return EQUIP_ERR_NOT_IN_COMBAT;
9649 if(BattleGround* bg = GetBattleGround())
9650 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9651 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9654 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9655 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9657 return EQUIP_ERR_OK;
9660 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9662 if( !pItem )
9663 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9665 uint32 count = pItem->GetCount();
9667 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9668 ItemPrototype const *pProto = pItem->GetProto();
9669 if( !pProto )
9670 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9672 if( pItem->IsBindedNotWith(GetGUID()) )
9673 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9675 // check count of items (skip for auto move for same player from bank)
9676 uint8 res = CanTakeMoreSimilarItems(pItem);
9677 if(res != EQUIP_ERR_OK)
9678 return res;
9680 // in specific slot
9681 if( bag != NULL_BAG && slot != NULL_SLOT )
9683 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9685 if (!pItem->IsBag())
9686 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9688 if( !HasBankBagSlot( slot ) )
9689 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9691 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9692 return cantuse;
9695 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9696 if(res!=EQUIP_ERR_OK)
9697 return res;
9699 if(count==0)
9700 return EQUIP_ERR_OK;
9703 // not specific slot or have space for partly store only in specific slot
9705 // in specific bag
9706 if( bag != NULL_BAG )
9708 if( pProto->InventoryType == INVTYPE_BAG )
9710 Bag *pBag = (Bag*)pItem;
9711 if( pBag && !pBag->IsEmpty() )
9712 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9715 // search stack in bag for merge to
9716 if( pProto->Stackable != 1 )
9718 if( bag == INVENTORY_SLOT_BAG_0 )
9720 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9721 if(res!=EQUIP_ERR_OK)
9722 return res;
9724 if(count==0)
9725 return EQUIP_ERR_OK;
9727 else
9729 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9730 if(res!=EQUIP_ERR_OK)
9731 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9733 if(res!=EQUIP_ERR_OK)
9734 return res;
9736 if(count==0)
9737 return EQUIP_ERR_OK;
9741 // search free slot in bag
9742 if( bag == INVENTORY_SLOT_BAG_0 )
9744 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9745 if(res!=EQUIP_ERR_OK)
9746 return res;
9748 if(count==0)
9749 return EQUIP_ERR_OK;
9751 else
9753 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9754 if(res!=EQUIP_ERR_OK)
9755 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9757 if(res!=EQUIP_ERR_OK)
9758 return res;
9760 if(count==0)
9761 return EQUIP_ERR_OK;
9765 // not specific bag or have space for partly store only in specific bag
9767 // search stack for merge to
9768 if( pProto->Stackable != 1 )
9770 // in slots
9771 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9772 if(res!=EQUIP_ERR_OK)
9773 return res;
9775 if(count==0)
9776 return EQUIP_ERR_OK;
9778 // in special bags
9779 if( pProto->BagFamily )
9781 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9783 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9784 if(res!=EQUIP_ERR_OK)
9785 continue;
9787 if(count==0)
9788 return EQUIP_ERR_OK;
9792 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9794 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9795 if(res!=EQUIP_ERR_OK)
9796 continue;
9798 if(count==0)
9799 return EQUIP_ERR_OK;
9803 // search free place in special bag
9804 if( pProto->BagFamily )
9806 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9808 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9809 if(res!=EQUIP_ERR_OK)
9810 continue;
9812 if(count==0)
9813 return EQUIP_ERR_OK;
9817 // search free space
9818 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9819 if(res!=EQUIP_ERR_OK)
9820 return res;
9822 if(count==0)
9823 return EQUIP_ERR_OK;
9825 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9827 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9828 if(res!=EQUIP_ERR_OK)
9829 continue;
9831 if(count==0)
9832 return EQUIP_ERR_OK;
9834 return EQUIP_ERR_BANK_FULL;
9837 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9839 if( pItem )
9841 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9842 if( !isAlive() && not_loading )
9843 return EQUIP_ERR_YOU_ARE_DEAD;
9844 //if( isStunned() )
9845 // return EQUIP_ERR_YOU_ARE_STUNNED;
9846 ItemPrototype const *pProto = pItem->GetProto();
9847 if( pProto )
9849 if( pItem->IsBindedNotWith(GetGUID()) )
9850 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9851 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9852 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9853 if( pItem->GetSkill() != 0 )
9855 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9856 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9858 if( pProto->RequiredSkill != 0 )
9860 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9861 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9862 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9863 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9865 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9866 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9867 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9868 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9869 if( getLevel() < pProto->RequiredLevel )
9870 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9871 return EQUIP_ERR_OK;
9874 return EQUIP_ERR_ITEM_NOT_FOUND;
9877 bool Player::CanUseItem( ItemPrototype const *pProto )
9879 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9881 if( pProto )
9883 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9884 return false;
9885 if( pProto->RequiredSkill != 0 )
9887 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9888 return false;
9889 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9890 return false;
9892 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9893 return false;
9894 if( getLevel() < pProto->RequiredLevel )
9895 return false;
9896 return true;
9898 return false;
9901 uint8 Player::CanUseAmmo( uint32 item ) const
9903 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9904 if( !isAlive() )
9905 return EQUIP_ERR_YOU_ARE_DEAD;
9906 //if( isStunned() )
9907 // return EQUIP_ERR_YOU_ARE_STUNNED;
9908 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9909 if( pProto )
9911 if( pProto->InventoryType!= INVTYPE_AMMO )
9912 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9913 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9914 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9915 if( pProto->RequiredSkill != 0 )
9917 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9918 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9919 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9920 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9922 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9923 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9924 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9925 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9927 if( getLevel() < pProto->RequiredLevel )
9928 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9930 // Requires No Ammo
9931 if(GetDummyAura(46699))
9932 return EQUIP_ERR_BAG_FULL6;
9934 return EQUIP_ERR_OK;
9936 return EQUIP_ERR_ITEM_NOT_FOUND;
9939 void Player::SetAmmo( uint32 item )
9941 if(!item)
9942 return;
9944 // already set
9945 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9946 return;
9948 // check ammo
9949 if(item)
9951 uint8 msg = CanUseAmmo( item );
9952 if( msg != EQUIP_ERR_OK )
9954 SendEquipError( msg, NULL, NULL );
9955 return;
9959 SetUInt32Value(PLAYER_AMMO_ID, item);
9961 _ApplyAmmoBonuses();
9964 void Player::RemoveAmmo()
9966 SetUInt32Value(PLAYER_AMMO_ID, 0);
9968 m_ammoDPS = 0.0f;
9970 if(CanModifyStats())
9971 UpdateDamagePhysical(RANGED_ATTACK);
9974 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9975 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9977 uint32 count = 0;
9978 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9979 count += itr->count;
9981 Item *pItem = Item::CreateItem( item, count, this );
9982 if( pItem )
9984 ItemAddedQuestCheck( item, count );
9985 if(randomPropertyId)
9986 pItem->SetItemRandomProperties(randomPropertyId);
9987 pItem = StoreItem( dest, pItem, update );
9989 return pItem;
9992 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9994 if( !pItem )
9995 return NULL;
9997 Item* lastItem = pItem;
9998 uint32 entry = pItem->GetEntry();
9999 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10001 uint16 pos = itr->pos;
10002 uint32 count = itr->count;
10004 ++itr;
10006 if(itr == dest.end())
10008 lastItem = _StoreItem(pos,pItem,count,false,update);
10009 break;
10012 lastItem = _StoreItem(pos,pItem,count,true,update);
10014 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10015 return lastItem;
10018 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10019 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10021 if( !pItem )
10022 return NULL;
10024 uint8 bag = pos >> 8;
10025 uint8 slot = pos & 255;
10027 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10029 Item *pItem2 = GetItemByPos( bag, slot );
10031 if (!pItem2)
10033 if (clone)
10034 pItem = pItem->CloneItem(count,this);
10035 else
10036 pItem->SetCount(count);
10038 if (!pItem)
10039 return NULL;
10041 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10042 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10043 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10044 pItem->SetBinding( true );
10046 if (bag == INVENTORY_SLOT_BAG_0)
10048 m_items[slot] = pItem;
10049 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10050 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10051 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10053 pItem->SetSlot( slot );
10054 pItem->SetContainer( NULL );
10056 // need update known currency
10057 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10058 UpdateKnownCurrencies(pItem->GetEntry(),true);
10060 if (IsInWorld() && update)
10062 pItem->AddToWorld();
10063 pItem->SendUpdateToPlayer( this );
10066 pItem->SetState(ITEM_CHANGED, this);
10068 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10070 pBag->StoreItem( slot, pItem, update );
10071 if( IsInWorld() && update )
10073 pItem->AddToWorld();
10074 pItem->SendUpdateToPlayer( this );
10076 pItem->SetState(ITEM_CHANGED, this);
10077 pBag->SetState(ITEM_CHANGED, this);
10080 AddEnchantmentDurations(pItem);
10081 AddItemDurations(pItem);
10083 return pItem;
10085 else
10087 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10088 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10089 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10090 pItem2->SetBinding( true );
10092 pItem2->SetCount( pItem2->GetCount() + count );
10093 if (IsInWorld() && update)
10094 pItem2->SendUpdateToPlayer( this );
10096 if (!clone)
10098 // delete item (it not in any slot currently)
10099 if (IsInWorld() && update)
10101 pItem->RemoveFromWorld();
10102 pItem->DestroyForPlayer( this );
10105 RemoveEnchantmentDurations(pItem);
10106 RemoveItemDurations(pItem);
10108 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10109 pItem->SetState(ITEM_REMOVED, this);
10112 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10113 AddEnchantmentDurations(pItem2);
10115 pItem2->SetState(ITEM_CHANGED, this);
10117 return pItem2;
10121 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10123 if (Item *pItem = Item::CreateItem( item, 1, this ))
10125 ItemAddedQuestCheck( item, 1 );
10126 return EquipItem( pos, pItem, update );
10129 return NULL;
10132 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10135 AddEnchantmentDurations(pItem);
10136 AddItemDurations(pItem);
10138 uint8 bag = pos >> 8;
10139 uint8 slot = pos & 255;
10141 Item *pItem2 = GetItemByPos( bag, slot );
10143 if( !pItem2 )
10145 VisualizeItem( slot, pItem);
10147 if(isAlive())
10149 ItemPrototype const *pProto = pItem->GetProto();
10151 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10152 if(pProto && pProto->ItemSet)
10153 AddItemsSetItem(this,pItem);
10155 _ApplyItemMods(pItem, slot, true);
10157 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10159 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10161 if (getClass() == CLASS_ROGUE)
10162 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10164 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10166 if (!spellProto)
10167 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10168 else
10170 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10172 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10173 data << uint64(GetGUID());
10174 data << uint8(1);
10175 data << uint32(cooldownSpell);
10176 data << uint32(0);
10177 GetSession()->SendPacket(&data);
10182 if( IsInWorld() && update )
10184 pItem->AddToWorld();
10185 pItem->SendUpdateToPlayer( this );
10188 ApplyEquipCooldown(pItem);
10190 if( slot == EQUIPMENT_SLOT_MAINHAND )
10191 UpdateExpertise(BASE_ATTACK);
10192 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10193 UpdateExpertise(OFF_ATTACK);
10195 else
10197 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10198 if( IsInWorld() && update )
10199 pItem2->SendUpdateToPlayer( this );
10201 // delete item (it not in any slot currently)
10202 //pItem->DeleteFromDB();
10203 if( IsInWorld() && update )
10205 pItem->RemoveFromWorld();
10206 pItem->DestroyForPlayer( this );
10209 RemoveEnchantmentDurations(pItem);
10210 RemoveItemDurations(pItem);
10212 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10213 pItem->SetState(ITEM_REMOVED, this);
10214 pItem2->SetState(ITEM_CHANGED, this);
10216 ApplyEquipCooldown(pItem2);
10218 return pItem2;
10221 // only for full equip instead adding to stack
10222 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10224 return pItem;
10227 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10229 if( pItem )
10231 AddEnchantmentDurations(pItem);
10232 AddItemDurations(pItem);
10234 uint8 slot = pos & 255;
10235 VisualizeItem( slot, pItem);
10237 if( IsInWorld() )
10239 pItem->AddToWorld();
10240 pItem->SendUpdateToPlayer( this );
10245 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10247 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10248 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10249 // entry // Size: 1
10250 // inspected enchantments // Size: 6
10251 // ? // Size: 5
10252 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10253 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10254 // // = 16
10256 if(pItem)
10258 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10260 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10261 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10263 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10264 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10266 // Use SetInt16Value to prevent set high part to FFFF for negative value
10267 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10268 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10270 else
10272 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10274 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10275 SetUInt32Value(VisibleBase + 0, 0);
10277 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10278 SetUInt32Value(VisibleBase + 1 + i, 0);
10280 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10281 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10285 void Player::VisualizeItem( uint8 slot, Item *pItem)
10287 if(!pItem)
10288 return;
10290 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10291 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10292 pItem->SetBinding( true );
10294 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10296 m_items[slot] = pItem;
10297 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10298 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10299 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10300 pItem->SetSlot( slot );
10301 pItem->SetContainer( NULL );
10303 if( slot < EQUIPMENT_SLOT_END )
10304 SetVisibleItemSlot(slot,pItem);
10306 pItem->SetState(ITEM_CHANGED, this);
10309 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10311 // note: removeitem does not actually change the item
10312 // it only takes the item out of storage temporarily
10313 // note2: if removeitem is to be used for delinking
10314 // the item must be removed from the player's updatequeue
10316 Item *pItem = GetItemByPos( bag, slot );
10317 if( pItem )
10319 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10321 RemoveEnchantmentDurations(pItem);
10322 RemoveItemDurations(pItem);
10324 if( bag == INVENTORY_SLOT_BAG_0 )
10326 if ( slot < INVENTORY_SLOT_BAG_END )
10328 ItemPrototype const *pProto = pItem->GetProto();
10329 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10331 if(pProto && pProto->ItemSet)
10332 RemoveItemsSetItem(this,pProto);
10334 _ApplyItemMods(pItem, slot, false);
10336 // remove item dependent auras and casts (only weapon and armor slots)
10337 if(slot < EQUIPMENT_SLOT_END)
10339 RemoveItemDependentAurasAndCasts(pItem);
10341 // remove held enchantments, update expertise
10342 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10344 if (pItem->GetItemSuffixFactor())
10346 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10347 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10349 else
10351 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10352 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10355 UpdateExpertise(BASE_ATTACK);
10357 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10358 UpdateExpertise(OFF_ATTACK);
10361 // need update known currency
10362 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10363 UpdateKnownCurrencies(pItem->GetEntry(),false);
10365 m_items[slot] = NULL;
10366 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10368 if ( slot < EQUIPMENT_SLOT_END )
10369 SetVisibleItemSlot(slot,NULL);
10371 else
10373 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10374 if( pBag )
10375 pBag->RemoveItem(slot, update);
10377 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10378 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10379 pItem->SetSlot( NULL_SLOT );
10380 if( IsInWorld() && update )
10381 pItem->SendUpdateToPlayer( this );
10385 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10386 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10388 if(Item* it = GetItemByPos(bag,slot))
10390 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10391 RemoveItem( bag,slot,update);
10392 it->RemoveFromUpdateQueueOf(this);
10393 if(it->IsInWorld())
10395 it->RemoveFromWorld();
10396 it->DestroyForPlayer( this );
10401 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10402 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10404 // update quest counters
10405 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10407 // store item
10408 Item* pLastItem = StoreItem( dest, pItem, update);
10410 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10411 if(pLastItem==pItem)
10413 // update owner for last item (this can be original item with wrong owner
10414 if(pLastItem->GetOwnerGUID() != GetGUID())
10415 pLastItem->SetOwnerGUID(GetGUID());
10417 // if this original item then it need create record in inventory
10418 // in case trade we already have item in other player inventory
10419 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10423 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10425 Item *pItem = GetItemByPos( bag, slot );
10426 if( pItem )
10428 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10430 // start from destroy contained items (only equipped bag can have its)
10431 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10433 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10434 DestroyItem(slot,i,update);
10437 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10438 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10440 RemoveEnchantmentDurations(pItem);
10441 RemoveItemDurations(pItem);
10443 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10445 if( bag == INVENTORY_SLOT_BAG_0 )
10447 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10449 // equipment and equipped bags can have applied bonuses
10450 if ( slot < INVENTORY_SLOT_BAG_END )
10452 ItemPrototype const *pProto = pItem->GetProto();
10454 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10455 if(pProto && pProto->ItemSet)
10456 RemoveItemsSetItem(this,pProto);
10458 _ApplyItemMods(pItem, slot, false);
10461 if ( slot < EQUIPMENT_SLOT_END )
10463 // remove item dependent auras and casts (only weapon and armor slots)
10464 RemoveItemDependentAurasAndCasts(pItem);
10466 // update expertise
10467 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10468 UpdateExpertise(BASE_ATTACK);
10469 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10470 UpdateExpertise(OFF_ATTACK);
10472 // equipment visual show
10473 SetVisibleItemSlot(slot,NULL);
10475 // need update known currency
10476 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10477 UpdateKnownCurrencies(pItem->GetEntry(),false);
10479 m_items[slot] = NULL;
10481 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10482 pBag->RemoveItem(slot, update);
10484 if( IsInWorld() && update )
10486 pItem->RemoveFromWorld();
10487 pItem->DestroyForPlayer(this);
10490 //pItem->SetOwnerGUID(0);
10491 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10492 pItem->SetSlot( NULL_SLOT );
10493 pItem->SetState(ITEM_REMOVED, this);
10497 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10499 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10500 uint32 remcount = 0;
10502 // in inventory
10503 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10505 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10507 if (pItem->GetEntry() == item)
10509 if (pItem->GetCount() + remcount <= count)
10511 // all items in inventory can unequipped
10512 remcount += pItem->GetCount();
10513 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10515 if (remcount >=count)
10516 return;
10518 else
10520 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10521 pItem->SetCount( pItem->GetCount() - count + remcount );
10522 if (IsInWorld() & update)
10523 pItem->SendUpdateToPlayer( this );
10524 pItem->SetState(ITEM_CHANGED, this);
10525 return;
10531 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10533 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10535 if (pItem->GetEntry() == item)
10537 if (pItem->GetCount() + remcount <= count)
10539 // all keys can be unequipped
10540 remcount += pItem->GetCount();
10541 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10543 if (remcount >=count)
10544 return;
10546 else
10548 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10549 pItem->SetCount( pItem->GetCount() - count + remcount );
10550 if (IsInWorld() & update)
10551 pItem->SendUpdateToPlayer( this );
10552 pItem->SetState(ITEM_CHANGED, this);
10553 return;
10559 // in inventory bags
10560 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10562 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10564 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10566 if(Item* pItem = pBag->GetItemByPos(j))
10568 if (pItem->GetEntry() == item)
10570 // all items in bags can be unequipped
10571 if (pItem->GetCount() + remcount <= count)
10573 remcount += pItem->GetCount();
10574 DestroyItem( i, j, update );
10576 if (remcount >=count)
10577 return;
10579 else
10581 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10582 pItem->SetCount( pItem->GetCount() - count + remcount );
10583 if (IsInWorld() && update)
10584 pItem->SendUpdateToPlayer( this );
10585 pItem->SetState(ITEM_CHANGED, this);
10586 return;
10594 // in equipment and bag list
10595 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10597 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10599 if (pItem && pItem->GetEntry() == item)
10601 if (pItem->GetCount() + remcount <= count)
10603 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10605 remcount += pItem->GetCount();
10606 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10608 if (remcount >=count)
10609 return;
10612 else
10614 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10615 pItem->SetCount( pItem->GetCount() - count + remcount );
10616 if (IsInWorld() & update)
10617 pItem->SendUpdateToPlayer( this );
10618 pItem->SetState(ITEM_CHANGED, this);
10619 return;
10626 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10628 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10630 // in inventory
10631 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10632 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10633 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10634 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10636 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10637 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10638 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10639 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10641 // in inventory bags
10642 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10643 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10644 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10645 if (Item* pItem = pBag->GetItemByPos(j))
10646 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10647 DestroyItem( i, j, update);
10649 // in equipment and bag list
10650 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10651 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10652 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10653 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10656 void Player::DestroyConjuredItems( bool update )
10658 // used when entering arena
10659 // destroys all conjured items
10660 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10662 // in inventory
10663 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10664 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10665 if (pItem->IsConjuredConsumable())
10666 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10668 // in inventory bags
10669 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10670 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10671 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10672 if (Item* pItem = pBag->GetItemByPos(j))
10673 if (pItem->IsConjuredConsumable())
10674 DestroyItem( i, j, update);
10676 // in equipment and bag list
10677 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10678 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10679 if (pItem->IsConjuredConsumable())
10680 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10683 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10685 if(!pItem)
10686 return;
10688 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10690 if( pItem->GetCount() <= count )
10692 count-= pItem->GetCount();
10694 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10696 else
10698 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10699 pItem->SetCount( pItem->GetCount() - count );
10700 count = 0;
10701 if( IsInWorld() & update )
10702 pItem->SendUpdateToPlayer( this );
10703 pItem->SetState(ITEM_CHANGED, this);
10707 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10709 uint8 srcbag = src >> 8;
10710 uint8 srcslot = src & 255;
10712 uint8 dstbag = dst >> 8;
10713 uint8 dstslot = dst & 255;
10715 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10716 if( !pSrcItem )
10718 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10719 return;
10722 // not let split all items (can be only at cheating)
10723 if(pSrcItem->GetCount() == count)
10725 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10726 return;
10729 // not let split more existed items (can be only at cheating)
10730 if(pSrcItem->GetCount() < count)
10732 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10733 return;
10736 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10738 //best error message found for attempting to split while looting
10739 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10740 return;
10743 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10744 Item *pNewItem = pSrcItem->CloneItem( count, this );
10745 if( !pNewItem )
10747 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10748 return;
10751 if( IsInventoryPos( dst ) )
10753 // change item amount before check (for unique max count check)
10754 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10756 ItemPosCountVec dest;
10757 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10758 if( msg != EQUIP_ERR_OK )
10760 delete pNewItem;
10761 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10762 SendEquipError( msg, pSrcItem, NULL );
10763 return;
10766 if( IsInWorld() )
10767 pSrcItem->SendUpdateToPlayer( this );
10768 pSrcItem->SetState(ITEM_CHANGED, this);
10769 StoreItem( dest, pNewItem, true);
10771 else if( IsBankPos ( dst ) )
10773 // change item amount before check (for unique max count check)
10774 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10776 ItemPosCountVec dest;
10777 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10778 if( msg != EQUIP_ERR_OK )
10780 delete pNewItem;
10781 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10782 SendEquipError( msg, pSrcItem, NULL );
10783 return;
10786 if( IsInWorld() )
10787 pSrcItem->SendUpdateToPlayer( this );
10788 pSrcItem->SetState(ITEM_CHANGED, this);
10789 BankItem( dest, pNewItem, true);
10791 else if( IsEquipmentPos ( dst ) )
10793 // change item amount before check (for unique max count check), provide space for splitted items
10794 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10796 uint16 dest;
10797 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10798 if( msg != EQUIP_ERR_OK )
10800 delete pNewItem;
10801 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10802 SendEquipError( msg, pSrcItem, NULL );
10803 return;
10806 if( IsInWorld() )
10807 pSrcItem->SendUpdateToPlayer( this );
10808 pSrcItem->SetState(ITEM_CHANGED, this);
10809 EquipItem( dest, pNewItem, true);
10810 AutoUnequipOffhandIfNeed();
10814 void Player::SwapItem( uint16 src, uint16 dst )
10816 uint8 srcbag = src >> 8;
10817 uint8 srcslot = src & 255;
10819 uint8 dstbag = dst >> 8;
10820 uint8 dstslot = dst & 255;
10822 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10823 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10825 if( !pSrcItem )
10826 return;
10828 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10830 if(!isAlive() )
10832 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10833 return;
10836 // SRC checks
10838 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10840 //best error message found for attempting to swap while looting
10841 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10842 return;
10845 // check unequip potability for equipped items and bank bags
10846 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10848 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10849 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10850 if(msg != EQUIP_ERR_OK)
10852 SendEquipError( msg, pSrcItem, pDstItem );
10853 return;
10857 // prevent put equipped/bank bag in self
10858 if( IsBagPos ( src ) && srcslot == dstbag)
10860 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10861 return;
10864 // DST checks
10866 if (pDstItem)
10868 if(pDstItem->m_lootGenerated) // prevent swap looting item
10870 //best error message found for attempting to swap while looting
10871 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10872 return;
10875 // check unequip potability for equipped items and bank bags
10876 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10878 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10879 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10880 if(msg != EQUIP_ERR_OK)
10882 SendEquipError( msg, pSrcItem, pDstItem );
10883 return;
10888 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10889 // or swap empty bag with another empty or not empty bag (with items exchange)
10891 // Move case
10892 if( !pDstItem )
10894 if( IsInventoryPos( dst ) )
10896 ItemPosCountVec dest;
10897 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10898 if( msg != EQUIP_ERR_OK )
10900 SendEquipError( msg, pSrcItem, NULL );
10901 return;
10904 RemoveItem(srcbag, srcslot, true);
10905 StoreItem( dest, pSrcItem, true);
10907 else if( IsBankPos ( dst ) )
10909 ItemPosCountVec dest;
10910 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10911 if( msg != EQUIP_ERR_OK )
10913 SendEquipError( msg, pSrcItem, NULL );
10914 return;
10917 RemoveItem(srcbag, srcslot, true);
10918 BankItem( dest, pSrcItem, true);
10920 else if( IsEquipmentPos ( dst ) )
10922 uint16 dest;
10923 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10924 if( msg != EQUIP_ERR_OK )
10926 SendEquipError( msg, pSrcItem, NULL );
10927 return;
10930 RemoveItem(srcbag, srcslot, true);
10931 EquipItem( dest, pSrcItem, true);
10932 AutoUnequipOffhandIfNeed();
10935 return;
10938 // attempt merge to / fill target item
10939 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10941 uint8 msg;
10942 ItemPosCountVec sDest;
10943 uint16 eDest;
10944 if( IsInventoryPos( dst ) )
10945 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10946 else if( IsBankPos ( dst ) )
10947 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10948 else if( IsEquipmentPos ( dst ) )
10949 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10950 else
10951 return;
10953 // can be merge/fill
10954 if(msg == EQUIP_ERR_OK)
10956 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10958 RemoveItem(srcbag, srcslot, true);
10960 if( IsInventoryPos( dst ) )
10961 StoreItem( sDest, pSrcItem, true);
10962 else if( IsBankPos ( dst ) )
10963 BankItem( sDest, pSrcItem, true);
10964 else if( IsEquipmentPos ( dst ) )
10966 EquipItem( eDest, pSrcItem, true);
10967 AutoUnequipOffhandIfNeed();
10970 else
10972 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10973 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10974 pSrcItem->SetState(ITEM_CHANGED, this);
10975 pDstItem->SetState(ITEM_CHANGED, this);
10976 if( IsInWorld() )
10978 pSrcItem->SendUpdateToPlayer( this );
10979 pDstItem->SendUpdateToPlayer( this );
10982 return;
10986 // impossible merge/fill, do real swap
10987 uint8 msg;
10989 // check src->dest move possibility
10990 ItemPosCountVec sDest;
10991 uint16 eDest = 0;
10992 if( IsInventoryPos( dst ) )
10993 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10994 else if( IsBankPos( dst ) )
10995 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10996 else if( IsEquipmentPos( dst ) )
10998 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10999 if( msg == EQUIP_ERR_OK )
11000 msg = CanUnequipItem( eDest, true );
11003 if( msg != EQUIP_ERR_OK )
11005 SendEquipError( msg, pSrcItem, pDstItem );
11006 return;
11009 // check dest->src move possibility
11010 ItemPosCountVec sDest2;
11011 uint16 eDest2 = 0;
11012 if( IsInventoryPos( src ) )
11013 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11014 else if( IsBankPos( src ) )
11015 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11016 else if( IsEquipmentPos( src ) )
11018 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11019 if( msg == EQUIP_ERR_OK )
11020 msg = CanUnequipItem( eDest2, true);
11023 if( msg != EQUIP_ERR_OK )
11025 SendEquipError( msg, pDstItem, pSrcItem );
11026 return;
11029 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11030 if(pSrcItem->IsBag() && pDstItem->IsBag())
11032 Bag* emptyBag = NULL;
11033 Bag* fullBag = NULL;
11034 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11036 emptyBag = (Bag*)pSrcItem;
11037 fullBag = (Bag*)pDstItem;
11039 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11041 emptyBag = (Bag*)pDstItem;
11042 fullBag = (Bag*)pSrcItem;
11045 // bag swap (with items exchange) case
11046 if(emptyBag && fullBag)
11048 ItemPrototype const* emotyProto = emptyBag->GetProto();
11050 uint32 count = 0;
11052 for(int i=0; i < fullBag->GetBagSize(); ++i)
11054 Item *bagItem = fullBag->GetItemByPos(i);
11055 if (!bagItem)
11056 continue;
11058 ItemPrototype const* bagItemProto = bagItem->GetProto();
11059 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11061 // one from items not go to empry target bag
11062 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11063 return;
11066 ++count;
11070 if (count > emptyBag->GetBagSize())
11072 // too small targeted bag
11073 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11074 return;
11077 // Items swap
11078 count = 0; // will pos in new bag
11079 for(int i=0; i< fullBag->GetBagSize(); ++i)
11081 Item *bagItem = fullBag->GetItemByPos(i);
11082 if (!bagItem)
11083 continue;
11085 fullBag->RemoveItem(i, true);
11086 emptyBag->StoreItem(count, bagItem, true);
11087 bagItem->SetState(ITEM_CHANGED, this);
11089 ++count;
11094 // now do moves, remove...
11095 RemoveItem(dstbag, dstslot, false);
11096 RemoveItem(srcbag, srcslot, false);
11098 // add to dest
11099 if( IsInventoryPos( dst ) )
11100 StoreItem(sDest, pSrcItem, true);
11101 else if( IsBankPos( dst ) )
11102 BankItem(sDest, pSrcItem, true);
11103 else if( IsEquipmentPos( dst ) )
11104 EquipItem(eDest, pSrcItem, true);
11106 // add to src
11107 if( IsInventoryPos( src ) )
11108 StoreItem(sDest2, pDstItem, true);
11109 else if( IsBankPos( src ) )
11110 BankItem(sDest2, pDstItem, true);
11111 else if( IsEquipmentPos( src ) )
11112 EquipItem(eDest2, pDstItem, true);
11114 AutoUnequipOffhandIfNeed();
11117 void Player::AddItemToBuyBackSlot( Item *pItem )
11119 if( pItem )
11121 uint32 slot = m_currentBuybackSlot;
11122 // if current back slot non-empty search oldest or free
11123 if(m_items[slot])
11125 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11126 uint32 oldest_slot = BUYBACK_SLOT_START;
11128 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11130 // found empty
11131 if(!m_items[i])
11133 slot = i;
11134 break;
11137 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11139 if(oldest_time > i_time)
11141 oldest_time = i_time;
11142 oldest_slot = i;
11146 // find oldest
11147 slot = oldest_slot;
11150 RemoveItemFromBuyBackSlot( slot, true );
11151 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11153 m_items[slot] = pItem;
11154 time_t base = time(NULL);
11155 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11156 uint32 eslot = slot - BUYBACK_SLOT_START;
11158 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11159 ItemPrototype const *pProto = pItem->GetProto();
11160 if( pProto )
11161 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11162 else
11163 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11164 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11166 // move to next (for non filled list is move most optimized choice)
11167 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11168 ++m_currentBuybackSlot;
11172 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11174 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11175 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11176 return m_items[slot];
11177 return NULL;
11180 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11182 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11183 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11185 Item *pItem = m_items[slot];
11186 if( pItem )
11188 pItem->RemoveFromWorld();
11189 if(del) pItem->SetState(ITEM_REMOVED, this);
11192 m_items[slot] = NULL;
11194 uint32 eslot = slot - BUYBACK_SLOT_START;
11195 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11196 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11197 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11199 // if current backslot is filled set to now free slot
11200 if(m_items[m_currentBuybackSlot])
11201 m_currentBuybackSlot = slot;
11205 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11207 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11208 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11209 data << uint8(msg);
11211 if(msg)
11213 data << uint64(pItem ? pItem->GetGUID() : 0);
11214 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11215 data << uint8(0); // not 0 there...
11217 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11219 uint32 level = 0;
11221 if(pItem)
11222 if(ItemPrototype const* proto = pItem->GetProto())
11223 level = proto->RequiredLevel;
11225 data << uint32(level); // new 2.4.0
11228 GetSession()->SendPacket(&data);
11231 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11233 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11234 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11235 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11236 data << uint32(item);
11237 if( param > 0 )
11238 data << uint32(param);
11239 data << uint8(msg);
11240 GetSession()->SendPacket(&data);
11243 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11245 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11246 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11247 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11248 data << uint64(guid);
11249 if( param > 0 )
11250 data << uint32(param);
11251 data << uint8(msg);
11252 GetSession()->SendPacket(&data);
11255 void Player::ClearTrade()
11257 tradeGold = 0;
11258 acceptTrade = false;
11259 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11260 tradeItems[i] = NULL_SLOT;
11263 void Player::TradeCancel(bool sendback)
11265 if(pTrader)
11267 // send yellow "Trade canceled" message to both traders
11268 WorldSession* ws;
11269 ws = GetSession();
11270 if(sendback)
11271 ws->SendCancelTrade();
11272 ws = pTrader->GetSession();
11273 if(!ws->PlayerLogout())
11274 ws->SendCancelTrade();
11276 // cleanup
11277 ClearTrade();
11278 pTrader->ClearTrade();
11279 // prevent loss of reference
11280 pTrader->pTrader = NULL;
11281 pTrader = NULL;
11285 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11287 if(m_itemDuration.empty())
11288 return;
11290 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11292 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11294 Item* item = *itr;
11295 ++itr; // current element can be erased in UpdateDuration
11297 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11298 item->UpdateDuration(this,time);
11302 void Player::UpdateEnchantTime(uint32 time)
11304 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11306 assert(itr->item);
11307 next=itr;
11308 if(!itr->item->GetEnchantmentId(itr->slot))
11310 next = m_enchantDuration.erase(itr);
11312 else if(itr->leftduration <= time)
11314 ApplyEnchantment(itr->item,itr->slot,false,false);
11315 itr->item->ClearEnchantment(itr->slot);
11316 next = m_enchantDuration.erase(itr);
11318 else if(itr->leftduration > time)
11320 itr->leftduration -= time;
11321 ++next;
11326 void Player::AddEnchantmentDurations(Item *item)
11328 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11330 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11331 continue;
11333 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11334 if( duration > 0 )
11335 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11339 void Player::RemoveEnchantmentDurations(Item *item)
11341 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11343 if(itr->item == item)
11345 // save duration in item
11346 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11347 itr = m_enchantDuration.erase(itr);
11349 else
11350 ++itr;
11354 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11356 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11357 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11359 next = itr;
11360 if(itr->slot==slot)
11362 if(itr->item && itr->item->GetEnchantmentId(slot))
11364 // remove from stats
11365 ApplyEnchantment(itr->item,slot,false,false);
11366 // remove visual
11367 itr->item->ClearEnchantment(slot);
11369 // remove from update list
11370 next = m_enchantDuration.erase(itr);
11372 else
11373 ++next;
11376 // remove enchants from inventory items
11377 // NOTE: no need to remove these from stats, since these aren't equipped
11378 // in inventory
11379 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11381 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11382 if( pItem && pItem->GetEnchantmentId(slot) )
11383 pItem->ClearEnchantment(slot);
11386 // in inventory bags
11387 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11389 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11390 if( pBag )
11392 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11394 Item* pItem = pBag->GetItemByPos(j);
11395 if( pItem && pItem->GetEnchantmentId(slot) )
11396 pItem->ClearEnchantment(slot);
11402 // duration == 0 will remove item enchant
11403 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11405 if(!item)
11406 return;
11408 if(slot >= MAX_ENCHANTMENT_SLOT)
11409 return;
11411 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11413 if(itr->item == item && itr->slot == slot)
11415 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11416 m_enchantDuration.erase(itr);
11417 break;
11420 if(item && duration > 0 )
11422 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11423 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11427 void Player::ApplyEnchantment(Item *item,bool apply)
11429 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11430 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11433 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11435 if(!item)
11436 return;
11438 if(!item->IsEquipped())
11439 return;
11441 if(slot >= MAX_ENCHANTMENT_SLOT)
11442 return;
11444 uint32 enchant_id = item->GetEnchantmentId(slot);
11445 if(!enchant_id)
11446 return;
11448 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11449 if(!pEnchant)
11450 return;
11452 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11453 return;
11455 if (!item->IsBroken())
11457 for (int s=0; s<3; s++)
11459 uint32 enchant_display_type = pEnchant->type[s];
11460 uint32 enchant_amount = pEnchant->amount[s];
11461 uint32 enchant_spell_id = pEnchant->spellid[s];
11463 switch(enchant_display_type)
11465 case ITEM_ENCHANTMENT_TYPE_NONE:
11466 break;
11467 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11468 // processed in Player::CastItemCombatSpell
11469 break;
11470 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11471 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11472 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11473 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11474 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11475 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11476 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11477 break;
11478 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11479 if(enchant_spell_id)
11481 if(apply)
11483 int32 basepoints = 0;
11484 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11485 if (item->GetItemRandomPropertyId())
11487 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11488 if (item_rand)
11490 // Search enchant_amount
11491 for (int k=0; k<3; k++)
11493 if(item_rand->enchant_id[k] == enchant_id)
11495 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11496 break;
11501 // Cast custom spell vs all equal basepoints getted from enchant_amount
11502 if (basepoints)
11503 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11504 else
11505 CastSpell(this,enchant_spell_id,true,item);
11507 else
11508 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11510 break;
11511 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11512 if (!enchant_amount)
11514 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11515 if(item_rand)
11517 for (int k=0; k<3; k++)
11519 if(item_rand->enchant_id[k] == enchant_id)
11521 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11522 break;
11528 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11529 break;
11530 case ITEM_ENCHANTMENT_TYPE_STAT:
11532 if (!enchant_amount)
11534 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11535 if(item_rand_suffix)
11537 for (int k=0; k<3; k++)
11539 if(item_rand_suffix->enchant_id[k] == enchant_id)
11541 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11542 break;
11548 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11549 switch (enchant_spell_id)
11551 case ITEM_MOD_AGILITY:
11552 sLog.outDebug("+ %u AGILITY",enchant_amount);
11553 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11554 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11555 break;
11556 case ITEM_MOD_STRENGTH:
11557 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11558 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11559 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11560 break;
11561 case ITEM_MOD_INTELLECT:
11562 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11563 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11564 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11565 break;
11566 case ITEM_MOD_SPIRIT:
11567 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11568 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11569 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11570 break;
11571 case ITEM_MOD_STAMINA:
11572 sLog.outDebug("+ %u STAMINA",enchant_amount);
11573 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11574 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11575 break;
11576 case ITEM_MOD_DEFENSE_SKILL_RATING:
11577 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11578 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11579 break;
11580 case ITEM_MOD_DODGE_RATING:
11581 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11582 sLog.outDebug("+ %u DODGE", enchant_amount);
11583 break;
11584 case ITEM_MOD_PARRY_RATING:
11585 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11586 sLog.outDebug("+ %u PARRY", enchant_amount);
11587 break;
11588 case ITEM_MOD_BLOCK_RATING:
11589 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11590 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11591 break;
11592 case ITEM_MOD_HIT_MELEE_RATING:
11593 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11594 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11595 break;
11596 case ITEM_MOD_HIT_RANGED_RATING:
11597 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11598 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11599 break;
11600 case ITEM_MOD_HIT_SPELL_RATING:
11601 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11602 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11603 break;
11604 case ITEM_MOD_CRIT_MELEE_RATING:
11605 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11606 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11607 break;
11608 case ITEM_MOD_CRIT_RANGED_RATING:
11609 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11610 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11611 break;
11612 case ITEM_MOD_CRIT_SPELL_RATING:
11613 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11614 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11615 break;
11616 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11617 // in Enchantments
11618 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11619 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11620 // break;
11621 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11622 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11623 // break;
11624 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11625 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11626 // break;
11627 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11628 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11629 // break;
11630 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11631 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11632 // break;
11633 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11634 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11635 // break;
11636 // case ITEM_MOD_HASTE_MELEE_RATING:
11637 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11638 // break;
11639 // case ITEM_MOD_HASTE_RANGED_RATING:
11640 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11641 // break;
11642 case ITEM_MOD_HASTE_SPELL_RATING:
11643 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11644 break;
11645 case ITEM_MOD_HIT_RATING:
11646 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11647 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11648 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11649 sLog.outDebug("+ %u HIT", enchant_amount);
11650 break;
11651 case ITEM_MOD_CRIT_RATING:
11652 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11653 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11654 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11655 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11656 break;
11657 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11658 // case ITEM_MOD_HIT_TAKEN_RATING:
11659 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11660 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11661 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11662 // break;
11663 // case ITEM_MOD_CRIT_TAKEN_RATING:
11664 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11665 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11666 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11667 // break;
11668 case ITEM_MOD_RESILIENCE_RATING:
11669 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11670 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11671 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11672 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11673 break;
11674 case ITEM_MOD_HASTE_RATING:
11675 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11676 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11677 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11678 sLog.outDebug("+ %u HASTE", enchant_amount);
11679 break;
11680 case ITEM_MOD_EXPERTISE_RATING:
11681 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11682 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11683 break;
11684 case ITEM_MOD_ATTACK_POWER:
11685 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11686 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11687 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11688 break;
11689 case ITEM_MOD_RANGED_ATTACK_POWER:
11690 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11691 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11692 break;
11693 case ITEM_MOD_FERAL_ATTACK_POWER:
11694 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11695 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11696 break;
11697 case ITEM_MOD_SPELL_HEALING_DONE:
11698 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11699 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11700 break;
11701 case ITEM_MOD_SPELL_DAMAGE_DONE:
11702 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11703 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11704 break;
11705 case ITEM_MOD_MANA_REGENERATION:
11706 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11707 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11708 break;
11709 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11710 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11711 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11712 break;
11713 case ITEM_MOD_SPELL_POWER:
11714 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11715 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11716 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11717 break;
11718 default:
11719 break;
11721 break;
11723 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11725 if(getClass() == CLASS_SHAMAN)
11727 float addValue = 0.0f;
11728 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11730 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11731 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11733 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11735 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11736 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11739 break;
11741 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11742 // processed in Player::CastItemUseSpell
11743 break;
11744 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11745 // nothing do..
11746 break;
11747 default:
11748 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11749 break;
11750 } /*switch(enchant_display_type)*/
11751 } /*for*/
11754 // visualize enchantment at player and equipped items
11755 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11757 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11758 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11761 if(apply_dur)
11763 if(apply)
11765 // set duration
11766 uint32 duration = item->GetEnchantmentDuration(slot);
11767 if(duration > 0)
11768 AddEnchantmentDuration(item,slot,duration);
11770 else
11772 // duration == 0 will remove EnchantDuration
11773 AddEnchantmentDuration(item,slot,0);
11778 void Player::SendEnchantmentDurations()
11780 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11782 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11786 void Player::SendItemDurations()
11788 for(ItemDurationList::const_iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11790 (*itr)->SendTimeUpdate(this);
11794 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11796 if(!item) // prevent crash
11797 return;
11799 // last check 2.0.10
11800 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11801 data << GetGUID(); // player GUID
11802 data << uint32(received); // 0=looted, 1=from npc
11803 data << uint32(created); // 0=received, 1=created
11804 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11805 data << (uint8)item->GetBagSlot(); // bagslot
11806 // item slot, but when added to stack: 0xFFFFFFFF
11807 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11808 data << uint32(item->GetEntry()); // item id
11809 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11810 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11811 data << uint32(count); // count of items
11812 data << GetItemCount(item->GetEntry()); // count of items in inventory
11814 if (broadcast && GetGroup())
11815 GetGroup()->BroadcastPacket(&data, true);
11816 else
11817 GetSession()->SendPacket(&data);
11820 /*********************************************************/
11821 /*** QUEST SYSTEM ***/
11822 /*********************************************************/
11824 void Player::PrepareQuestMenu( uint64 guid )
11826 Object *pObject;
11827 QuestRelations* pObjectQR;
11828 QuestRelations* pObjectQIR;
11830 // pets also can have quests
11831 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11832 if( pCreature )
11834 pObject = (Object*)pCreature;
11835 pObjectQR = &objmgr.mCreatureQuestRelations;
11836 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11838 else
11840 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11841 if( pGameObject )
11843 pObject = (Object*)pGameObject;
11844 pObjectQR = &objmgr.mGOQuestRelations;
11845 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11847 else
11848 return;
11851 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11852 qm.ClearMenu();
11854 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11856 uint32 quest_id = i->second;
11857 QuestStatus status = GetQuestStatus( quest_id );
11858 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11859 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11860 else if ( status == QUEST_STATUS_INCOMPLETE )
11861 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11862 else if (status == QUEST_STATUS_AVAILABLE )
11863 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11866 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11868 uint32 quest_id = i->second;
11869 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11870 if(!pQuest) continue;
11872 QuestStatus status = GetQuestStatus( quest_id );
11874 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11875 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11876 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11877 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11881 void Player::SendPreparedQuest( uint64 guid )
11883 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11884 if( questMenu.Empty() )
11885 return;
11887 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11889 uint32 status = qmi0.m_qIcon;
11891 // single element case
11892 if ( questMenu.MenuItemCount() == 1 )
11894 // Auto open -- maybe also should verify there is no greeting
11895 uint32 quest_id = qmi0.m_qId;
11896 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11897 if ( pQuest )
11899 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11900 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11901 else if( status == DIALOG_STATUS_INCOMPLETE )
11902 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11903 // Send completable on repeatable quest if player don't have quest
11904 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11905 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11906 else
11907 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11910 // multiply entries
11911 else
11913 QEmote qe;
11914 qe._Delay = 0;
11915 qe._Emote = 0;
11916 std::string title = "";
11918 // need pet case for some quests
11919 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11920 if( pCreature )
11922 uint32 textid = pCreature->GetNpcTextId();
11923 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11924 if( !gossiptext )
11926 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11927 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11928 title = "";
11930 else
11932 qe = gossiptext->Options[0].Emotes[0];
11934 if(!gossiptext->Options[0].Text_0.empty())
11936 title = gossiptext->Options[0].Text_0;
11938 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11939 if (loc_idx >= 0)
11941 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11942 if (nl)
11944 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11945 title = nl->Text_0[0][loc_idx];
11949 else
11951 title = gossiptext->Options[0].Text_1;
11953 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11954 if (loc_idx >= 0)
11956 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11957 if (nl)
11959 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11960 title = nl->Text_1[0][loc_idx];
11966 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11970 bool Player::IsActiveQuest( uint32 quest_id ) const
11972 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11974 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11977 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11979 Object *pObject;
11980 QuestRelations* pObjectQR;
11981 QuestRelations* pObjectQIR;
11983 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11984 if( pCreature )
11986 pObject = (Object*)pCreature;
11987 pObjectQR = &objmgr.mCreatureQuestRelations;
11988 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11990 else
11992 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11993 if( pGameObject )
11995 pObject = (Object*)pGameObject;
11996 pObjectQR = &objmgr.mGOQuestRelations;
11997 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11999 else
12000 return NULL;
12003 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12004 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12006 if (itr->second == nextQuestID)
12007 return objmgr.GetQuestTemplate(nextQuestID);
12010 return NULL;
12013 bool Player::CanSeeStartQuest( Quest const *pQuest )
12015 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12016 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12017 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12018 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12020 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12023 return false;
12026 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12028 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12029 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12030 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12031 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12032 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12033 && SatisfyQuestDay( pQuest, msg );
12036 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12038 if( !SatisfyQuestLog( msg ) )
12039 return false;
12041 uint32 srcitem = pQuest->GetSrcItemId();
12042 if( srcitem > 0 )
12044 uint32 count = pQuest->GetSrcItemCount();
12045 ItemPosCountVec dest;
12046 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12048 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12049 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12050 return true;
12051 else if( msg2 != EQUIP_ERR_OK )
12053 SendEquipError( msg2, NULL, NULL );
12054 return false;
12057 return true;
12060 bool Player::CanCompleteQuest( uint32 quest_id )
12062 if( quest_id )
12064 QuestStatusData& q_status = mQuestStatus[quest_id];
12065 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12066 return false; // not allow re-complete quest
12068 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12070 if(!qInfo)
12071 return false;
12073 // auto complete quest
12074 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12075 return true;
12077 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12080 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12082 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12084 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12085 return false;
12089 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12091 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12093 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12094 continue;
12096 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12097 return false;
12101 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12102 return false;
12104 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12105 return false;
12107 if ( qInfo->GetRewOrReqMoney() < 0 )
12109 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12110 return false;
12113 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12114 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12115 return false;
12117 return true;
12120 return false;
12123 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12125 // Solve problem that player don't have the quest and try complete it.
12126 // if repeatable she must be able to complete event if player don't have it.
12127 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12128 if( !CanTakeQuest(pQuest, false) )
12129 return false;
12131 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12132 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12133 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12134 return false;
12136 if( !CanRewardQuest(pQuest, false) )
12137 return false;
12139 return true;
12142 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12144 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12145 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12146 return false;
12148 // daily quest can't be rewarded (25 daily quest already completed)
12149 if(!SatisfyQuestDay(pQuest,true))
12150 return false;
12152 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12153 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12154 return false;
12156 // prevent receive reward with quest items in bank
12157 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12159 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12161 if( pQuest->ReqItemCount[i]!= 0 &&
12162 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12164 if(msg)
12165 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12166 return false;
12171 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12172 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12173 return false;
12175 return true;
12178 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12180 // prevent receive reward with quest items in bank or for not completed quest
12181 if(!CanRewardQuest(pQuest,msg))
12182 return false;
12184 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12186 if( pQuest->RewChoiceItemId[reward] )
12188 ItemPosCountVec dest;
12189 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12190 if( res != EQUIP_ERR_OK )
12192 SendEquipError( res, NULL, NULL );
12193 return false;
12198 if ( pQuest->GetRewItemsCount() > 0 )
12200 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12202 if( pQuest->RewItemId[i] )
12204 ItemPosCountVec dest;
12205 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12206 if( res != EQUIP_ERR_OK )
12208 SendEquipError( res, NULL, NULL );
12209 return false;
12215 return true;
12218 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12220 uint16 log_slot = FindQuestSlot( 0 );
12221 assert(log_slot < MAX_QUEST_LOG_SIZE);
12223 uint32 quest_id = pQuest->GetQuestId();
12225 // if not exist then created with set uState==NEW and rewarded=false
12226 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12228 // check for repeatable quests status reset
12229 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12230 questStatusData.m_explored = false;
12232 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12234 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12235 questStatusData.m_itemcount[i] = 0;
12238 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12240 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12241 questStatusData.m_creatureOrGOcount[i] = 0;
12244 GiveQuestSourceItem( pQuest );
12245 AdjustQuestReqItemCount( pQuest, questStatusData );
12247 if( pQuest->GetRepObjectiveFaction() )
12248 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12249 GetReputationMgr().SetVisible(factionEntry);
12251 uint32 qtime = 0;
12252 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12254 uint32 limittime = pQuest->GetLimitTime();
12256 // shared timed quest
12257 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12258 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12260 AddTimedQuest( quest_id );
12261 questStatusData.m_timer = limittime * IN_MILISECONDS;
12262 qtime = static_cast<uint32>(time(NULL)) + limittime;
12264 else
12265 questStatusData.m_timer = 0;
12267 SetQuestSlot(log_slot, quest_id, qtime);
12269 if (questStatusData.uState != QUEST_NEW)
12270 questStatusData.uState = QUEST_CHANGED;
12272 //starting initial quest script
12273 if(questGiver && pQuest->GetQuestStartScript()!=0)
12274 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12276 // Some spells applied at quest activation
12277 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12278 if(saBounds.first != saBounds.second)
12280 uint32 zone, area;
12281 GetZoneAndAreaId(zone,area);
12283 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12284 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12285 if( !HasAura(itr->second->spellId,0) )
12286 CastSpell(this,itr->second->spellId,true);
12289 UpdateForQuestWorldObjects();
12292 void Player::CompleteQuest( uint32 quest_id )
12294 if( quest_id )
12296 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12298 uint16 log_slot = FindQuestSlot( quest_id );
12299 if( log_slot < MAX_QUEST_LOG_SIZE)
12300 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12302 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12304 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12305 RewardQuest(qInfo,0,this,false);
12306 else
12307 SendQuestComplete( quest_id );
12312 void Player::IncompleteQuest( uint32 quest_id )
12314 if( quest_id )
12316 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12318 uint16 log_slot = FindQuestSlot( quest_id );
12319 if( log_slot < MAX_QUEST_LOG_SIZE)
12320 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12324 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12326 uint32 quest_id = pQuest->GetQuestId();
12328 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12330 if ( pQuest->ReqItemId[i] )
12331 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12334 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12335 // SetTimedQuest( 0 );
12336 m_timedquests.erase(pQuest->GetQuestId());
12338 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12340 if( pQuest->RewChoiceItemId[reward] )
12342 ItemPosCountVec dest;
12343 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12345 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12346 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12351 if ( pQuest->GetRewItemsCount() > 0 )
12353 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12355 if( pQuest->RewItemId[i] )
12357 ItemPosCountVec dest;
12358 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12360 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12361 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12367 RewardReputation( pQuest );
12369 if( pQuest->GetRewSpellCast() > 0 )
12370 CastSpell( this, pQuest->GetRewSpellCast(), true);
12371 else if( pQuest->GetRewSpell() > 0)
12372 CastSpell( this, pQuest->GetRewSpell(), true);
12374 uint16 log_slot = FindQuestSlot( quest_id );
12375 if( log_slot < MAX_QUEST_LOG_SIZE)
12376 SetQuestSlot(log_slot,0);
12378 QuestStatusData& q_status = mQuestStatus[quest_id];
12380 // Not give XP in case already completed once repeatable quest
12381 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12383 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12384 GiveXP( XP , NULL );
12385 else
12387 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12388 ModifyMoney( money );
12389 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12392 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12393 if(pQuest->GetRewOrReqMoney())
12395 ModifyMoney( pQuest->GetRewOrReqMoney() );
12397 if(pQuest->GetRewOrReqMoney() > 0)
12398 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12401 // honor reward
12402 if(pQuest->GetRewHonorableKills())
12403 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12405 // title reward
12406 if(pQuest->GetCharTitleId())
12408 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12409 SetTitle(titleEntry);
12412 if(pQuest->GetBonusTalents())
12414 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12415 InitTalentForLevel();
12418 // Send reward mail
12419 if(pQuest->GetRewMailTemplateId())
12421 MailMessageType mailType;
12422 uint32 senderGuidOrEntry;
12423 switch(questGiver->GetTypeId())
12425 case TYPEID_UNIT:
12426 mailType = MAIL_CREATURE;
12427 senderGuidOrEntry = questGiver->GetEntry();
12428 break;
12429 case TYPEID_GAMEOBJECT:
12430 mailType = MAIL_GAMEOBJECT;
12431 senderGuidOrEntry = questGiver->GetEntry();
12432 break;
12433 case TYPEID_ITEM:
12434 mailType = MAIL_ITEM;
12435 senderGuidOrEntry = questGiver->GetEntry();
12436 break;
12437 case TYPEID_PLAYER:
12438 mailType = MAIL_NORMAL;
12439 senderGuidOrEntry = questGiver->GetGUIDLow();
12440 break;
12441 default:
12442 mailType = MAIL_NORMAL;
12443 senderGuidOrEntry = GetGUIDLow();
12444 break;
12447 Loot questMailLoot;
12449 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12451 // fill mail
12452 MailItemsInfo mi; // item list preparing
12454 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12455 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12457 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12459 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12461 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12462 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12467 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12470 if(pQuest->IsDaily())
12472 SetDailyQuestStatus(quest_id);
12473 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12476 if ( !pQuest->IsRepeatable() )
12477 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12478 else
12479 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12481 q_status.m_rewarded = true;
12483 if(announce)
12484 SendQuestReward( pQuest, XP, questGiver );
12486 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12487 if (pQuest->GetZoneOrSort() > 0)
12488 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12489 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12490 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12492 uint32 zone = 0;
12493 uint32 area = 0;
12495 // remove auras from spells with quest reward state limitations
12496 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12497 if(saEndBounds.first != saEndBounds.second)
12499 GetZoneAndAreaId(zone,area);
12501 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12502 if(!itr->second->IsFitToRequirements(this,zone,area))
12503 RemoveAurasDueToSpell(itr->second->spellId);
12506 // Some spells applied at quest reward
12507 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12508 if(saBounds.first != saBounds.second)
12510 if(!zone || !area)
12511 GetZoneAndAreaId(zone,area);
12513 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12514 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12515 if( !HasAura(itr->second->spellId,0) )
12516 CastSpell(this,itr->second->spellId,true);
12520 void Player::FailQuest( uint32 quest_id )
12522 if( quest_id )
12524 IncompleteQuest( quest_id );
12526 uint16 log_slot = FindQuestSlot( quest_id );
12527 if( log_slot < MAX_QUEST_LOG_SIZE)
12529 SetQuestSlotTimer(log_slot, 1 );
12530 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12532 SendQuestFailed( quest_id );
12536 void Player::FailTimedQuest( uint32 quest_id )
12538 if( quest_id )
12540 QuestStatusData& q_status = mQuestStatus[quest_id];
12542 q_status.m_timer = 0;
12543 if (q_status.uState != QUEST_NEW)
12544 q_status.uState = QUEST_CHANGED;
12546 IncompleteQuest( quest_id );
12548 uint16 log_slot = FindQuestSlot( quest_id );
12549 if( log_slot < MAX_QUEST_LOG_SIZE)
12551 SetQuestSlotTimer(log_slot, 1 );
12552 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12554 SendQuestTimerFailed( quest_id );
12558 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12560 int32 zoneOrSort = qInfo->GetZoneOrSort();
12561 int32 skillOrClass = qInfo->GetSkillOrClass();
12563 // skip zone zoneOrSort and 0 case skillOrClass
12564 if( zoneOrSort >= 0 && skillOrClass == 0 )
12565 return true;
12567 int32 questSort = -zoneOrSort;
12568 uint8 reqSortClass = ClassByQuestSort(questSort);
12570 // check class sort cases in zoneOrSort
12571 if( reqSortClass != 0 && getClass() != reqSortClass)
12573 if( msg )
12574 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12575 return false;
12578 // check class
12579 if( skillOrClass < 0 )
12581 uint8 reqClass = -int32(skillOrClass);
12582 if(getClass() != reqClass)
12584 if( msg )
12585 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12586 return false;
12589 // check skill
12590 else if( skillOrClass > 0 )
12592 uint32 reqSkill = skillOrClass;
12593 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12595 if( msg )
12596 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12597 return false;
12601 return true;
12604 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12606 if( getLevel() < qInfo->GetMinLevel() )
12608 if( msg )
12609 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12610 return false;
12612 return true;
12615 bool Player::SatisfyQuestLog( bool msg )
12617 // exist free slot
12618 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12619 return true;
12621 if( msg )
12623 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12624 GetSession()->SendPacket( &data );
12625 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12627 return false;
12630 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12632 // No previous quest (might be first quest in a series)
12633 if( qInfo->prevQuests.empty())
12634 return true;
12636 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12638 uint32 prevId = abs(*iter);
12640 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12641 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12643 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12645 // If any of the positive previous quests completed, return true
12646 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12648 // skip one-from-all exclusive group
12649 if(qPrevInfo->GetExclusiveGroup() >= 0)
12650 return true;
12652 // each-from-all exclusive group ( < 0)
12653 // can be start if only all quests in prev quest exclusive group completed and rewarded
12654 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12655 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12657 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12659 for(; iter2 != end; ++iter2)
12661 uint32 exclude_Id = iter2->second;
12663 // skip checked quest id, only state of other quests in group is interesting
12664 if(exclude_Id == prevId)
12665 continue;
12667 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12669 // alternative quest from group also must be completed and rewarded(reported)
12670 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12672 if( msg )
12673 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12674 return false;
12677 return true;
12679 // If any of the negative previous quests active, return true
12680 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12681 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12683 // skip one-from-all exclusive group
12684 if(qPrevInfo->GetExclusiveGroup() >= 0)
12685 return true;
12687 // each-from-all exclusive group ( < 0)
12688 // can be start if only all quests in prev quest exclusive group active
12689 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12690 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12692 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12694 for(; iter2 != end; ++iter2)
12696 uint32 exclude_Id = iter2->second;
12698 // skip checked quest id, only state of other quests in group is interesting
12699 if(exclude_Id == prevId)
12700 continue;
12702 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12704 // alternative quest from group also must be active
12705 if( i_exstatus == mQuestStatus.end() ||
12706 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12707 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12709 if( msg )
12710 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12711 return false;
12714 return true;
12719 // Has only positive prev. quests in non-rewarded state
12720 // and negative prev. quests in non-active state
12721 if( msg )
12722 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12724 return false;
12727 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12729 uint32 reqraces = qInfo->GetRequiredRaces();
12730 if ( reqraces == 0 )
12731 return true;
12732 if( (reqraces & getRaceMask()) == 0 )
12734 if( msg )
12735 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12736 return false;
12738 return true;
12741 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12743 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12744 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12746 if( msg )
12747 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12748 return false;
12751 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12752 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12754 if( msg )
12755 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12756 return false;
12759 return true;
12762 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12764 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12765 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12767 if( msg )
12768 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12769 return false;
12771 return true;
12774 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12776 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12778 if( msg )
12779 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12780 return false;
12782 return true;
12785 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12787 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12788 if(qInfo->GetExclusiveGroup() <= 0)
12789 return true;
12791 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12792 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12794 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12796 for(; iter != end; ++iter)
12798 uint32 exclude_Id = iter->second;
12800 // skip checked quest id, only state of other quests in group is interesting
12801 if(exclude_Id == qInfo->GetQuestId())
12802 continue;
12804 // not allow have daily quest if daily quest from exclusive group already recently completed
12805 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12806 if( !SatisfyQuestDay(Nquest, false) )
12808 if( msg )
12809 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12810 return false;
12813 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12815 // alternative quest already started or completed
12816 if( i_exstatus != mQuestStatus.end()
12817 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12819 if( msg )
12820 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12821 return false;
12824 return true;
12827 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12829 if(!qInfo->GetNextQuestInChain())
12830 return true;
12832 // next quest in chain already started or completed
12833 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12834 if( itr != mQuestStatus.end()
12835 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12837 if( msg )
12838 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12839 return false;
12842 // check for all quests further up the chain
12843 // only necessary if there are quest chains with more than one quest that can be skipped
12844 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12845 return true;
12848 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12850 // No previous quest in chain
12851 if( qInfo->prevChainQuests.empty())
12852 return true;
12854 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12856 uint32 prevId = *iter;
12858 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12860 if( i_prevstatus != mQuestStatus.end() )
12862 // If any of the previous quests in chain active, return false
12863 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12864 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12866 if( msg )
12867 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12868 return false;
12872 // check for all quests further down the chain
12873 // only necessary if there are quest chains with more than one quest that can be skipped
12874 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12875 // return false;
12878 // No previous quest in chain active
12879 return true;
12882 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12884 if(!qInfo->IsDaily())
12885 return true;
12887 bool have_slot = false;
12888 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12890 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12891 if(qInfo->GetQuestId()==id)
12892 return false;
12894 if(!id)
12895 have_slot = true;
12898 if(!have_slot)
12900 if( msg )
12901 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12902 return false;
12905 return true;
12908 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12910 uint32 srcitem = pQuest->GetSrcItemId();
12911 if( srcitem > 0 )
12913 uint32 count = pQuest->GetSrcItemCount();
12914 if( count <= 0 )
12915 count = 1;
12917 ItemPosCountVec dest;
12918 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12919 if( msg == EQUIP_ERR_OK )
12921 Item * item = StoreNewItem(dest, srcitem, true);
12922 SendNewItem(item, count, true, false);
12923 return true;
12925 // player already have max amount required item, just report success
12926 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12927 return true;
12928 else
12929 SendEquipError( msg, NULL, NULL );
12930 return false;
12933 return true;
12936 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12938 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12939 if( qInfo )
12941 uint32 srcitem = qInfo->GetSrcItemId();
12942 if( srcitem > 0 )
12944 uint32 count = qInfo->GetSrcItemCount();
12945 if( count <= 0 )
12946 count = 1;
12948 // exist one case when destroy source quest item not possible:
12949 // non un-equippable item (equipped non-empty bag, for example)
12950 uint8 res = CanUnequipItems(srcitem,count);
12951 if(res != EQUIP_ERR_OK)
12953 if(msg)
12954 SendEquipError( res, NULL, NULL );
12955 return false;
12958 DestroyItemCount(srcitem, count, true, true);
12961 return true;
12964 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12966 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12967 if( qInfo )
12969 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12970 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12971 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12972 && !qInfo->IsRepeatable() )
12973 return itr->second.m_rewarded;
12975 return false;
12977 return false;
12980 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12982 if( quest_id )
12984 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12985 if( itr != mQuestStatus.end() )
12986 return itr->second.m_status;
12988 return QUEST_STATUS_NONE;
12991 bool Player::CanShareQuest(uint32 quest_id) const
12993 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12994 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12996 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12997 if( itr != mQuestStatus.end() )
12998 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13000 return false;
13003 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13005 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13006 if( qInfo )
13008 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13010 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13011 m_timedquests.erase(qInfo->GetQuestId());
13014 QuestStatusData& q_status = mQuestStatus[quest_id];
13016 q_status.m_status = status;
13017 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13020 UpdateForQuestWorldObjects();
13023 // not used in MaNGOS, but used in scripting code
13024 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13026 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13027 if( !qInfo )
13028 return 0;
13030 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13031 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13032 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13034 return 0;
13037 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13039 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13041 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13043 uint32 reqitemcount = pQuest->ReqItemCount[i];
13044 if( reqitemcount != 0 )
13046 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13048 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13049 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13055 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13057 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13058 if ( GetQuestSlotQuestId(i) == quest_id )
13059 return i;
13061 return MAX_QUEST_LOG_SIZE;
13064 void Player::AreaExploredOrEventHappens( uint32 questId )
13066 if( questId )
13068 uint16 log_slot = FindQuestSlot( questId );
13069 if( log_slot < MAX_QUEST_LOG_SIZE)
13071 QuestStatusData& q_status = mQuestStatus[questId];
13073 if(!q_status.m_explored)
13075 q_status.m_explored = true;
13076 if (q_status.uState != QUEST_NEW)
13077 q_status.uState = QUEST_CHANGED;
13080 if( CanCompleteQuest( questId ) )
13081 CompleteQuest( questId );
13085 //not used in mangosd, function for external script library
13086 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13088 if( Group *pGroup = GetGroup() )
13090 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13092 Player *pGroupGuy = itr->getSource();
13094 // for any leave or dead (with not released body) group member at appropriate distance
13095 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13096 pGroupGuy->AreaExploredOrEventHappens(questId);
13099 else
13100 AreaExploredOrEventHappens(questId);
13103 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13105 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13107 uint32 questid = GetQuestSlotQuestId(i);
13108 if ( questid == 0 )
13109 continue;
13111 QuestStatusData& q_status = mQuestStatus[questid];
13113 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13114 continue;
13116 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13117 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13118 continue;
13120 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13122 uint32 reqitem = qInfo->ReqItemId[j];
13123 if ( reqitem == entry )
13125 uint32 reqitemcount = qInfo->ReqItemCount[j];
13126 uint32 curitemcount = q_status.m_itemcount[j];
13127 if ( curitemcount < reqitemcount )
13129 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13130 q_status.m_itemcount[j] += additemcount;
13131 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13133 SendQuestUpdateAddItem( qInfo, j, additemcount );
13135 if ( CanCompleteQuest( questid ) )
13136 CompleteQuest( questid );
13137 return;
13141 UpdateForQuestWorldObjects();
13144 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13146 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13148 uint32 questid = GetQuestSlotQuestId(i);
13149 if(!questid)
13150 continue;
13151 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13152 if ( !qInfo )
13153 continue;
13154 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13155 continue;
13157 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13159 uint32 reqitem = qInfo->ReqItemId[j];
13160 if ( reqitem == entry )
13162 QuestStatusData& q_status = mQuestStatus[questid];
13164 uint32 reqitemcount = qInfo->ReqItemCount[j];
13165 uint32 curitemcount;
13166 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13167 curitemcount = q_status.m_itemcount[j];
13168 else
13169 curitemcount = GetItemCount(entry,true);
13170 if ( curitemcount < reqitemcount + count )
13172 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13173 q_status.m_itemcount[j] = curitemcount - remitemcount;
13174 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13176 IncompleteQuest( questid );
13178 return;
13182 UpdateForQuestWorldObjects();
13185 void Player::KilledMonster( uint32 entry, uint64 guid )
13187 uint32 addkillcount = 1;
13188 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13189 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13191 uint32 questid = GetQuestSlotQuestId(i);
13192 if(!questid)
13193 continue;
13195 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13196 if( !qInfo )
13197 continue;
13198 // just if !ingroup || !noraidgroup || raidgroup
13199 QuestStatusData& q_status = mQuestStatus[questid];
13200 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13202 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13204 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13206 // skip GO activate objective or none
13207 if(qInfo->ReqCreatureOrGOId[j] <=0)
13208 continue;
13210 // skip Cast at creature objective
13211 if(qInfo->ReqSpell[j] !=0 )
13212 continue;
13214 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13216 if ( reqkill == entry )
13218 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13219 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13220 if ( curkillcount < reqkillcount )
13222 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13223 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13225 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13227 if ( CanCompleteQuest( questid ) )
13228 CompleteQuest( questid );
13230 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13231 continue;
13239 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13241 bool isCreature = IS_CREATURE_GUID(guid);
13243 uint32 addCastCount = 1;
13244 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13246 uint32 questid = GetQuestSlotQuestId(i);
13247 if(!questid)
13248 continue;
13250 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13251 if ( !qInfo )
13252 continue;
13254 QuestStatusData& q_status = mQuestStatus[questid];
13256 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13258 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13260 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13262 // skip kill creature objective (0) or wrong spell casts
13263 if(qInfo->ReqSpell[j] != spell_id )
13264 continue;
13266 uint32 reqTarget = 0;
13268 if(isCreature)
13270 // creature activate objectives
13271 if(qInfo->ReqCreatureOrGOId[j] > 0)
13272 // checked at quest_template loading
13273 reqTarget = qInfo->ReqCreatureOrGOId[j];
13275 else
13277 // GO activate objective
13278 if(qInfo->ReqCreatureOrGOId[j] < 0)
13279 // checked at quest_template loading
13280 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13283 // other not this creature/GO related objectives
13284 if( reqTarget != entry )
13285 continue;
13287 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13288 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13289 if ( curCastCount < reqCastCount )
13291 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13292 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13294 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13297 if ( CanCompleteQuest( questid ) )
13298 CompleteQuest( questid );
13300 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13301 break;
13308 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13310 uint32 addTalkCount = 1;
13311 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13313 uint32 questid = GetQuestSlotQuestId(i);
13314 if(!questid)
13315 continue;
13317 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13318 if ( !qInfo )
13319 continue;
13321 QuestStatusData& q_status = mQuestStatus[questid];
13323 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13325 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13327 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13329 // skip spell casts and Gameobject objectives
13330 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13331 continue;
13333 uint32 reqTarget = 0;
13335 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13336 // checked at quest_template loading
13337 reqTarget = qInfo->ReqCreatureOrGOId[j];
13338 else
13339 continue;
13341 if ( reqTarget == entry )
13343 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13344 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13345 if ( curTalkCount < reqTalkCount )
13347 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13348 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13350 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13352 if ( CanCompleteQuest( questid ) )
13353 CompleteQuest( questid );
13355 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13356 continue;
13364 void Player::MoneyChanged( uint32 count )
13366 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13368 uint32 questid = GetQuestSlotQuestId(i);
13369 if (!questid)
13370 continue;
13372 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13373 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13375 QuestStatusData& q_status = mQuestStatus[questid];
13377 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13379 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13381 if ( CanCompleteQuest( questid ) )
13382 CompleteQuest( questid );
13385 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13387 if(int32(count) < -qInfo->GetRewOrReqMoney())
13388 IncompleteQuest( questid );
13394 void Player::ReputationChanged(FactionEntry const* factionEntry )
13396 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13398 if(uint32 questid = GetQuestSlotQuestId(i))
13400 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13402 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13404 QuestStatusData& q_status = mQuestStatus[questid];
13405 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13407 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13408 if ( CanCompleteQuest( questid ) )
13409 CompleteQuest( questid );
13411 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13413 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13414 IncompleteQuest( questid );
13422 bool Player::HasQuestForItem( uint32 itemid ) const
13424 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13426 uint32 questid = GetQuestSlotQuestId(i);
13427 if ( questid == 0 )
13428 continue;
13430 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13431 if(qs_itr == mQuestStatus.end())
13432 continue;
13434 QuestStatusData const& q_status = qs_itr->second;
13436 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13438 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13439 if(!qinfo)
13440 continue;
13442 // hide quest if player is in raid-group and quest is no raid quest
13443 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13444 continue;
13446 // There should be no mixed ReqItem/ReqSource drop
13447 // This part for ReqItem drop
13448 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13450 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13451 return true;
13453 // This part - for ReqSource
13454 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13456 // examined item is a source item
13457 if (qinfo->ReqSourceId[j] == itemid)
13459 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13461 // 'unique' item
13462 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13463 return true;
13465 // allows custom amount drop when not 0
13466 if (qinfo->ReqSourceCount[j])
13468 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13469 return true;
13470 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13471 return true;
13476 return false;
13479 void Player::SendQuestComplete( uint32 quest_id )
13481 if( quest_id )
13483 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13484 data << uint32(quest_id);
13485 GetSession()->SendPacket( &data );
13486 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13490 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13492 uint32 questid = pQuest->GetQuestId();
13493 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13494 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13495 data << uint32(questid);
13497 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13499 data << uint32(XP);
13500 data << uint32(pQuest->GetRewOrReqMoney());
13502 else
13504 data << uint32(0);
13505 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13508 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13509 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13510 GetSession()->SendPacket( &data );
13512 if (pQuest->GetQuestCompleteScript() != 0)
13513 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13516 void Player::SendQuestFailed( uint32 quest_id )
13518 if( quest_id )
13520 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13521 data << quest_id;
13522 data << uint32(0); // failed reason (4 for inventory is full)
13523 GetSession()->SendPacket( &data );
13524 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13528 void Player::SendQuestTimerFailed( uint32 quest_id )
13530 if( quest_id )
13532 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13533 data << quest_id;
13534 GetSession()->SendPacket( &data );
13535 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13539 void Player::SendCanTakeQuestResponse( uint32 msg )
13541 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13542 data << uint32(msg);
13543 GetSession()->SendPacket( &data );
13544 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13547 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13549 if( pPlayer )
13551 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13552 data << uint64(pPlayer->GetGUID());
13553 data << uint8(msg); // valid values: 0-8
13554 GetSession()->SendPacket( &data );
13555 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13559 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13561 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13562 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13563 //data << pQuest->ReqItemId[item_idx];
13564 //data << count;
13565 GetSession()->SendPacket( &data );
13568 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13570 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13572 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13573 if (entry < 0)
13574 // client expected gameobject template id in form (id|0x80000000)
13575 entry = (-entry) | 0x80000000;
13577 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13578 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13579 data << uint32(pQuest->GetQuestId());
13580 data << uint32(entry);
13581 data << uint32(old_count + add_count);
13582 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13583 data << uint64(guid);
13584 GetSession()->SendPacket(&data);
13586 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13587 if( log_slot < MAX_QUEST_LOG_SIZE)
13588 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13591 /*********************************************************/
13592 /*** LOAD SYSTEM ***/
13593 /*********************************************************/
13595 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13597 bool delete_result = true;
13598 if(!result)
13600 // 0 1 2 3 4 5 6 7 8 9
13601 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13602 if(!result) return false;
13604 else delete_result = false;
13606 Field *fields = result->Fetch();
13608 if(!LoadValues( fields[1].GetString()))
13610 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13611 if(delete_result) delete result;
13612 return false;
13615 // overwrite possible wrong/corrupted guid
13616 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13618 m_name = fields[2].GetCppString();
13620 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13621 SetMapId(fields[6].GetUInt32());
13622 // the instance id is not needed at character enum
13624 m_Played_time[0] = fields[7].GetUInt32();
13625 m_Played_time[1] = fields[8].GetUInt32();
13627 m_atLoginFlags = fields[9].GetUInt32();
13629 // I don't see these used anywhere ..
13630 /*_LoadGroup();
13632 _LoadBoundInstances();*/
13634 if (delete_result) delete result;
13636 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13637 m_items[i] = NULL;
13639 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13640 m_deathState = DEAD;
13642 return true;
13645 void Player::_LoadDeclinedNames(QueryResult* result)
13647 if(!result)
13648 return;
13650 if(m_declinedname)
13651 delete m_declinedname;
13653 m_declinedname = new DeclinedName;
13654 Field *fields = result->Fetch();
13655 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13656 m_declinedname->name[i] = fields[i].GetCppString();
13658 delete result;
13661 void Player::_LoadArenaTeamInfo(QueryResult *result)
13663 // arenateamid, played_week, played_season, personal_rating
13664 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13665 if (!result)
13666 return;
13670 Field *fields = result->Fetch();
13672 uint32 arenateamid = fields[0].GetUInt32();
13673 uint32 played_week = fields[1].GetUInt32();
13674 uint32 played_season = fields[2].GetUInt32();
13675 uint32 personal_rating = fields[3].GetUInt32();
13677 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13678 if(!aTeam)
13680 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13681 continue;
13683 uint8 arenaSlot = aTeam->GetSlot();
13685 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13686 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13687 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13688 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13689 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13690 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13692 }while (result->NextRow());
13693 delete result;
13696 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13698 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13699 if(!result)
13700 return false;
13702 Field *fields = result->Fetch();
13704 x = fields[0].GetFloat();
13705 y = fields[1].GetFloat();
13706 z = fields[2].GetFloat();
13707 o = fields[3].GetFloat();
13708 mapid = fields[4].GetUInt32();
13709 in_flight = !fields[5].GetCppString().empty();
13711 delete result;
13712 return true;
13715 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13717 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13718 if( !result )
13719 return false;
13721 Field *fields = result->Fetch();
13723 data = StrSplit(fields[0].GetCppString(), " ");
13725 delete result;
13727 return true;
13730 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13732 if(index >= data.size())
13733 return 0;
13735 return (uint32)atoi(data[index].c_str());
13738 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13740 float result;
13741 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13742 memcpy(&result, &temp, sizeof(result));
13744 return result;
13747 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13749 Tokens data;
13750 if(!LoadValuesArrayFromDB(data,guid))
13751 return 0;
13753 return GetUInt32ValueFromArray(data,index);
13756 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13758 float result;
13759 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13760 memcpy(&result, &temp, sizeof(result));
13762 return result;
13765 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13767 //// 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
13768 //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);
13769 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13771 if(!result)
13773 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13774 return false;
13777 Field *fields = result->Fetch();
13779 uint32 dbAccountId = fields[1].GetUInt32();
13781 // check if the character's account in the db and the logged in account match.
13782 // player should be able to load/delete character only with correct account!
13783 if( dbAccountId != GetSession()->GetAccountId() )
13785 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13786 delete result;
13787 return false;
13790 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13792 m_name = fields[3].GetCppString();
13794 // check name limitations
13795 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13797 delete result;
13798 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13799 return false;
13802 if(!LoadValues( fields[2].GetString()))
13804 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13805 delete result;
13806 return false;
13809 // overwrite possible wrong/corrupted guid
13810 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13812 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13813 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13815 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13816 SetVisibleItemSlot(slot,NULL);
13818 if (m_items[slot])
13820 delete m_items[slot];
13821 m_items[slot] = NULL;
13825 // update money limits
13826 if(GetMoney() > MAX_MONEY_AMOUNT)
13827 SetMoney(MAX_MONEY_AMOUNT);
13829 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13830 outDebugValues();
13832 m_race = fields[4].GetUInt8();
13833 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13834 //Other way is to saves m_team into characters table.
13835 setFactionForRace(m_race);
13836 SetCharm(NULL);
13838 m_class = fields[5].GetUInt8();
13840 // load home bind and check in same time class/race pair, it used later for restore broken positions
13841 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13842 return false;
13844 InitPrimaryProffesions(); // to max set before any spell loaded
13846 // init saved position, and fix it later if problematic
13847 uint32 transGUID = fields[24].GetUInt32();
13848 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13849 SetMapId(fields[9].GetUInt32());
13850 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13852 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13854 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13856 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13857 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13858 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13860 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13862 // check arena teams integrity
13863 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13865 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13866 if(!arena_team_id)
13867 continue;
13869 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13870 if(at->HaveMember(GetGUID()))
13871 continue;
13873 // arena team not exist or not member, cleanup fields
13874 for(int j =0; j < 6; ++j)
13875 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13878 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13880 if(!IsPositionValid())
13882 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13883 RelocateToHomebind();
13885 transGUID = 0;
13887 m_movementInfo.t_x = 0.0f;
13888 m_movementInfo.t_y = 0.0f;
13889 m_movementInfo.t_z = 0.0f;
13890 m_movementInfo.t_o = 0.0f;
13893 uint32 bgid = fields[34].GetUInt32();
13894 uint32 bgteam = fields[35].GetUInt32();
13896 if(bgid) //saved in BattleGround
13898 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13900 // check entry point and fix to homebind if need
13901 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13902 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13903 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13905 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13907 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13909 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13910 AddBattleGroundQueueId(bgQueueTypeId);
13912 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13913 SetBGTeam(bgteam);
13915 //join player to battleground group
13916 currentBg->EventPlayerLoggedIn(this, GetGUID());
13917 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13919 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13921 else
13923 Relocate(GetBattleGroundEntryPoint());
13924 //RemoveArenaAuras(true);
13927 else
13929 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13930 // if server restart after player save in BG or area
13931 // player can have current coordinates in to BG/Arean map, fix this
13932 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13934 // return to BG master
13935 SetMapId(fields[36].GetUInt32());
13936 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13938 // check entry point and fix to homebind if need
13939 mapEntry = sMapStore.LookupEntry(GetMapId());
13940 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13941 RelocateToHomebind();
13945 if (transGUID != 0)
13947 m_movementInfo.t_x = fields[20].GetFloat();
13948 m_movementInfo.t_y = fields[21].GetFloat();
13949 m_movementInfo.t_z = fields[22].GetFloat();
13950 m_movementInfo.t_o = fields[23].GetFloat();
13952 if( !MaNGOS::IsValidMapCoord(
13953 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13954 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13955 // transport size limited
13956 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13958 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13959 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13960 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13962 RelocateToHomebind();
13964 m_movementInfo.t_x = 0.0f;
13965 m_movementInfo.t_y = 0.0f;
13966 m_movementInfo.t_z = 0.0f;
13967 m_movementInfo.t_o = 0.0f;
13969 transGUID = 0;
13973 if (transGUID != 0)
13975 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13977 if( (*iter)->GetGUIDLow() == transGUID)
13979 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13980 // client without expansion support
13981 if(GetSession()->Expansion() < transMapEntry->Expansion())
13983 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13984 break;
13987 m_transport = *iter;
13988 m_transport->AddPassenger(this);
13989 SetMapId(m_transport->GetMapId());
13990 break;
13994 if(!m_transport)
13996 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13997 guid,transGUID);
13999 RelocateToHomebind();
14001 m_movementInfo.t_x = 0.0f;
14002 m_movementInfo.t_y = 0.0f;
14003 m_movementInfo.t_z = 0.0f;
14004 m_movementInfo.t_o = 0.0f;
14006 transGUID = 0;
14009 else // not transport case
14011 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14012 // client without expansion support
14013 if(GetSession()->Expansion() < mapEntry->Expansion())
14015 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14016 RelocateToHomebind();
14020 // NOW player must have valid map
14021 // load the player's map here if it's not already loaded
14022 Map *map = GetMap();
14024 // since the player may not be bound to the map yet, make sure subsequent
14025 // getmap calls won't create new maps
14026 SetInstanceId(map->GetInstanceId());
14028 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14029 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14031 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14032 if(at)
14033 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14034 else
14035 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());
14038 SaveRecallPosition();
14040 time_t now = time(NULL);
14041 time_t logoutTime = time_t(fields[16].GetUInt64());
14043 // since last logout (in seconds)
14044 uint64 time_diff = uint64(now - logoutTime);
14046 // set value, including drunk invisibility detection
14047 // calculate sobering. after 15 minutes logged out, the player will be sober again
14048 float soberFactor;
14049 if(time_diff > 15*MINUTE)
14050 soberFactor = 0;
14051 else
14052 soberFactor = 1-time_diff/(15.0f*MINUTE);
14053 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14054 SetDrunkValue(newDrunkenValue);
14056 m_rest_bonus = fields[15].GetFloat();
14057 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14058 float bubble0 = 0.031;
14059 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14060 float bubble1 = 0.125;
14062 if((int32)fields[16].GetUInt32() > 0)
14064 float bubble = fields[17].GetUInt32() > 0
14065 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14066 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14068 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14071 m_cinematic = fields[12].GetUInt32();
14072 m_Played_time[0]= fields[13].GetUInt32();
14073 m_Played_time[1]= fields[14].GetUInt32();
14075 m_resetTalentsCost = fields[18].GetUInt32();
14076 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14078 // reserve some flags
14079 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14081 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14082 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14084 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14086 uint32 extraflags = fields[25].GetUInt32();
14088 m_stableSlots = fields[26].GetUInt32();
14089 if(m_stableSlots > MAX_PET_STABLES)
14091 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14092 m_stableSlots = MAX_PET_STABLES;
14095 m_atLoginFlags = fields[27].GetUInt32();
14097 // Honor system
14098 // Update Honor kills data
14099 m_lastHonorUpdateTime = logoutTime;
14100 UpdateHonorFields();
14102 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14103 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14104 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14106 std::string taxi_nodes = fields[31].GetCppString();
14108 delete result;
14110 // clear channel spell data (if saved at channel spell casting)
14111 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14112 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14114 // clear charm/summon related fields
14115 SetCharm(NULL);
14116 SetPet(NULL);
14117 SetCharmerGUID(0);
14118 SetOwnerGUID(0);
14119 SetCreatorGUID(0);
14121 // reset some aura modifiers before aura apply
14122 SetFarSightGUID(0);
14123 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14124 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14126 _LoadSkills();
14128 // make sure the unit is considered out of combat for proper loading
14129 ClearInCombat();
14131 // make sure the unit is considered not in duel for proper loading
14132 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14133 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14135 // remember loaded power/health values to restore after stats initialization and modifier applying
14136 uint32 savedHealth = GetHealth();
14137 uint32 savedPower[MAX_POWERS];
14138 for(uint32 i = 0; i < MAX_POWERS; ++i)
14139 savedPower[i] = GetPower(Powers(i));
14141 // reset stats before loading any modifiers
14142 InitStatsForLevel();
14143 InitTaxiNodesForLevel();
14144 InitGlyphsForLevel();
14145 InitRunes();
14147 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14149 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14150 //_LoadMail();
14152 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14153 _LoadGlyphAuras();
14155 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14156 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14157 m_deathState = DEAD;
14159 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14161 // after spell load, learn rewarded spell if need also
14162 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14163 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14165 // after spell and quest load
14166 InitTalentForLevel();
14167 learnDefaultSpells();
14169 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14171 // must be before inventory (some items required reputation check)
14172 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14174 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14176 // update items with duration and realtime
14177 UpdateItemDuration(time_diff, true);
14179 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14181 // unread mails and next delivery time, actual mails not loaded
14182 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14184 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14186 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14187 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14188 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14190 if(!HasTitle(curTitle))
14191 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14194 // Not finish taxi flight path
14195 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14197 // problems with taxi path loading
14198 TaxiNodesEntry const* nodeEntry = NULL;
14199 if(uint32 node_id = m_taxi.GetTaxiSource())
14200 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14202 if(!nodeEntry) // don't know taxi start node, to homebind
14204 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14205 RelocateToHomebind();
14206 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14208 else // have start node, to it
14210 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14211 SetMapId(nodeEntry->map_id);
14212 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14213 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14215 m_taxi.ClearTaxiDestinations();
14217 else if(uint32 node_id = m_taxi.GetTaxiSource())
14219 // save source node as recall coord to prevent recall and fall from sky
14220 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14221 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14222 m_recallMap = nodeEntry->map_id;
14223 m_recallX = nodeEntry->x;
14224 m_recallY = nodeEntry->y;
14225 m_recallZ = nodeEntry->z;
14227 // flight will started later
14230 // has to be called after last Relocate() in Player::LoadFromDB
14231 SetFallInformation(0, GetPositionZ());
14233 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14235 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14236 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14237 if(!isAlive())
14238 RemoveAllAurasOnDeath();
14240 //apply all stat bonuses from items and auras
14241 SetCanModifyStats(true);
14242 UpdateAllStats();
14244 // restore remembered power/health values (but not more max values)
14245 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14246 for(uint32 i = 0; i < MAX_POWERS; ++i)
14247 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14249 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14250 outDebugValues();
14252 // GM state
14253 if(GetSession()->GetSecurity() > SEC_PLAYER)
14255 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14257 default:
14258 case 0: break; // disable
14259 case 1: SetGameMaster(true); break; // enable
14260 case 2: // save state
14261 if(extraflags & PLAYER_EXTRA_GM_ON)
14262 SetGameMaster(true);
14263 break;
14266 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14268 default:
14269 case 0: SetGMVisible(false); break; // invisible
14270 case 1: break; // visible
14271 case 2: // save state
14272 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14273 SetGMVisible(false);
14274 break;
14277 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14279 default:
14280 case 0: break; // disable
14281 case 1: SetAcceptTicket(true); break; // enable
14282 case 2: // save state
14283 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14284 SetAcceptTicket(true);
14285 break;
14288 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14290 default:
14291 case 0: break; // disable
14292 case 1: SetGMChat(true); break; // enable
14293 case 2: // save state
14294 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14295 SetGMChat(true);
14296 break;
14299 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14301 default:
14302 case 0: break; // disable
14303 case 1: SetAcceptWhispers(true); break; // enable
14304 case 2: // save state
14305 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14306 SetAcceptWhispers(true);
14307 break;
14311 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14313 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14314 m_achievementMgr.CheckAllAchievementCriteria();
14315 return true;
14318 bool Player::isAllowedToLoot(Creature* creature)
14320 if(Player* recipient = creature->GetLootRecipient())
14322 if (recipient == this)
14323 return true;
14324 if( Group* otherGroup = recipient->GetGroup())
14326 Group* thisGroup = GetGroup();
14327 if(!thisGroup)
14328 return false;
14329 return thisGroup == otherGroup;
14331 return false;
14333 else
14334 // prevent other players from looting if the recipient got disconnected
14335 return !creature->hasLootRecipient();
14338 void Player::_LoadActions(QueryResult *result)
14340 m_actionButtons.clear();
14342 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14344 if(result)
14348 Field *fields = result->Fetch();
14350 uint8 button = fields[0].GetUInt8();
14352 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14353 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14354 else
14356 sLog.outError( " ...at loading, and will deleted in DB also");
14358 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14359 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14362 while( result->NextRow() );
14364 delete result;
14368 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14370 m_Auras.clear();
14371 for (int i = 0; i < TOTAL_AURAS; ++i)
14372 m_modAuras[i].clear();
14374 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14376 if(result)
14380 Field *fields = result->Fetch();
14381 uint64 caster_guid = fields[0].GetUInt64();
14382 uint32 spellid = fields[1].GetUInt32();
14383 uint32 effindex = fields[2].GetUInt32();
14384 uint32 stackcount = fields[3].GetUInt32();
14385 int32 damage = (int32)fields[4].GetUInt32();
14386 int32 maxduration = (int32)fields[5].GetUInt32();
14387 int32 remaintime = (int32)fields[6].GetUInt32();
14388 int32 remaincharges = (int32)fields[7].GetUInt32();
14390 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14391 if(!spellproto)
14393 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14394 continue;
14397 if(effindex >= 3)
14399 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14400 continue;
14403 // negative effects should continue counting down after logout
14404 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14406 if(remaintime <= int32(timediff))
14407 continue;
14409 remaintime -= timediff;
14412 // prevent wrong values of remaincharges
14413 if(spellproto->procCharges)
14415 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14416 remaincharges = spellproto->procCharges;
14418 else
14419 remaincharges = 0;
14422 for(uint32 i=0; i<stackcount; ++i)
14424 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14425 if(!damage)
14426 damage = aura->GetModifier()->m_amount;
14428 // reset stolen single target auras
14429 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14430 aura->SetIsSingleTarget(false);
14432 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14433 AddAura(aura);
14434 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14437 while( result->NextRow() );
14439 delete result;
14442 if(m_class == CLASS_WARRIOR)
14443 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14446 void Player::_LoadGlyphAuras()
14448 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14450 if (uint32 glyph = GetGlyph(i))
14452 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14454 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14456 if(gp->TypeFlags == gs->TypeFlags)
14458 CastSpell(this, gp->SpellId, true);
14459 continue;
14461 else
14462 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14464 else
14465 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14467 else
14468 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14470 // On any error remove glyph
14471 SetGlyph(i, 0);
14476 void Player::LoadCorpse()
14478 if( isAlive() )
14480 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14482 else
14484 if(Corpse *corpse = GetCorpse())
14486 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14488 else
14490 //Prevent Dead Player login without corpse
14491 ResurrectPlayer(0.5f);
14496 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14498 //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());
14499 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14500 //NOTE: the "order by `bag`" is important because it makes sure
14501 //the bagMap is filled before items in the bags are loaded
14502 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14503 //expected to be equipped before offhand items (TODO: fixme)
14505 uint32 zone = GetZoneId();
14507 if (result)
14509 std::list<Item*> problematicItems;
14511 // prevent items from being added to the queue when stored
14512 m_itemUpdateQueueBlocked = true;
14515 Field *fields = result->Fetch();
14516 uint32 bag_guid = fields[1].GetUInt32();
14517 uint8 slot = fields[2].GetUInt8();
14518 uint32 item_guid = fields[3].GetUInt32();
14519 uint32 item_id = fields[4].GetUInt32();
14521 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14523 if(!proto)
14525 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14526 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14527 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14528 continue;
14531 Item *item = NewItemOrBag(proto);
14533 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14535 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14536 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14537 item->FSetState(ITEM_REMOVED);
14538 item->SaveToDB(); // it also deletes item object !
14539 continue;
14542 // not allow have in alive state item limited to another map/zone
14543 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14545 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14546 item->FSetState(ITEM_REMOVED);
14547 item->SaveToDB(); // it also deletes item object !
14548 continue;
14551 // "Conjured items disappear if you are logged out for more than 15 minutes"
14552 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14554 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14555 item->FSetState(ITEM_REMOVED);
14556 item->SaveToDB(); // it also deletes item object !
14557 continue;
14560 bool success = true;
14562 if (!bag_guid)
14564 // the item is not in a bag
14565 item->SetContainer( NULL );
14566 item->SetSlot(slot);
14568 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14570 ItemPosCountVec dest;
14571 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14572 item = StoreItem(dest, item, true);
14573 else
14574 success = false;
14576 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14578 uint16 dest;
14579 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14580 QuickEquipItem(dest, item);
14581 else
14582 success = false;
14584 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14586 ItemPosCountVec dest;
14587 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14588 item = BankItem(dest, item, true);
14589 else
14590 success = false;
14593 if(success)
14595 // store bags that may contain items in them
14596 if(item->IsBag() && IsBagPos(item->GetPos()))
14597 bagMap[item_guid] = (Bag*)item;
14600 else
14602 item->SetSlot(NULL_SLOT);
14603 // the item is in a bag, find the bag
14604 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14605 if(itr != bagMap.end())
14606 itr->second->StoreItem(slot, item, true );
14607 else
14608 success = false;
14611 // item's state may have changed after stored
14612 if (success)
14613 item->SetState(ITEM_UNCHANGED, this);
14614 else
14616 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);
14617 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14618 problematicItems.push_back(item);
14620 } while (result->NextRow());
14622 delete result;
14623 m_itemUpdateQueueBlocked = false;
14625 // send by mail problematic items
14626 while(!problematicItems.empty())
14628 // fill mail
14629 MailItemsInfo mi; // item list preparing
14631 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14633 Item* item = problematicItems.front();
14634 problematicItems.pop_front();
14636 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14639 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14641 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14644 //if(isAlive())
14645 _ApplyAllItemMods();
14648 // load mailed item which should receive current player
14649 void Player::_LoadMailedItems(Mail *mail)
14651 // data needs to be at first place for Item::LoadFromDB
14652 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);
14653 if(!result)
14654 return;
14658 Field *fields = result->Fetch();
14659 uint32 item_guid_low = fields[1].GetUInt32();
14660 uint32 item_template = fields[2].GetUInt32();
14662 mail->AddItem(item_guid_low, item_template);
14664 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14666 if(!proto)
14668 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);
14669 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14670 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14671 continue;
14674 Item *item = NewItemOrBag(proto);
14676 if(!item->LoadFromDB(item_guid_low, 0, result))
14678 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14679 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14680 item->FSetState(ITEM_REMOVED);
14681 item->SaveToDB(); // it also deletes item object !
14682 continue;
14685 AddMItem(item);
14686 } while (result->NextRow());
14688 delete result;
14691 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14693 //set a count of unread mails
14694 //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);
14695 if (resultUnread)
14697 Field *fieldMail = resultUnread->Fetch();
14698 unReadMails = fieldMail[0].GetUInt8();
14699 delete resultUnread;
14702 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14703 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14704 if (resultDelivery)
14706 Field *fieldMail = resultDelivery->Fetch();
14707 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14708 delete resultDelivery;
14712 void Player::_LoadMail()
14714 m_mail.clear();
14715 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14716 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());
14717 if(result)
14721 Field *fields = result->Fetch();
14722 Mail *m = new Mail;
14723 m->messageID = fields[0].GetUInt32();
14724 m->messageType = fields[1].GetUInt8();
14725 m->sender = fields[2].GetUInt32();
14726 m->receiver = fields[3].GetUInt32();
14727 m->subject = fields[4].GetCppString();
14728 m->itemTextId = fields[5].GetUInt32();
14729 bool has_items = fields[6].GetBool();
14730 m->expire_time = (time_t)fields[7].GetUInt64();
14731 m->deliver_time = (time_t)fields[8].GetUInt64();
14732 m->money = fields[9].GetUInt32();
14733 m->COD = fields[10].GetUInt32();
14734 m->checked = fields[11].GetUInt32();
14735 m->stationery = fields[12].GetUInt8();
14736 m->mailTemplateId = fields[13].GetInt16();
14738 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14740 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14741 m->mailTemplateId = 0;
14744 m->state = MAIL_STATE_UNCHANGED;
14746 if (has_items)
14747 _LoadMailedItems(m);
14749 m_mail.push_back(m);
14750 } while( result->NextRow() );
14751 delete result;
14753 m_mailsLoaded = true;
14756 void Player::LoadPet()
14758 //fixme: the pet should still be loaded if the player is not in world
14759 // just not added to the map
14760 if(IsInWorld())
14762 Pet *pet = new Pet;
14763 if(!pet->LoadPetFromDB(this,0,0,true))
14764 delete pet;
14768 void Player::_LoadQuestStatus(QueryResult *result)
14770 mQuestStatus.clear();
14772 uint32 slot = 0;
14774 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14775 //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());
14777 if(result)
14781 Field *fields = result->Fetch();
14783 uint32 quest_id = fields[0].GetUInt32();
14784 // used to be new, no delete?
14785 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14786 if( pQuest )
14788 // find or create
14789 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14791 uint32 qstatus = fields[1].GetUInt32();
14792 if(qstatus < MAX_QUEST_STATUS)
14793 questStatusData.m_status = QuestStatus(qstatus);
14794 else
14796 questStatusData.m_status = QUEST_STATUS_NONE;
14797 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14800 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14801 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14803 time_t quest_time = time_t(fields[4].GetUInt64());
14805 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14807 AddTimedQuest( quest_id );
14809 if (quest_time <= sWorld.GetGameTime())
14810 questStatusData.m_timer = 1;
14811 else
14812 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14814 else
14815 quest_time = 0;
14817 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14818 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14819 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14820 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14821 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14822 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14823 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14824 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14826 questStatusData.uState = QUEST_UNCHANGED;
14828 // add to quest log
14829 if( slot < MAX_QUEST_LOG_SIZE &&
14830 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14831 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14832 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14834 SetQuestSlot(slot,quest_id,quest_time);
14836 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14837 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14839 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14840 if(questStatusData.m_creatureOrGOcount[idx])
14841 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14843 ++slot;
14846 if(questStatusData.m_rewarded)
14848 // learn rewarded spell if unknown
14849 learnQuestRewardedSpells(pQuest);
14851 // set rewarded title if any
14852 if(pQuest->GetCharTitleId())
14854 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14855 SetTitle(titleEntry);
14858 if(pQuest->GetBonusTalents())
14859 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14862 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14865 while( result->NextRow() );
14867 delete result;
14870 // clear quest log tail
14871 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14872 SetQuestSlot(i,0);
14875 void Player::_LoadDailyQuestStatus(QueryResult *result)
14877 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14878 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14880 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14882 if(result)
14884 uint32 quest_daily_idx = 0;
14888 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14890 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14891 break;
14894 Field *fields = result->Fetch();
14896 uint32 quest_id = fields[0].GetUInt32();
14898 // save _any_ from daily quest times (it must be after last reset anyway)
14899 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14901 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14902 if( !pQuest )
14903 continue;
14905 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14906 ++quest_daily_idx;
14908 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14910 while( result->NextRow() );
14912 delete result;
14915 m_DailyQuestChanged = false;
14918 void Player::_LoadSpells(QueryResult *result)
14920 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14922 if(result)
14926 Field *fields = result->Fetch();
14928 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14930 while( result->NextRow() );
14932 delete result;
14936 void Player::_LoadTutorials(QueryResult *result)
14938 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14940 if(result)
14944 Field *fields = result->Fetch();
14946 for (int iI=0; iI<8; ++iI)
14947 m_Tutorials[iI] = fields[iI].GetUInt32();
14949 while( result->NextRow() );
14951 delete result;
14954 m_TutorialsChanged = false;
14957 void Player::_LoadGroup(QueryResult *result)
14959 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14960 if(result)
14962 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14963 delete result;
14964 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14965 if(group)
14967 uint8 subgroup = group->GetMemberGroup(GetGUID());
14968 SetGroup(group, subgroup);
14969 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14971 // the group leader may change the instance difficulty while the player is offline
14972 SetDifficulty(group->GetDifficulty());
14978 void Player::_LoadBoundInstances(QueryResult *result)
14980 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
14981 m_boundInstances[i].clear();
14983 Group *group = GetGroup();
14985 //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));
14986 if(result)
14990 Field *fields = result->Fetch();
14991 bool perm = fields[1].GetBool();
14992 uint32 mapId = fields[2].GetUInt32();
14993 uint32 instanceId = fields[0].GetUInt32();
14994 uint8 difficulty = fields[3].GetUInt8();
14995 time_t resetTime = (time_t)fields[4].GetUInt64();
14996 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14997 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14998 // and in that case it is not used
15000 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15001 if(!mapEntry || !mapEntry->IsDungeon())
15003 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15004 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15005 continue;
15008 if(!perm && group)
15010 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);
15011 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15012 continue;
15015 // since non permanent binds are always solo bind, they can always be reset
15016 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15017 if(save) BindToInstance(save, perm, true);
15018 } while(result->NextRow());
15019 delete result;
15023 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15025 // some instances only have one difficulty
15026 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15027 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15029 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15030 if(itr != m_boundInstances[difficulty].end())
15031 return &itr->second;
15032 else
15033 return NULL;
15036 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15038 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15039 UnbindInstance(itr, difficulty, unload);
15042 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15044 if(itr != m_boundInstances[difficulty].end())
15046 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15047 itr->second.save->RemovePlayer(this); // save can become invalid
15048 m_boundInstances[difficulty].erase(itr++);
15052 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15054 if(save)
15056 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15057 if(bind.save)
15059 // update the save when the group kills a boss
15060 if(permanent != bind.perm || save != bind.save)
15061 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());
15063 else
15064 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15066 if(bind.save != save)
15068 if(bind.save) bind.save->RemovePlayer(this);
15069 save->AddPlayer(this);
15072 if(permanent) save->SetCanReset(false);
15074 bind.save = save;
15075 bind.perm = permanent;
15076 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());
15077 return &bind;
15079 else
15080 return NULL;
15083 void Player::SendRaidInfo()
15085 uint32 counter = 0;
15087 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15089 size_t p_counter = data.wpos();
15090 data << uint32(counter); // placeholder
15092 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15094 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15096 if(itr->second.perm)
15098 InstanceSave *save = itr->second.save;
15099 data << uint32(save->GetMapId());
15100 data << uint32(save->GetResetTime() - time(NULL));
15101 data << uint32(save->GetInstanceId());
15102 data << uint32(save->GetDifficulty());
15103 ++counter;
15107 data.put<uint32>(p_counter,counter);
15108 GetSession()->SendPacket(&data);
15112 - called on every successful teleportation to a map
15114 void Player::SendSavedInstances()
15116 bool hasBeenSaved = false;
15117 WorldPacket data;
15119 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15121 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15123 if(itr->second.perm) // only permanent binds are sent
15125 hasBeenSaved = true;
15126 break;
15131 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15132 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15133 data << uint32(hasBeenSaved);
15134 GetSession()->SendPacket(&data);
15136 if(!hasBeenSaved)
15137 return;
15139 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15141 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15143 if(itr->second.perm)
15145 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15146 data << uint32(itr->second.save->GetMapId());
15147 GetSession()->SendPacket(&data);
15153 /// convert the player's binds to the group
15154 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15156 bool has_binds = false;
15157 bool has_solo = false;
15159 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15160 assert(player_guid);
15162 // copy all binds to the group, when changing leader it's assumed the character
15163 // will not have any solo binds
15165 if(player)
15167 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15169 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15171 has_binds = true;
15172 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15173 // permanent binds are not removed
15174 if(!itr->second.perm)
15176 player->UnbindInstance(itr, i, true); // increments itr
15177 has_solo = true;
15179 else
15180 ++itr;
15185 // if the player's not online we don't know what binds it has
15186 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));
15187 // the following should not get executed when changing leaders
15188 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15191 bool Player::_LoadHomeBind(QueryResult *result)
15193 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15194 if(!info)
15196 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15197 return false;
15200 bool ok = false;
15201 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15202 if (result)
15204 Field *fields = result->Fetch();
15205 m_homebindMapId = fields[0].GetUInt32();
15206 m_homebindZoneId = fields[1].GetUInt16();
15207 m_homebindX = fields[2].GetFloat();
15208 m_homebindY = fields[3].GetFloat();
15209 m_homebindZ = fields[4].GetFloat();
15210 delete result;
15212 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15214 // accept saved data only for valid position (and non instanceable), and accessable
15215 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15216 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15218 ok = true;
15220 else
15221 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15224 if(!ok)
15226 m_homebindMapId = info->mapId;
15227 m_homebindZoneId = info->zoneId;
15228 m_homebindX = info->positionX;
15229 m_homebindY = info->positionY;
15230 m_homebindZ = info->positionZ;
15232 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);
15235 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15236 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15238 return true;
15241 /*********************************************************/
15242 /*** SAVE SYSTEM ***/
15243 /*********************************************************/
15245 void Player::SaveToDB()
15247 // delay auto save at any saves (manual, in code, or autosave)
15248 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15250 // first save/honor gain after midnight will also update the player's honor fields
15251 UpdateHonorFields();
15253 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15254 //save, far from tavern/city
15255 //save, but in tavern/city
15256 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15257 outDebugValues();
15259 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15260 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15261 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15262 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15263 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15264 uint32 tmp_displayid = GetDisplayId();
15266 // Set player sit state to standing on save, also stealth and shifted form
15267 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15268 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15269 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15270 SetDisplayId(GetNativeDisplayId());
15272 bool inworld = IsInWorld();
15274 CharacterDatabase.BeginTransaction();
15276 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15278 std::string sql_name = m_name;
15279 CharacterDatabase.escape_string(sql_name);
15281 std::ostringstream ss;
15282 ss << "INSERT INTO characters (guid,account,name,race,class,"
15283 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15284 "taximask, online, cinematic, "
15285 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15286 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15287 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15288 << GetGUIDLow() << ", "
15289 << GetSession()->GetAccountId() << ", '"
15290 << sql_name << "', "
15291 << m_race << ", "
15292 << m_class << ", ";
15294 if(!IsBeingTeleported())
15296 ss << GetMapId() << ", "
15297 << (uint32)GetDifficulty() << ", "
15298 << finiteAlways(GetPositionX()) << ", "
15299 << finiteAlways(GetPositionY()) << ", "
15300 << finiteAlways(GetPositionZ()) << ", "
15301 << finiteAlways(GetOrientation()) << ", '";
15303 else
15305 ss << GetTeleportDest().mapid << ", "
15306 << (uint32)GetDifficulty() << ", "
15307 << finiteAlways(GetTeleportDest().x) << ", "
15308 << finiteAlways(GetTeleportDest().y) << ", "
15309 << finiteAlways(GetTeleportDest().z) << ", "
15310 << finiteAlways(GetTeleportDest().o) << ", '";
15313 uint16 i;
15314 for( i = 0; i < m_valuesCount; ++i )
15316 ss << GetUInt32Value(i) << " ";
15319 ss << "', ";
15321 ss << m_taxi; // string with TaxiMaskSize numbers
15323 ss << ", ";
15324 ss << (inworld ? 1 : 0);
15326 ss << ", ";
15327 ss << m_cinematic;
15329 ss << ", ";
15330 ss << m_Played_time[0];
15331 ss << ", ";
15332 ss << m_Played_time[1];
15334 ss << ", ";
15335 ss << finiteAlways(m_rest_bonus);
15336 ss << ", ";
15337 ss << (uint64)time(NULL);
15338 ss << ", ";
15339 ss << is_save_resting;
15340 ss << ", ";
15341 ss << m_resetTalentsCost;
15342 ss << ", ";
15343 ss << (uint64)m_resetTalentsTime;
15345 ss << ", ";
15346 ss << finiteAlways(m_movementInfo.t_x);
15347 ss << ", ";
15348 ss << finiteAlways(m_movementInfo.t_y);
15349 ss << ", ";
15350 ss << finiteAlways(m_movementInfo.t_z);
15351 ss << ", ";
15352 ss << finiteAlways(m_movementInfo.t_o);
15353 ss << ", ";
15354 if (m_transport)
15355 ss << m_transport->GetGUIDLow();
15356 else
15357 ss << "0";
15359 ss << ", ";
15360 ss << m_ExtraFlags;
15362 ss << ", ";
15363 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15365 ss << ", ";
15366 ss << uint32(m_atLoginFlags);
15368 ss << ", ";
15369 ss << GetZoneId();
15371 ss << ", ";
15372 ss << (uint64)m_deathExpireTime;
15374 ss << ", '";
15375 ss << m_taxi.SaveTaxiDestinationsToString();
15376 ss << "', '0', ";
15377 ss << GetBattleGroundId();
15378 ss << ", ";
15379 ss << GetBGTeam();
15380 ss << ", ";
15381 ss << m_bgEntryPoint.mapid << ", "
15382 << finiteAlways(m_bgEntryPoint.x) << ", "
15383 << finiteAlways(m_bgEntryPoint.y) << ", "
15384 << finiteAlways(m_bgEntryPoint.z) << ", "
15385 << finiteAlways(m_bgEntryPoint.o);
15386 ss << ")";
15388 CharacterDatabase.Execute( ss.str().c_str() );
15390 if(m_mailsUpdated) //save mails only when needed
15391 _SaveMail();
15393 _SaveInventory();
15394 _SaveQuestStatus();
15395 _SaveDailyQuestStatus();
15396 _SaveTutorials();
15397 _SaveSpells();
15398 _SaveSpellCooldowns();
15399 _SaveActions();
15400 _SaveAuras();
15401 m_achievementMgr.SaveToDB();
15402 m_reputationMgr.SaveToDB();
15404 CharacterDatabase.CommitTransaction();
15406 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15407 SetDisplayId(tmp_displayid);
15408 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15409 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15410 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15411 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15413 // save pet (hunter pet level and experience and all type pets health/mana).
15414 if(Pet* pet = GetPet())
15415 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15418 // fast save function for item/money cheating preventing - save only inventory and money state
15419 void Player::SaveInventoryAndGoldToDB()
15421 _SaveInventory();
15422 //money is in data field
15423 SaveDataFieldToDB();
15426 void Player::_SaveActions()
15428 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15430 switch (itr->second.uState)
15432 case ACTIONBUTTON_NEW:
15433 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15434 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15435 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15436 ++itr;
15437 break;
15438 case ACTIONBUTTON_CHANGED:
15439 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15440 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15441 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15442 ++itr;
15443 break;
15444 case ACTIONBUTTON_DELETED:
15445 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15446 m_actionButtons.erase(itr++);
15447 break;
15448 default:
15449 ++itr;
15450 break;
15455 void Player::_SaveAuras()
15457 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15459 AuraMap const& auras = GetAuras();
15461 if (auras.empty())
15462 return;
15464 spellEffectPair lastEffectPair = auras.begin()->first;
15465 uint32 stackCounter = 1;
15467 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15469 if(itr == auras.end() || lastEffectPair != itr->first)
15471 AuraMap::const_iterator itr2 = itr;
15472 // save previous spellEffectPair to db
15473 itr2--;
15475 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15477 //skip all auras from spells that are passive or need a shapeshift
15478 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15480 //do not save single target auras (unless they were cast by the player)
15481 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15483 uint8 i;
15484 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15485 for (i = 0; i < 3; ++i)
15486 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15487 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15488 break;
15490 if (i == 3)
15492 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15493 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15494 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()));
15499 if(itr == auras.end())
15500 break;
15503 if (lastEffectPair == itr->first)
15504 stackCounter++;
15505 else
15507 lastEffectPair = itr->first;
15508 stackCounter = 1;
15513 void Player::_SaveInventory()
15515 // force items in buyback slots to new state
15516 // and remove those that aren't already
15517 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15519 Item *item = m_items[i];
15520 if (!item || item->GetState() == ITEM_NEW) continue;
15521 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15522 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15523 m_items[i]->FSetState(ITEM_NEW);
15526 // update enchantment durations
15527 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15529 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15532 // if no changes
15533 if (m_itemUpdateQueue.empty()) return;
15535 // do not save if the update queue is corrupt
15536 bool error = false;
15537 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15539 Item *item = m_itemUpdateQueue[i];
15540 if(!item || item->GetState() == ITEM_REMOVED) continue;
15541 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15543 if (test == NULL)
15545 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());
15546 error = true;
15548 else if (test != item)
15550 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());
15551 error = true;
15555 if (error)
15557 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15558 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15559 return;
15562 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15564 Item *item = m_itemUpdateQueue[i];
15565 if(!item) continue;
15567 Bag *container = item->GetContainer();
15568 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15570 switch(item->GetState())
15572 case ITEM_NEW:
15573 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());
15574 break;
15575 case ITEM_CHANGED:
15576 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());
15577 break;
15578 case ITEM_REMOVED:
15579 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15580 break;
15581 case ITEM_UNCHANGED:
15582 break;
15585 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15587 m_itemUpdateQueue.clear();
15590 void Player::_SaveMail()
15592 if (!m_mailsLoaded)
15593 return;
15595 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15597 Mail *m = (*itr);
15598 if (m->state == MAIL_STATE_CHANGED)
15600 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'",
15601 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15602 if(m->removedItems.size())
15604 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15605 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15606 m->removedItems.clear();
15608 m->state = MAIL_STATE_UNCHANGED;
15610 else if (m->state == MAIL_STATE_DELETED)
15612 if (m->HasItems())
15613 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15614 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15615 if (m->itemTextId)
15616 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15617 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15618 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15622 //deallocate deleted mails...
15623 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15625 if ((*itr)->state == MAIL_STATE_DELETED)
15627 Mail* m = *itr;
15628 m_mail.erase(itr);
15629 delete m;
15630 itr = m_mail.begin();
15632 else
15633 ++itr;
15636 m_mailsUpdated = false;
15639 void Player::_SaveQuestStatus()
15641 // we don't need transactions here.
15642 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15644 switch (i->second.uState)
15646 case QUEST_NEW :
15647 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15648 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15649 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]);
15650 break;
15651 case QUEST_CHANGED :
15652 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' ",
15653 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 );
15654 break;
15655 case QUEST_UNCHANGED:
15656 break;
15658 i->second.uState = QUEST_UNCHANGED;
15662 void Player::_SaveDailyQuestStatus()
15664 if(!m_DailyQuestChanged)
15665 return;
15667 m_DailyQuestChanged = false;
15669 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15671 // we don't need transactions here.
15672 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15673 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15674 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15675 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15676 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15679 void Player::_SaveSpells()
15681 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15683 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15684 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15686 // add only changed/new not dependent spells
15687 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15688 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);
15690 if (itr->second->state == PLAYERSPELL_REMOVED)
15692 delete itr->second;
15693 m_spells.erase(itr++);
15695 else
15697 itr->second->state = PLAYERSPELL_UNCHANGED;
15698 ++itr;
15704 void Player::_SaveTutorials()
15706 if(!m_TutorialsChanged)
15707 return;
15709 uint32 Rows=0;
15710 // it's better than rebuilding indexes multiple times
15711 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15712 if(result)
15714 Rows = result->Fetch()[0].GetUInt32();
15715 delete result;
15718 if (Rows)
15720 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'",
15721 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 );
15723 else
15725 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]);
15728 m_TutorialsChanged = false;
15731 void Player::outDebugValues() const
15733 if(!sLog.IsOutDebug()) // optimize disabled debug output
15734 return;
15736 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15737 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15738 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15739 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15740 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15741 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15742 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15743 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15744 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15745 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15746 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15747 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15750 /*********************************************************/
15751 /*** FLOOD FILTER SYSTEM ***/
15752 /*********************************************************/
15754 void Player::UpdateSpeakTime()
15756 // ignore chat spam protection for GMs in any mode
15757 if(GetSession()->GetSecurity() > SEC_PLAYER)
15758 return;
15760 time_t current = time (NULL);
15761 if(m_speakTime > current)
15763 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15764 if(!max_count)
15765 return;
15767 ++m_speakCount;
15768 if(m_speakCount >= max_count)
15770 // prevent overwrite mute time, if message send just before mutes set, for example.
15771 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15772 if(GetSession()->m_muteTime < new_mute)
15773 GetSession()->m_muteTime = new_mute;
15775 m_speakCount = 0;
15778 else
15779 m_speakCount = 0;
15781 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15784 bool Player::CanSpeak() const
15786 return GetSession()->m_muteTime <= time (NULL);
15789 /*********************************************************/
15790 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15791 /*********************************************************/
15793 void Player::SendAttackSwingNotInRange()
15795 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15796 GetSession()->SendPacket( &data );
15799 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15801 std::ostringstream ss;
15802 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15803 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15804 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15805 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15806 sLog.outDebug(ss.str().c_str());
15807 CharacterDatabase.Execute(ss.str().c_str());
15810 void Player::SaveDataFieldToDB()
15812 std::ostringstream ss;
15813 ss<<"UPDATE characters SET data='";
15815 for(uint16 i = 0; i < m_valuesCount; ++i )
15817 ss << GetUInt32Value(i) << " ";
15819 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15821 CharacterDatabase.Execute(ss.str().c_str());
15824 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15826 std::ostringstream ss2;
15827 ss2<<"UPDATE characters SET data='";
15828 int i=0;
15829 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15831 ss2<<tokens[i]<<" ";
15833 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15835 return CharacterDatabase.Execute(ss2.str().c_str());
15838 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15840 char buf[11];
15841 snprintf(buf,11,"%u",value);
15843 if(index >= tokens.size())
15844 return;
15846 tokens[index] = buf;
15849 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15851 Tokens tokens;
15852 if(!LoadValuesArrayFromDB(tokens,guid))
15853 return;
15855 if(index >= tokens.size())
15856 return;
15858 char buf[11];
15859 snprintf(buf,11,"%u",value);
15860 tokens[index] = buf;
15862 SaveValuesArrayInDB(tokens,guid);
15865 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15867 uint32 temp;
15868 memcpy(&temp, &value, sizeof(value));
15869 Player::SetUInt32ValueInDB(index, temp, guid);
15872 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15874 Tokens tokens;
15875 if(!LoadValuesArrayFromDB(tokens, guid))
15876 return;
15878 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15879 uint8 race = unit_bytes0 & 0xFF;
15880 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15882 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15883 if(!info)
15884 return;
15886 unit_bytes0 &= ~(0xFF << 16);
15887 unit_bytes0 |= (gender << 16);
15888 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15890 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15891 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15893 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15895 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15896 player_bytes2 &= ~0xFF;
15897 player_bytes2 |= facialHair;
15898 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15900 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15901 player_bytes3 &= ~0xFF;
15902 player_bytes3 |= gender;
15903 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15905 SaveValuesArrayInDB(tokens, guid);
15908 void Player::SendAttackSwingNotStanding()
15910 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15911 GetSession()->SendPacket( &data );
15914 void Player::SendAttackSwingDeadTarget()
15916 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15917 GetSession()->SendPacket( &data );
15920 void Player::SendAttackSwingCantAttack()
15922 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15923 GetSession()->SendPacket( &data );
15926 void Player::SendAttackSwingCancelAttack()
15928 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15929 GetSession()->SendPacket( &data );
15932 void Player::SendAttackSwingBadFacingAttack()
15934 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15935 GetSession()->SendPacket( &data );
15938 void Player::SendAutoRepeatCancel()
15940 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15941 data.append(GetPackGUID()); // may be it's target guid
15942 GetSession()->SendPacket( &data );
15945 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15947 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15948 data << Area;
15949 data << Experience;
15950 GetSession()->SendPacket(&data);
15953 void Player::SendDungeonDifficulty(bool IsInGroup)
15955 uint8 val = 0x00000001;
15956 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15957 data << (uint32)GetDifficulty();
15958 data << uint32(val);
15959 data << uint32(IsInGroup);
15960 GetSession()->SendPacket(&data);
15963 void Player::SendResetFailedNotify(uint32 mapid)
15965 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15966 data << uint32(mapid);
15967 GetSession()->SendPacket(&data);
15970 /// Reset all solo instances and optionally send a message on success for each
15971 void Player::ResetInstances(uint8 method)
15973 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15975 // we assume that when the difficulty changes, all instances that can be reset will be
15976 uint8 dif = GetDifficulty();
15978 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15980 InstanceSave *p = itr->second.save;
15981 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15982 if(!entry || !p->CanReset())
15984 ++itr;
15985 continue;
15988 if(method == INSTANCE_RESET_ALL)
15990 // the "reset all instances" method can only reset normal maps
15991 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15993 ++itr;
15994 continue;
15998 // if the map is loaded, reset it
15999 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16000 if(map && map->IsDungeon())
16001 ((InstanceMap*)map)->Reset(method);
16003 // since this is a solo instance there should not be any players inside
16004 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16005 SendResetInstanceSuccess(p->GetMapId());
16007 p->DeleteFromDB();
16008 m_boundInstances[dif].erase(itr++);
16010 // the following should remove the instance save from the manager and delete it as well
16011 p->RemovePlayer(this);
16015 void Player::SendResetInstanceSuccess(uint32 MapId)
16017 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16018 data << MapId;
16019 GetSession()->SendPacket(&data);
16022 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16024 // TODO: find what other fail reasons there are besides players in the instance
16025 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16026 data << reason;
16027 data << MapId;
16028 GetSession()->SendPacket(&data);
16031 /*********************************************************/
16032 /*** Update timers ***/
16033 /*********************************************************/
16035 ///checks the 15 afk reports per 5 minutes limit
16036 void Player::UpdateAfkReport(time_t currTime)
16038 if(m_bgAfkReportedTimer <= currTime)
16040 m_bgAfkReportedCount = 0;
16041 m_bgAfkReportedTimer = currTime+5*MINUTE;
16045 void Player::UpdateContestedPvP(uint32 diff)
16047 if(!m_contestedPvPTimer||isInCombat())
16048 return;
16049 if(m_contestedPvPTimer <= diff)
16051 ResetContestedPvP();
16053 else
16054 m_contestedPvPTimer -= diff;
16057 void Player::UpdatePvPFlag(time_t currTime)
16059 if(!IsPvP())
16060 return;
16061 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16062 return;
16064 UpdatePvP(false);
16067 void Player::UpdateDuelFlag(time_t currTime)
16069 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16070 return;
16072 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16073 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16075 duel->startTimer = 0;
16076 duel->startTime = currTime;
16077 duel->opponent->duel->startTimer = 0;
16078 duel->opponent->duel->startTime = currTime;
16081 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16083 if(!pet)
16084 pet = GetPet();
16086 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16088 //returning of reagents only for players, so best done here
16089 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16090 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16092 if(spellInfo)
16094 for(uint32 i = 0; i < 7; ++i)
16096 if(spellInfo->Reagent[i] > 0)
16098 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16099 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16100 if( msg == EQUIP_ERR_OK )
16102 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16103 if(IsInWorld())
16104 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16109 m_temporaryUnsummonedPetNumber = 0;
16112 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16113 return;
16115 // only if current pet in slot
16116 switch(pet->getPetType())
16118 case MINI_PET:
16119 m_miniPet = 0;
16120 break;
16121 case GUARDIAN_PET:
16122 m_guardianPets.erase(pet->GetGUID());
16123 break;
16124 default:
16125 if(GetPetGUID() == pet->GetGUID())
16126 SetPet(NULL);
16127 break;
16130 pet->CombatStop();
16132 if(returnreagent)
16134 switch(pet->GetEntry())
16136 //warlock pets except imp are removed(?) when logging out
16137 case 1860:
16138 case 1863:
16139 case 417:
16140 case 17252:
16141 mode = PET_SAVE_NOT_IN_SLOT;
16142 break;
16146 pet->SavePetToDB(mode);
16148 pet->CleanupsBeforeDelete();
16149 pet->AddObjectToRemoveList();
16150 pet->m_removed = true;
16152 if(pet->isControlled())
16154 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16155 data << uint64(0);
16156 data << uint32(0);
16157 GetSession()->SendPacket(&data);
16159 if(GetGroup())
16160 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16164 void Player::RemoveMiniPet()
16166 if(Pet* pet = GetMiniPet())
16168 pet->Remove(PET_SAVE_AS_DELETED);
16169 m_miniPet = 0;
16173 Pet* Player::GetMiniPet()
16175 if(!m_miniPet)
16176 return NULL;
16177 return ObjectAccessor::GetPet(m_miniPet);
16180 void Player::RemoveGuardians()
16182 while(!m_guardianPets.empty())
16184 uint64 guid = *m_guardianPets.begin();
16185 if(Pet* pet = ObjectAccessor::GetPet(guid))
16186 pet->Remove(PET_SAVE_AS_DELETED);
16188 m_guardianPets.erase(guid);
16192 bool Player::HasGuardianWithEntry(uint32 entry)
16194 // pet guid middle part is entry (and creature also)
16195 // and in guardian list must be guardians with same entry _always_
16196 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16198 if(Pet* pet = ObjectAccessor::GetPet(*itr))
16199 if (Pet->GetEntry() == entry)
16200 return true;
16203 return false;
16206 void Player::Uncharm()
16208 Unit* charm = GetCharm();
16209 if(!charm)
16210 return;
16212 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16213 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16216 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16218 *data << (uint8)msgtype;
16219 *data << (uint32)language;
16220 *data << (uint64)GetGUID();
16221 *data << (uint32)language; //language 2.1.0 ?
16222 *data << (uint64)GetGUID();
16223 *data << (uint32)(text.length()+1);
16224 *data << text;
16225 *data << (uint8)chatTag();
16228 void Player::Say(const std::string& text, const uint32 language)
16230 WorldPacket data(SMSG_MESSAGECHAT, 200);
16231 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16232 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16235 void Player::Yell(const std::string& text, const uint32 language)
16237 WorldPacket data(SMSG_MESSAGECHAT, 200);
16238 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16239 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16242 void Player::TextEmote(const std::string& text)
16244 WorldPacket data(SMSG_MESSAGECHAT, 200);
16245 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16246 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16249 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16251 if (language != LANG_ADDON) // if not addon data
16252 language = LANG_UNIVERSAL; // whispers should always be readable
16254 Player *rPlayer = objmgr.GetPlayer(receiver);
16256 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16257 if(!rPlayer->isDND() || isGameMaster())
16259 WorldPacket data(SMSG_MESSAGECHAT, 200);
16260 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16261 rPlayer->GetSession()->SendPacket(&data);
16263 data.Initialize(SMSG_MESSAGECHAT, 200);
16264 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16265 GetSession()->SendPacket(&data);
16267 else
16269 // announce to player that player he is whispering to is dnd and cannot receive his message
16270 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16273 if(!isAcceptWhispers())
16275 SetAcceptWhispers(true);
16276 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16279 // announce to player that player he is whispering to is afk
16280 if(rPlayer->isAFK())
16281 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16283 // if player whisper someone, auto turn of dnd to be able to receive an answer
16284 if(isDND() && !rPlayer->isGameMaster())
16285 ToggleDND();
16288 void Player::PetSpellInitialize()
16290 Pet* pet = GetPet();
16292 if(!pet)
16293 return;
16295 sLog.outDebug("Pet Spells Groups");
16297 CharmInfo *charmInfo = pet->GetCharmInfo();
16299 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16300 data << uint64(pet->GetGUID());
16301 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16302 data << uint32(0);
16303 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16305 // action bar loop
16306 for(uint32 i = 0; i < 10; ++i)
16308 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16311 size_t spellsCountPos = data.wpos();
16313 // spells count
16314 uint8 addlist = 0;
16315 data << uint8(addlist); // placeholder
16317 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16319 // spells loop
16320 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16322 if(itr->second->state == PETSPELL_REMOVED)
16323 continue;
16325 data << uint16(itr->first);
16326 data << uint16(itr->second->active); // pet spell active state isn't boolean
16327 ++addlist;
16331 data.put<uint8>(spellsCountPos, addlist);
16333 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16334 data << uint8(cooldownsCount);
16336 time_t curTime = time(NULL);
16338 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16340 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16342 data << uint16(itr->first); // spellid
16343 data << uint16(0); // spell category?
16344 data << uint32(cooldown); // cooldown
16345 data << uint32(0); // category cooldown
16348 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16350 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16352 data << uint16(itr->first); // spellid
16353 data << uint16(0); // spell category?
16354 data << uint32(0); // cooldown
16355 data << uint32(cooldown); // category cooldown
16358 GetSession()->SendPacket(&data);
16361 void Player::PossessSpellInitialize()
16363 Unit* charm = GetCharm();
16365 if(!charm)
16366 return;
16368 CharmInfo *charmInfo = charm->GetCharmInfo();
16370 if(!charmInfo)
16372 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16373 return;
16376 uint8 addlist = 0;
16377 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16379 //16
16380 data << uint64(charm->GetGUID());
16381 data << uint32(0x00000000);
16382 data << uint32(0);
16383 data << uint32(0);
16385 for(uint32 i = 0; i < 10; ++i) //40
16387 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16390 data << uint8(addlist); //1
16392 uint8 count = 0;
16393 data << uint8(count); // cooldowns count
16395 GetSession()->SendPacket(&data);
16398 void Player::CharmSpellInitialize()
16400 Unit* charm = GetCharm();
16402 if(!charm)
16403 return;
16405 CharmInfo *charmInfo = charm->GetCharmInfo();
16406 if(!charmInfo)
16408 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16409 return;
16412 uint8 addlist = 0;
16414 if(charm->GetTypeId() != TYPEID_PLAYER)
16416 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16418 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16420 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16422 if(charmInfo->GetCharmSpell(i)->spellId)
16423 ++addlist;
16428 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16430 data << uint64(charm->GetGUID());
16431 data << uint32(0x00000000);
16432 data << uint32(0);
16433 if(charm->GetTypeId() != TYPEID_PLAYER)
16434 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16435 else
16436 data << uint8(0) << uint8(0);
16437 data << uint16(0);
16439 for(uint32 i = 0; i < 10; ++i) //40
16441 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16444 data << uint8(addlist); //1
16446 if(addlist)
16448 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16450 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16451 if(cspell->spellId)
16453 data << uint16(cspell->spellId);
16454 data << uint16(cspell->active);
16459 uint8 count = 0;
16460 data << uint8(count); // cooldowns count
16462 GetSession()->SendPacket(&data);
16465 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16467 if (!mod || !spellInfo)
16468 return false;
16470 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16472 // prevent apply to any spell except spell that trigger expire
16473 if(spell)
16475 if(mod->lastAffected != spell)
16476 return false;
16478 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16479 return false;
16482 return spellmgr.IsAffectedByMod(spellInfo, mod);
16485 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16487 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16489 for(int eff=0;eff<96;++eff)
16491 uint64 _mask = 0;
16492 uint64 _mask2= 0;
16493 if (eff<64) _mask = uint64(1) << (eff- 0);
16494 else _mask2= uint64(1) << (eff-64);
16495 if ( mod->mask & _mask || mod->mask2 & _mask2)
16497 int32 val = 0;
16498 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16500 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16501 val += (*itr)->value;
16503 val += apply ? mod->value : -(mod->value);
16504 WorldPacket data(Opcode, (1+1+4));
16505 data << uint8(eff);
16506 data << uint8(mod->op);
16507 data << int32(val);
16508 SendDirectMessage(&data);
16512 if (apply)
16513 m_spellMods[mod->op].push_back(mod);
16514 else
16516 if (mod->charges == -1)
16517 --m_SpellModRemoveCount;
16518 m_spellMods[mod->op].remove(mod);
16519 delete mod;
16523 void Player::RemoveSpellMods(Spell const* spell)
16525 if(!spell || (m_SpellModRemoveCount == 0))
16526 return;
16528 for(int i=0;i<MAX_SPELLMOD;++i)
16530 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16532 SpellModifier *mod = *itr;
16533 ++itr;
16535 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16537 RemoveAurasDueToSpell(mod->spellId);
16538 if (m_spellMods[i].empty())
16539 break;
16540 else
16541 itr = m_spellMods[i].begin();
16547 // send Proficiency
16548 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16550 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16551 data << pr1 << pr2;
16552 GetSession()->SendPacket (&data);
16555 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16557 QueryResult *result = NULL;
16558 if(type==10)
16559 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16560 else
16561 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16562 if(result)
16564 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.
16565 { // and SendPetitionQueryOpcode reads data from the DB
16566 Field *fields = result->Fetch();
16567 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16568 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16570 // send update if charter owner in game
16571 Player* owner = objmgr.GetPlayer(ownerguid);
16572 if(owner)
16573 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16575 } while ( result->NextRow() );
16577 delete result;
16579 if(type==10)
16580 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16581 else
16582 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16585 CharacterDatabase.BeginTransaction();
16586 if(type == 10)
16588 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16589 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16591 else
16593 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16594 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16596 CharacterDatabase.CommitTransaction();
16599 void Player::LeaveAllArenaTeams(uint64 guid)
16601 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));
16602 if(!result)
16603 return;
16607 Field *fields = result->Fetch();
16608 uint32 at_id = fields[0].GetUInt32();
16609 if(at_id != 0)
16611 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16612 if(at)
16613 at->DelMember(guid);
16615 } while (result->NextRow());
16617 delete result;
16620 void Player::SetRestBonus (float rest_bonus_new)
16622 // Prevent resting on max level
16623 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16624 rest_bonus_new = 0;
16626 if(rest_bonus_new < 0)
16627 rest_bonus_new = 0;
16629 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16631 if(rest_bonus_new > rest_bonus_max)
16632 m_rest_bonus = rest_bonus_max;
16633 else
16634 m_rest_bonus = rest_bonus_new;
16636 // update data for client
16637 if(m_rest_bonus>10)
16638 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16639 else if(m_rest_bonus<=1)
16640 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16642 //RestTickUpdate
16643 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16646 void Player::HandleStealthedUnitsDetection()
16648 std::list<Unit*> stealthedUnits;
16650 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16651 Cell cell(p);
16652 cell.data.Part.reserved = ALL_DISTRICT;
16653 cell.SetNoCreate();
16655 MaNGOS::AnyStealthedCheck u_check;
16656 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16658 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16659 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16661 CellLock<GridReadGuard> cell_lock(cell, p);
16662 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16663 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16665 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16667 if((*i)==this)
16669 i = stealthedUnits.erase(i);
16670 continue;
16673 if ((*i)->isVisibleForOrDetect(this,true))
16676 (*i)->SendUpdateToPlayer(this);
16677 m_clientGUIDs.insert((*i)->GetGUID());
16679 #ifdef MANGOS_DEBUG
16680 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16681 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16682 #endif
16684 // target aura duration for caster show only if target exist at caster client
16685 // send data at target visibility change (adding to client)
16686 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16687 SendAurasForTarget(*i);
16689 i = stealthedUnits.erase(i);
16690 continue;
16693 ++i;
16697 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16699 if(nodes.size() < 2)
16700 return false;
16702 // not let cheating with start flight mounted
16703 if(IsMounted())
16705 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16706 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16707 GetSession()->SendPacket(&data);
16708 return false;
16711 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16713 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16714 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16715 GetSession()->SendPacket(&data);
16716 return false;
16719 // 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
16720 if(GetSession()->isLogingOut() ||
16721 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16722 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16723 IsNonMeleeSpellCasted(false) ||
16724 isInCombat())
16726 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16727 data << uint32(ERR_TAXIPLAYERBUSY);
16728 GetSession()->SendPacket(&data);
16729 return false;
16732 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16733 return false;
16735 uint32 sourcenode = nodes[0];
16737 // starting node too far away (cheat?)
16738 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16739 if( !node || node->map_id != GetMapId() ||
16740 (node->x - GetPositionX())*(node->x - GetPositionX())+
16741 (node->y - GetPositionY())*(node->y - GetPositionY())+
16742 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16743 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16745 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16746 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16747 GetSession()->SendPacket(&data);
16748 return false;
16751 // Prepare to flight start now
16753 // stop combat at start taxi flight if any
16754 CombatStop();
16756 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16757 TradeCancel(true);
16759 // clean not finished taxi path if any
16760 m_taxi.ClearTaxiDestinations();
16762 // 0 element current node
16763 m_taxi.AddTaxiDestination(sourcenode);
16765 // fill destinations path tail
16766 uint32 sourcepath = 0;
16767 uint32 totalcost = 0;
16769 uint32 prevnode = sourcenode;
16770 uint32 lastnode = 0;
16772 for(uint32 i = 1; i < nodes.size(); ++i)
16774 uint32 path, cost;
16776 lastnode = nodes[i];
16777 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16779 if(!path)
16781 m_taxi.ClearTaxiDestinations();
16782 return false;
16785 totalcost += cost;
16787 if(prevnode == sourcenode)
16788 sourcepath = path;
16790 m_taxi.AddTaxiDestination(lastnode);
16792 prevnode = lastnode;
16795 if(!mount_id) // if not provide then attempt use default.
16796 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16798 if (mount_id == 0 || sourcepath == 0)
16800 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16801 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16802 GetSession()->SendPacket(&data);
16803 m_taxi.ClearTaxiDestinations();
16804 return false;
16807 uint32 money = GetMoney();
16809 if(npc)
16811 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16814 if(money < totalcost)
16816 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16817 data << uint32(ERR_TAXINOTENOUGHMONEY);
16818 GetSession()->SendPacket(&data);
16819 m_taxi.ClearTaxiDestinations();
16820 return false;
16823 //Checks and preparations done, DO FLIGHT
16824 ModifyMoney(-(int32)totalcost);
16825 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16826 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16828 // prevent stealth flight
16829 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16831 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16832 data << uint32(ERR_TAXIOK);
16833 GetSession()->SendPacket(&data);
16835 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16837 GetSession()->SendDoFlight(mount_id, sourcepath);
16839 return true;
16842 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16844 // last check 2.0.10
16845 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16846 data << GetGUID();
16847 data << uint8(0x0); // flags (0x1, 0x2)
16848 time_t curTime = time(NULL);
16849 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16851 if (itr->second->state == PLAYERSPELL_REMOVED)
16852 continue;
16853 uint32 unSpellId = itr->first;
16854 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16855 if (!spellInfo)
16857 ASSERT(spellInfo);
16858 continue;
16861 // Not send cooldown for this spells
16862 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16863 continue;
16865 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16867 data << unSpellId;
16868 data << unTimeMs; // in m.secs
16869 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16872 GetSession()->SendPacket(&data);
16875 void Player::InitDataForForm(bool reapplyMods)
16877 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16878 if(ssEntry && ssEntry->attackSpeed)
16880 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16881 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16882 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16884 else
16885 SetRegularAttackTime();
16887 switch(m_form)
16889 case FORM_CAT:
16891 if(getPowerType()!=POWER_ENERGY)
16892 setPowerType(POWER_ENERGY);
16893 break;
16895 case FORM_BEAR:
16896 case FORM_DIREBEAR:
16898 if(getPowerType()!=POWER_RAGE)
16899 setPowerType(POWER_RAGE);
16900 break;
16902 default: // 0, for example
16904 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16905 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16906 setPowerType(Powers(cEntry->powerType));
16907 break;
16911 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16912 if (!reapplyMods)
16913 UpdateEquipSpellsAtFormChange();
16915 UpdateAttackPowerAndDamage();
16916 UpdateAttackPowerAndDamage(true);
16919 // Return true is the bought item has a max count to force refresh of window by caller
16920 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16922 // cheating attempt
16923 if(count < 1) count = 1;
16925 if(!isAlive())
16926 return false;
16928 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16929 if( !pProto )
16931 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16932 return false;
16935 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
16936 if (!pCreature)
16938 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16939 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16940 return false;
16943 VendorItemData const* vItems = pCreature->GetVendorItems();
16944 if(!vItems || vItems->Empty())
16946 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16947 return false;
16950 size_t vendor_slot = vItems->FindItemSlot(item);
16951 if(vendor_slot >= vItems->GetItemCount())
16953 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16954 return false;
16957 VendorItem const* crItem = vItems->m_items[vendor_slot];
16959 // check current item amount if it limited
16960 if( crItem->maxcount != 0 )
16962 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16964 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16965 return false;
16969 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16971 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16972 return false;
16975 if(crItem->ExtendedCost)
16977 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16978 if(!iece)
16980 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16981 return false;
16984 // honor points price
16985 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16987 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16988 return false;
16991 // arena points price
16992 if(GetArenaPoints() < (iece->reqarenapoints * count))
16994 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16995 return false;
16998 // item base price
16999 for (uint8 i = 0; i < 5; ++i)
17001 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17003 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17004 return false;
17008 // check for personal arena rating requirement
17009 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17011 // probably not the proper equip err
17012 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17013 return false;
17017 uint32 price = pProto->BuyPrice * count;
17019 // reputation discount
17020 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17022 if( GetMoney() < price )
17024 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17025 return false;
17028 uint8 bag = 0; // init for case invalid bagGUID
17030 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17032 Bag *pBag;
17033 if( bagguid == GetGUID() )
17035 bag = INVENTORY_SLOT_BAG_0;
17037 else
17039 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17041 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17042 if( pBag )
17044 if( bagguid == pBag->GetGUID() )
17046 bag = i;
17047 break;
17054 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17056 ItemPosCountVec dest;
17057 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17058 if( msg != EQUIP_ERR_OK )
17060 SendEquipError( msg, NULL, NULL );
17061 return false;
17064 ModifyMoney( -(int32)price );
17065 if(crItem->ExtendedCost) // case for new honor system
17067 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17068 if(iece->reqhonorpoints)
17069 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17070 if(iece->reqarenapoints)
17071 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17072 for (uint8 i = 0; i < 5; ++i)
17074 if(iece->reqitem[i])
17075 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17079 if(Item *it = StoreNewItem( dest, item, true ))
17081 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17083 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17084 data << pCreature->GetGUID();
17085 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17086 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17087 data << (uint32)count;
17088 GetSession()->SendPacket(&data);
17090 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17093 else if( IsEquipmentPos( bag, slot ) )
17095 if(pProto->BuyCount * count != 1)
17097 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17098 return false;
17101 uint16 dest;
17102 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17103 if( msg != EQUIP_ERR_OK )
17105 SendEquipError( msg, NULL, NULL );
17106 return false;
17109 ModifyMoney( -(int32)price );
17110 if(crItem->ExtendedCost) // case for new honor system
17112 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17113 if(iece->reqhonorpoints)
17114 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17115 if(iece->reqarenapoints)
17116 ModifyArenaPoints( - int32(iece->reqarenapoints));
17117 for (uint8 i = 0; i < 5; ++i)
17119 if(iece->reqitem[i])
17120 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17124 if(Item *it = EquipNewItem( dest, item, true ))
17126 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17128 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17129 data << pCreature->GetGUID();
17130 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17131 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17132 data << (uint32)count;
17133 GetSession()->SendPacket(&data);
17135 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17137 AutoUnequipOffhandIfNeed();
17140 else
17142 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17143 return false;
17146 return crItem->maxcount!=0;
17149 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17151 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17152 // the personal rating of the arena team must match the required limit as well
17153 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17154 uint32 max_personal_rating = 0;
17155 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17157 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17159 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17160 uint32 t_rating = at->GetRating();
17161 p_rating = p_rating<t_rating? p_rating : t_rating;
17162 if(max_personal_rating < p_rating)
17163 max_personal_rating = p_rating;
17166 return max_personal_rating;
17169 void Player::UpdateHomebindTime(uint32 time)
17171 // GMs never get homebind timer online
17172 if (m_InstanceValid || isGameMaster())
17174 if(m_HomebindTimer) // instance valid, but timer not reset
17176 // hide reminder
17177 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17178 data << uint32(0);
17179 data << uint32(0);
17180 GetSession()->SendPacket(&data);
17182 // instance is valid, reset homebind timer
17183 m_HomebindTimer = 0;
17185 else if (m_HomebindTimer > 0)
17187 if (time >= m_HomebindTimer)
17189 // teleport to homebind location
17190 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17192 else
17193 m_HomebindTimer -= time;
17195 else
17197 // instance is invalid, start homebind timer
17198 m_HomebindTimer = 60000;
17199 // send message to player
17200 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17201 data << m_HomebindTimer;
17202 data << uint32(1);
17203 GetSession()->SendPacket(&data);
17204 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17208 void Player::UpdatePvP(bool state, bool ovrride)
17210 if(!state || ovrride)
17212 SetPvP(state);
17213 if(Pet* pet = GetPet())
17214 pet->SetPvP(state);
17215 if(Unit* charmed = GetCharm())
17216 charmed->SetPvP(state);
17218 pvpInfo.endTimer = 0;
17220 else
17222 if(pvpInfo.endTimer != 0)
17223 pvpInfo.endTimer = time(NULL);
17224 else
17226 SetPvP(state);
17228 if(Pet* pet = GetPet())
17229 pet->SetPvP(state);
17230 if(Unit* charmed = GetCharm())
17231 charmed->SetPvP(state);
17236 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17238 // init cooldown values
17239 uint32 cat = 0;
17240 int32 rec = -1;
17241 int32 catrec = -1;
17243 // some special item spells without correct cooldown in SpellInfo
17244 // cooldown information stored in item prototype
17245 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17247 if(itemId)
17249 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17251 for(int idx = 0; idx < 5; ++idx)
17253 if(proto->Spells[idx].SpellId == spellInfo->Id)
17255 cat = proto->Spells[idx].SpellCategory;
17256 rec = proto->Spells[idx].SpellCooldown;
17257 catrec = proto->Spells[idx].SpellCategoryCooldown;
17258 break;
17264 // if no cooldown found above then base at DBC data
17265 if(rec < 0 && catrec < 0)
17267 cat = spellInfo->Category;
17268 rec = spellInfo->RecoveryTime;
17269 catrec = spellInfo->CategoryRecoveryTime;
17272 time_t curTime = time(NULL);
17274 time_t catrecTime;
17275 time_t recTime;
17277 // overwrite time for selected category
17278 if(infinityCooldown)
17280 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17281 // but not allow ignore until reset or re-login
17282 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17283 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17285 else
17287 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17288 // prevent 0 cooldowns set by another way
17289 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17290 rec = GetAttackTime(RANGED_ATTACK);
17292 // Now we have cooldown data (if found any), time to apply mods
17293 if(rec > 0)
17294 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17296 if(catrec > 0)
17297 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17299 // replace negative cooldowns by 0
17300 if (rec < 0) rec = 0;
17301 if (catrec < 0) catrec = 0;
17303 // no cooldown after applying spell mods
17304 if( rec == 0 && catrec == 0)
17305 return;
17307 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17308 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17311 // self spell cooldown
17312 if(recTime > 0)
17313 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17315 // category spells
17316 if (cat && catrec > 0)
17318 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17319 if(i_scstore != sSpellCategoryStore.end())
17321 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17323 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17324 continue;
17326 AddSpellCooldown(*i_scset, itemId, catrecTime);
17332 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17334 SpellCooldown sc;
17335 sc.end = end_time;
17336 sc.itemid = itemid;
17337 m_spellCooldowns[spellid] = sc;
17340 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17342 // start cooldowns at server side, if any
17343 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17345 // Send activate cooldown timer (possible 0) at client side
17346 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17347 data << spellInfo->Id;
17348 data << GetGUID();
17349 SendDirectMessage(&data);
17352 void Player::UpdatePotionCooldown(Spell* spell)
17354 // no potion used i combat or still in combat
17355 if(!m_lastPotionId || isInCombat())
17356 return;
17358 // Call not from spell cast, send cooldown event for item spells if no in combat
17359 if(!spell)
17361 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17362 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17363 for(int idx = 0; idx < 5; ++idx)
17364 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17365 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17366 SendCooldownEvent(spellInfo,m_lastPotionId);
17368 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17369 else
17370 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17372 m_lastPotionId = 0;
17375 //slot to be excluded while counting
17376 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17378 if(!enchantmentcondition)
17379 return true;
17381 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17383 if(!Condition)
17384 return true;
17386 uint8 curcount[4] = {0, 0, 0, 0};
17388 //counting current equipped gem colors
17389 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17391 if(i == slot)
17392 continue;
17393 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17394 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17396 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17398 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17399 if(!enchant_id)
17400 continue;
17402 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17403 if(!enchantEntry)
17404 continue;
17406 uint32 gemid = enchantEntry->GemID;
17407 if(!gemid)
17408 continue;
17410 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17411 if(!gemProto)
17412 continue;
17414 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17415 if(!gemProperty)
17416 continue;
17418 uint8 GemColor = gemProperty->color;
17420 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17422 if(tmpcolormask & GemColor)
17423 ++curcount[b];
17429 bool activate = true;
17431 for(int i = 0; i < 5; ++i)
17433 if(!Condition->Color[i])
17434 continue;
17436 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17438 // if have <CompareColor> use them as count, else use <value> from Condition
17439 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17441 switch(Condition->Comparator[i])
17443 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17444 activate &= (_cur_gem < _cmp_gem) ? true : false;
17445 break;
17446 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17447 activate &= (_cur_gem > _cmp_gem) ? true : false;
17448 break;
17449 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17450 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17451 break;
17455 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");
17457 return activate;
17460 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17462 //cycle all equipped items
17463 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17465 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17466 if(slot == exceptslot)
17467 continue;
17469 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17471 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17472 continue;
17474 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17476 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17477 if(!enchant_id)
17478 continue;
17480 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17481 if(!enchantEntry)
17482 continue;
17484 uint32 condition = enchantEntry->EnchantmentCondition;
17485 if(condition)
17487 //was enchant active with/without item?
17488 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17489 //should it now be?
17490 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17492 // ignore item gem conditions
17493 //if state changed, (dis)apply enchant
17494 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17501 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17502 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17504 //cycle all equipped items
17505 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17507 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17508 if(slot == exceptslot)
17509 continue;
17511 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17513 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17514 continue;
17516 //cycle all (gem)enchants
17517 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17519 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17520 if(!enchant_id) //if no enchant go to next enchant(slot)
17521 continue;
17523 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17524 if(!enchantEntry)
17525 continue;
17527 //only metagems to be (de)activated, so only enchants with condition
17528 uint32 condition = enchantEntry->EnchantmentCondition;
17529 if(condition)
17530 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17535 void Player::LeaveBattleground(bool teleportToEntryPoint)
17537 if(BattleGround *bg = GetBattleGround())
17539 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17541 // call after remove to be sure that player resurrected for correct cast
17542 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17544 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17545 CastSpell(this, 26013, true); // Deserter
17550 bool Player::CanJoinToBattleground() const
17552 // check Deserter debuff
17553 if(GetDummyAura(26013))
17554 return false;
17556 return true;
17559 bool Player::CanReportAfkDueToLimit()
17561 // a player can complain about 15 people per 5 minutes
17562 if(m_bgAfkReportedCount >= 15)
17563 return false;
17564 ++m_bgAfkReportedCount;
17565 return true;
17568 ///This player has been blamed to be inactive in a battleground
17569 void Player::ReportedAfkBy(Player* reporter)
17571 BattleGround *bg = GetBattleGround();
17572 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17573 return;
17575 // check if player has 'Idle' or 'Inactive' debuff
17576 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17578 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17579 // 3 players have to complain to apply debuff
17580 if(m_bgAfkReporter.size() >= 3)
17582 // cast 'Idle' spell
17583 CastSpell(this, 43680, true);
17584 m_bgAfkReporter.clear();
17589 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17591 // gamemaster in GM mode see all, including ghosts
17592 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17593 return true;
17595 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17596 if (InBattleGround())
17598 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17599 return false;
17600 return true;
17603 // Live player see live player or dead player with not realized corpse
17604 if(pl->isAlive() || pl->m_deathTimer > 0)
17606 return isAlive() || m_deathTimer > 0;
17609 // Ghost see other friendly ghosts, that's for sure
17610 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17611 return true;
17613 // Dead player see live players near own corpse
17614 if(isAlive())
17616 Corpse *corpse = pl->GetCorpse();
17617 if(corpse)
17619 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17620 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17621 return true;
17625 // and not see any other
17626 return false;
17629 bool Player::IsVisibleGloballyFor( Player* u ) const
17631 if(!u)
17632 return false;
17634 // Always can see self
17635 if (u==this)
17636 return true;
17638 // Visible units, always are visible for all players
17639 if (GetVisibility() == VISIBILITY_ON)
17640 return true;
17642 // GMs are visible for higher gms (or players are visible for gms)
17643 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17644 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17646 // non faction visibility non-breakable for non-GMs
17647 if (GetVisibility() == VISIBILITY_OFF)
17648 return false;
17650 // non-gm stealth/invisibility not hide from global player lists
17651 return true;
17654 void Player::UpdateVisibilityOf(WorldObject* target)
17656 if(HaveAtClient(target))
17658 if(!target->isVisibleForInState(this,true))
17660 target->DestroyForPlayer(this);
17661 m_clientGUIDs.erase(target->GetGUID());
17663 #ifdef MANGOS_DEBUG
17664 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17665 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17666 #endif
17669 else
17671 if(target->isVisibleForInState(this,false))
17673 target->SendUpdateToPlayer(this);
17674 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17675 m_clientGUIDs.insert(target->GetGUID());
17677 #ifdef MANGOS_DEBUG
17678 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17679 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17680 #endif
17682 // target aura duration for caster show only if target exist at caster client
17683 // send data at target visibility change (adding to client)
17684 if(target!=this && target->isType(TYPEMASK_UNIT))
17685 SendAurasForTarget((Unit*)target);
17687 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17688 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17693 template<class T>
17694 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17696 s64.insert(target->GetGUID());
17699 template<>
17700 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17702 if(!target->IsTransport())
17703 s64.insert(target->GetGUID());
17706 template<class T>
17707 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17709 if(HaveAtClient(target))
17711 if(!target->isVisibleForInState(this,true))
17713 target->BuildOutOfRangeUpdateBlock(&data);
17714 m_clientGUIDs.erase(target->GetGUID());
17716 #ifdef MANGOS_DEBUG
17717 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17718 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));
17719 #endif
17722 else
17724 if(target->isVisibleForInState(this,false))
17726 visibleNow.insert(target);
17727 target->BuildUpdate(data_updates);
17728 target->BuildCreateUpdateBlockForPlayer(&data, this);
17729 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17731 #ifdef MANGOS_DEBUG
17732 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17733 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));
17734 #endif
17739 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17740 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17741 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17742 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17743 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17745 void Player::InitPrimaryProffesions()
17747 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17750 void Player::SendComboPoints()
17752 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17753 if (combotarget)
17755 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17756 data.append(combotarget->GetPackGUID());
17757 data << uint8(m_comboPoints);
17758 GetSession()->SendPacket(&data);
17762 void Player::AddComboPoints(Unit* target, int8 count)
17764 if(!count)
17765 return;
17767 // without combo points lost (duration checked in aura)
17768 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17770 if(target->GetGUID() == m_comboTarget)
17772 m_comboPoints += count;
17774 else
17776 if(m_comboTarget)
17777 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17778 target2->RemoveComboPointHolder(GetGUIDLow());
17780 m_comboTarget = target->GetGUID();
17781 m_comboPoints = count;
17783 target->AddComboPointHolder(GetGUIDLow());
17786 if (m_comboPoints > 5) m_comboPoints = 5;
17787 if (m_comboPoints < 0) m_comboPoints = 0;
17789 SendComboPoints();
17792 void Player::ClearComboPoints()
17794 if(!m_comboTarget)
17795 return;
17797 // without combopoints lost (duration checked in aura)
17798 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17800 m_comboPoints = 0;
17802 SendComboPoints();
17804 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17805 target->RemoveComboPointHolder(GetGUIDLow());
17807 m_comboTarget = 0;
17810 void Player::SetGroup(Group *group, int8 subgroup)
17812 if(group == NULL)
17813 m_group.unlink();
17814 else
17816 // never use SetGroup without a subgroup unless you specify NULL for group
17817 assert(subgroup >= 0);
17818 m_group.link(group, this);
17819 m_group.setSubGroup((uint8)subgroup);
17823 void Player::SendInitialPacketsBeforeAddToMap()
17825 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17826 data << uint32(0); // unknown, may be rest state time or experience
17827 GetSession()->SendPacket(&data);
17829 // Homebind
17830 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17831 data << m_homebindX << m_homebindY << m_homebindZ;
17832 data << (uint32) m_homebindMapId;
17833 data << (uint32) m_homebindZoneId;
17834 GetSession()->SendPacket(&data);
17836 // SMSG_SET_PROFICIENCY
17837 // SMSG_UPDATE_AURA_DURATION
17839 // tutorial stuff
17840 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17841 for (int i = 0; i < 8; ++i)
17842 data << uint32( GetTutorialInt(i) );
17843 GetSession()->SendPacket(&data);
17845 SendInitialSpells();
17847 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17848 data << uint32(0); // count, for(count) uint32;
17849 GetSession()->SendPacket(&data);
17851 SendInitialActionButtons();
17852 m_reputationMgr.SendInitialReputations();
17853 m_achievementMgr.SendAllAchievementData();
17855 // update zone
17856 uint32 newzone, newarea;
17857 GetZoneAndAreaId(newzone,newarea);
17858 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17860 // SMSG_SET_AURA_SINGLE
17862 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17863 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17864 data << (float)0.01666667f; // game speed
17865 GetSession()->SendPacket( &data );
17867 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17868 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17869 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17871 m_mover = this;
17874 void Player::SendInitialPacketsAfterAddToMap()
17876 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17877 data << uint32(0x00000000); // on blizz it increments periodically
17878 GetSession()->SendPacket(&data);
17880 CastSpell(this, 836, true); // LOGINEFFECT
17882 // set some aura effects that send packet to player client after add player to map
17883 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17884 // same auras state lost at far teleport, send it one more time in this case also
17885 static const AuraType auratypes[] =
17887 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17888 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17889 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17891 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17893 Unit::AuraList const& auraList = GetAurasByType(*itr);
17894 if(!auraList.empty())
17895 auraList.front()->ApplyModifier(true,true);
17898 if(HasAuraType(SPELL_AURA_MOD_STUN))
17899 SetMovement(MOVE_ROOT);
17901 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17902 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17904 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17905 data2.append(GetPackGUID());
17906 data2 << (uint32)2;
17907 SendMessageToSet(&data2,true);
17910 SendAurasForTarget(this);
17911 SendEnchantmentDurations(); // must be after add to map
17912 SendItemDurations(); // must be after add to map
17915 void Player::SendUpdateToOutOfRangeGroupMembers()
17917 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17918 return;
17919 if(Group* group = GetGroup())
17920 group->UpdatePlayerOutOfRange(this);
17922 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17923 m_auraUpdateMask = 0;
17924 if(Pet *pet = GetPet())
17925 pet->ResetAuraUpdateMask();
17928 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17930 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17931 data << uint32(mapid);
17932 data << uint8(reason); // transfer abort reason
17933 switch(reason)
17935 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17936 case TRANSFER_ABORT_DIFFICULTY:
17937 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17938 data << uint8(arg);
17939 break;
17941 GetSession()->SendPacket(&data);
17944 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17946 // type of warning, based on the time remaining until reset
17947 uint32 type;
17948 if(time > 3600)
17949 type = RAID_INSTANCE_WELCOME;
17950 else if(time > 900 && time <= 3600)
17951 type = RAID_INSTANCE_WARNING_HOURS;
17952 else if(time > 300 && time <= 900)
17953 type = RAID_INSTANCE_WARNING_MIN;
17954 else
17955 type = RAID_INSTANCE_WARNING_MIN_SOON;
17956 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17957 data << uint32(type);
17958 data << uint32(mapid);
17959 data << uint32(time);
17960 GetSession()->SendPacket(&data);
17963 void Player::ApplyEquipCooldown( Item * pItem )
17965 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17967 _Spell const& spellData = pItem->GetProto()->Spells[i];
17969 // no spell
17970 if( !spellData.SpellId )
17971 continue;
17973 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17974 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17975 continue;
17977 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17979 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17980 data << pItem->GetGUID();
17981 data << uint32(spellData.SpellId);
17982 GetSession()->SendPacket(&data);
17986 void Player::resetSpells()
17988 // not need after this call
17989 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17991 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17992 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17995 // make full copy of map (spells removed and marked as deleted at another spell remove
17996 // and we can't use original map for safe iterative with visit each spell at loop end
17997 PlayerSpellMap smap = GetSpellMap();
17999 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18000 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18002 learnDefaultSpells();
18003 learnQuestRewardedSpells();
18006 void Player::learnDefaultSpells()
18008 // learn default race/class spells
18009 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18010 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18012 uint32 tspell = *itr;
18013 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18014 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18015 addSpell(tspell,true,true,true,false);
18016 else // but send in normal spell in game learn case
18017 learnSpell(tspell,true);
18021 void Player::learnQuestRewardedSpells(Quest const* quest)
18023 uint32 spell_id = quest->GetRewSpellCast();
18025 // skip quests without rewarded spell
18026 if( !spell_id )
18027 return;
18029 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18030 if(!spellInfo)
18031 return;
18033 // check learned spells state
18034 bool found = false;
18035 for(int i=0; i < 3; ++i)
18037 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18039 found = true;
18040 break;
18044 // skip quests with not teaching spell or already known spell
18045 if(!found)
18046 return;
18048 // prevent learn non first rank unknown profession and second specialization for same profession)
18049 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18050 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18052 // not have first rank learned (unlearned prof?)
18053 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18054 if( !HasSpell(first_spell) )
18055 return;
18057 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18058 if(!learnedInfo)
18059 return;
18061 // specialization
18062 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18064 // search other specialization for same prof
18065 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18067 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18068 continue;
18070 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18071 if(!itrInfo)
18072 return;
18074 // compare only specializations
18075 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18076 continue;
18078 // compare same chain spells
18079 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18080 continue;
18082 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18083 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18084 return;
18089 CastSpell( this, spell_id, true);
18092 void Player::learnQuestRewardedSpells()
18094 // learn spells received from quest completing
18095 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18097 // skip no rewarded quests
18098 if(!itr->second.m_rewarded)
18099 continue;
18101 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18102 if( !quest )
18103 continue;
18105 learnQuestRewardedSpells(quest);
18109 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18111 uint32 raceMask = getRaceMask();
18112 uint32 classMask = getClassMask();
18113 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18115 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18116 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18117 continue;
18118 // Check race if set
18119 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18120 continue;
18121 // Check class if set
18122 if (pAbility->classmask && !(pAbility->classmask & classMask))
18123 continue;
18125 if (sSpellStore.LookupEntry(pAbility->spellId))
18127 // need unlearn spell
18128 if (skill_value < pAbility->req_skill_value)
18129 removeSpell(pAbility->spellId);
18130 // need learn
18131 else if (!IsInWorld())
18132 addSpell(pAbility->spellId,true,true,true,false);
18133 else
18134 learnSpell(pAbility->spellId,true);
18139 void Player::SendAurasForTarget(Unit *target)
18141 if(target->GetVisibleAuras()->empty()) // speedup things
18142 return;
18144 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18145 data.append(target->GetPackGUID());
18147 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18148 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18150 for(uint32 j = 0; j < 3; ++j)
18152 if(Aura *aura = target->GetAura(itr->second, j))
18154 data << uint8(aura->GetAuraSlot());
18155 data << uint32(aura->GetId());
18157 if(aura->GetId())
18159 uint8 auraFlags = aura->GetAuraFlags();
18160 // flags
18161 data << uint8(auraFlags);
18162 // level
18163 data << uint8(aura->GetAuraLevel());
18164 // charges
18165 data << uint8(aura->GetAuraCharges());
18167 if(!(auraFlags & AFLAG_NOT_CASTER))
18169 data << uint8(0); // packed GUID of someone (caster?)
18172 if(auraFlags & AFLAG_DURATION) // include aura duration
18174 data << uint32(aura->GetAuraMaxDuration());
18175 data << uint32(aura->GetAuraDuration());
18178 break;
18183 GetSession()->SendPacket(&data);
18186 void Player::SetDailyQuestStatus( uint32 quest_id )
18188 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18190 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18192 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18193 m_lastDailyQuestTime = time(NULL); // last daily quest time
18194 m_DailyQuestChanged = true;
18195 break;
18200 void Player::ResetDailyQuestStatus()
18202 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18203 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18205 // DB data deleted in caller
18206 m_DailyQuestChanged = false;
18207 m_lastDailyQuestTime = 0;
18210 BattleGround* Player::GetBattleGround() const
18212 if(GetBattleGroundId()==0)
18213 return NULL;
18215 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18218 bool Player::InArena() const
18220 BattleGround *bg = GetBattleGround();
18221 if(!bg || !bg->isArena())
18222 return false;
18224 return true;
18227 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18229 // get a template bg instead of running one
18230 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18231 if(!bg)
18232 return false;
18234 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18235 return false;
18237 return true;
18240 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18242 //returned to hardcoded version of this function, because there is no way to code it dynamic
18243 uint32 level = getLevel();
18244 if( bgTypeId == BATTLEGROUND_AV )
18245 level--;
18247 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18248 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18250 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18251 return QUEUE_ID_MAX_LEVEL_80;
18253 return BGQueueIdBasedOnLevel(queue_id);
18256 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18258 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18259 if(!vendor_faction || !vendor_faction->faction)
18260 return 1.0f;
18262 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18263 if(rank <= REP_NEUTRAL)
18264 return 1.0f;
18266 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18269 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18271 uint32 racemask = getRaceMask();
18272 uint32 classmask = getClassMask();
18274 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18275 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18276 if(lower==upper)
18277 return true;
18279 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18281 // skip wrong race skills
18282 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18283 continue;
18285 // skip wrong class skills
18286 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18287 continue;
18289 return true;
18292 return false;
18295 bool Player::HasQuestForGO(int32 GOId) const
18297 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18299 uint32 questid = GetQuestSlotQuestId(i);
18300 if ( questid == 0 )
18301 continue;
18303 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18304 if(qs_itr == mQuestStatus.end())
18305 continue;
18307 QuestStatusData const& qs = qs_itr->second;
18309 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18311 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18312 if(!qinfo)
18313 continue;
18315 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18316 continue;
18318 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18320 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18321 continue;
18323 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18324 return true;
18328 return false;
18331 void Player::UpdateForQuestWorldObjects()
18333 if(m_clientGUIDs.empty())
18334 return;
18336 UpdateData udata;
18337 WorldPacket packet;
18338 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18340 if(IS_GAMEOBJECT_GUID(*itr))
18342 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18343 if(obj)
18344 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18346 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18348 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18349 if(!obj)
18350 continue;
18351 // check if this unit requires quest specific flags
18353 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
18354 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(obj->GetEntry()); itr != map.upper_bound(obj->GetEntry()); ++itr)
18356 if(itr->second.questId != 0)
18358 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18359 break;
18365 udata.BuildPacket(&packet);
18366 GetSession()->SendPacket(&packet);
18369 void Player::SummonIfPossible(bool agree)
18371 if(!agree)
18373 m_summon_expire = 0;
18374 return;
18377 // expire and auto declined
18378 if(m_summon_expire < time(NULL))
18379 return;
18381 // stop taxi flight at summon
18382 if(isInFlight())
18384 GetMotionMaster()->MovementExpired();
18385 m_taxi.ClearTaxiDestinations();
18388 // drop flag at summon
18389 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18390 if(BattleGround *bg = GetBattleGround())
18391 bg->EventPlayerDroppedFlag(this);
18393 m_summon_expire = 0;
18395 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18397 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18400 void Player::RemoveItemDurations( Item *item )
18402 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18404 if(*itr==item)
18406 m_itemDuration.erase(itr);
18407 break;
18412 void Player::AddItemDurations( Item *item )
18414 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18416 m_itemDuration.push_back(item);
18417 item->SendTimeUpdate(this);
18421 void Player::AutoUnequipOffhandIfNeed()
18423 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18424 if(!offItem)
18425 return;
18427 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18428 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18429 return;
18431 ItemPosCountVec off_dest;
18432 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18433 if( off_msg == EQUIP_ERR_OK )
18435 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18436 StoreItem( off_dest, offItem, true );
18438 else
18440 MailItemsInfo mi;
18441 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18442 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18443 CharacterDatabase.BeginTransaction();
18444 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18445 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18446 CharacterDatabase.CommitTransaction();
18448 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18449 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18453 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18455 if(spellInfo->EquippedItemClass < 0)
18456 return true;
18458 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18459 // for optimize check 2 used cases only
18460 switch(spellInfo->EquippedItemClass)
18462 case ITEM_CLASS_WEAPON:
18464 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18465 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18466 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18467 return true;
18468 break;
18470 case ITEM_CLASS_ARMOR:
18472 // tabard not have dependent spells
18473 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18474 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18475 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18476 return true;
18478 // shields can be equipped to offhand slot
18479 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18480 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18481 return true;
18483 // ranged slot can have some armor subclasses
18484 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18485 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18486 return true;
18488 break;
18490 default:
18491 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18492 break;
18495 return false;
18498 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18500 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18501 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18502 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18503 return true;
18505 // Check no reagent use mask
18506 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18507 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18508 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18509 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18510 return true;
18512 return false;
18515 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18517 AuraMap& auras = GetAuras();
18518 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18520 Aura* aura = itr->second;
18522 // skip passive (passive item dependent spells work in another way) and not self applied auras
18523 SpellEntry const* spellInfo = aura->GetSpellProto();
18524 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18526 ++itr;
18527 continue;
18530 // skip if not item dependent or have alternative item
18531 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18533 ++itr;
18534 continue;
18537 // no alt item, remove aura, restart check
18538 RemoveAurasDueToSpell(aura->GetId());
18539 itr = auras.begin();
18542 // currently casted spells can be dependent from item
18543 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18545 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18546 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18547 InterruptSpell(i);
18551 uint32 Player::GetResurrectionSpellId()
18553 // search priceless resurrection possibilities
18554 uint32 prio = 0;
18555 uint32 spell_id = 0;
18556 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18557 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18559 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18560 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18562 switch((*itr)->GetId())
18564 case 20707: spell_id = 3026; break; // rank 1
18565 case 20762: spell_id = 20758; break; // rank 2
18566 case 20763: spell_id = 20759; break; // rank 3
18567 case 20764: spell_id = 20760; break; // rank 4
18568 case 20765: spell_id = 20761; break; // rank 5
18569 case 27239: spell_id = 27240; break; // rank 6
18570 case 47883: spell_id = 47882; break; // rank 7
18571 default:
18572 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18573 continue;
18576 prio = 3;
18578 // Twisting Nether // prio: 2 (max)
18579 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18581 prio = 2;
18582 spell_id = 23700;
18586 // Reincarnation (passive spell) // prio: 1
18587 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18588 spell_id = 21169;
18590 return spell_id;
18593 // Used in triggers for check "Only to targets that grant experience or honor" req
18594 bool Player::isHonorOrXPTarget(Unit* pVictim)
18596 uint32 v_level = pVictim->getLevel();
18597 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18599 // Victim level less gray level
18600 if(v_level<=k_grey)
18601 return false;
18603 if(pVictim->GetTypeId() == TYPEID_UNIT)
18605 if (((Creature*)pVictim)->isTotem() ||
18606 ((Creature*)pVictim)->isPet() ||
18607 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18608 return false;
18610 return true;
18613 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18615 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18617 // prepare data for near group iteration (PvP and !PvP cases)
18618 uint32 xp = 0;
18619 bool honored_kill = false;
18621 if(Group *pGroup = GetGroup())
18623 uint32 count = 0;
18624 uint32 sum_level = 0;
18625 Player* member_with_max_level = NULL;
18626 Player* not_gray_member_with_max_level = NULL;
18628 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18630 if(member_with_max_level)
18632 /// not get Xp in PvP or no not gray players in group
18633 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18635 /// skip in check PvP case (for speed, not used)
18636 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18637 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18638 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18640 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18642 Player* pGroupGuy = itr->getSource();
18643 if(!pGroupGuy)
18644 continue;
18646 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18647 continue; // member (alive or dead) or his corpse at req. distance
18649 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18650 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18651 honored_kill = true;
18653 // xp and reputation only in !PvP case
18654 if(!PvP)
18656 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18658 // if is in dungeon then all receive full reputation at kill
18659 // rewarded any alive/dead/near_corpse group member
18660 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18662 // XP updated only for alive group member
18663 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18664 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18666 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18668 pGroupGuy->GiveXP(itr_xp, pVictim);
18669 if(Pet* pet = pGroupGuy->GetPet())
18670 pet->GivePetXP(itr_xp/2);
18673 // quest objectives updated only for alive group member or dead but with not released body
18674 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18676 // normal creature (not pet/etc) can be only in !PvP case
18677 if(pVictim->GetTypeId()==TYPEID_UNIT)
18678 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18684 else // if (!pGroup)
18686 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18688 // honor can be in PvP and !PvP (racial leader) cases
18689 if(RewardHonor(pVictim,1))
18690 honored_kill = true;
18692 // xp and reputation only in !PvP case
18693 if(!PvP)
18695 RewardReputation(pVictim,1);
18696 GiveXP(xp, pVictim);
18698 if(Pet* pet = GetPet())
18699 pet->GivePetXP(xp);
18701 // normal creature (not pet/etc) can be only in !PvP case
18702 if(pVictim->GetTypeId()==TYPEID_UNIT)
18703 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18706 return xp || honored_kill;
18709 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18711 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18713 // prepare data for near group iteration
18714 if(Group *pGroup = GetGroup())
18716 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18718 Player* pGroupGuy = itr->getSource();
18719 if(!pGroupGuy)
18720 continue;
18722 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18723 continue; // member (alive or dead) or his corpse at req. distance
18725 // quest objectives updated only for alive group member or dead but with not released body
18726 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18727 pGroupGuy->KilledMonster(creature_id, creature_guid);
18730 else // if (!pGroup)
18731 KilledMonster(creature_id, creature_guid);
18734 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18736 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18737 return true;
18739 if (isAlive())
18740 return false;
18742 Corpse* corpse = GetCorpse();
18743 if (!corpse)
18744 return false;
18746 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18749 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18751 Item* item = GetWeaponForAttack(attType,true);
18753 // unarmed only with base attack
18754 if(attType != BASE_ATTACK && !item)
18755 return 0;
18757 // weapon skill or (unarmed for base attack)
18758 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18759 return GetBaseSkillValue(skill);
18762 void Player::ResurectUsingRequestData()
18764 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18765 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18767 ResurrectPlayer(0.0f,false);
18769 if(GetMaxHealth() > m_resurrectHealth)
18770 SetHealth( m_resurrectHealth );
18771 else
18772 SetHealth( GetMaxHealth() );
18774 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18775 SetPower(POWER_MANA, m_resurrectMana );
18776 else
18777 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18779 SetPower(POWER_RAGE, 0 );
18781 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18783 SpawnCorpseBones();
18786 void Player::SetClientControl(Unit* target, uint8 allowMove)
18788 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18789 data.append(target->GetPackGUID());
18790 data << uint8(allowMove);
18791 GetSession()->SendPacket(&data);
18794 void Player::UpdateZoneDependentAuras( uint32 newZone )
18796 // remove new continent flight forms
18797 if( !IsAllowUseFlyMountsHere() )
18799 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18800 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18803 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18804 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18805 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18806 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18807 if( !HasAura(itr->second->spellId,0) )
18808 CastSpell(this,itr->second->spellId,true);
18811 void Player::UpdateAreaDependentAuras( uint32 newArea )
18813 // remove auras from spells with area limitations
18814 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18816 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18817 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18818 RemoveAura(iter);
18819 else
18820 ++iter;
18823 // some auras applied at subzone enter
18824 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18825 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18826 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18827 if( !HasAura(itr->second->spellId,0) )
18828 CastSpell(this,itr->second->spellId,true);
18831 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18833 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18834 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18836 return copseReclaimDelay[0];
18839 time_t now = time(NULL);
18840 // 0..2 full period
18841 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18842 return copseReclaimDelay[count];
18845 void Player::UpdateCorpseReclaimDelay()
18847 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18849 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18850 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18851 return;
18853 time_t now = time(NULL);
18854 if(now < m_deathExpireTime)
18856 // full and partly periods 1..3
18857 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18858 if(count < MAX_DEATH_COUNT)
18859 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18860 else
18861 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18863 else
18864 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18867 void Player::SendCorpseReclaimDelay(bool load)
18869 Corpse* corpse = GetCorpse();
18870 if(!corpse)
18871 return;
18873 uint32 delay;
18874 if(load)
18876 if(corpse->GetGhostTime() > m_deathExpireTime)
18877 return;
18879 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18881 uint32 count;
18882 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18883 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18885 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18886 if(count>=MAX_DEATH_COUNT)
18887 count = MAX_DEATH_COUNT-1;
18889 else
18890 count=0;
18892 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18894 time_t now = time(NULL);
18895 if(now >= expected_time)
18896 return;
18898 delay = expected_time-now;
18900 else
18901 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18903 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18904 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18905 data << uint32(delay*IN_MILISECONDS);
18906 GetSession()->SendPacket( &data );
18909 Player* Player::GetNextRandomRaidMember(float radius)
18911 Group *pGroup = GetGroup();
18912 if(!pGroup)
18913 return NULL;
18915 std::vector<Player*> nearMembers;
18916 nearMembers.reserve(pGroup->GetMembersCount());
18918 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18920 Player* Target = itr->getSource();
18922 // IsHostileTo check duel and controlled by enemy
18923 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18924 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18925 nearMembers.push_back(Target);
18928 if (nearMembers.empty())
18929 return NULL;
18931 uint32 randTarget = urand(0,nearMembers.size()-1);
18932 return nearMembers[randTarget];
18935 PartyResult Player::CanUninviteFromGroup() const
18937 const Group* grp = GetGroup();
18938 if(!grp)
18939 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18941 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18942 return PARTY_RESULT_YOU_NOT_LEADER;
18944 if(InBattleGround())
18945 return PARTY_RESULT_INVITE_RESTRICTED;
18947 return PARTY_RESULT_OK;
18950 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18952 //we must move references from m_group to m_originalGroup
18953 SetOriginalGroup(GetGroup(), GetSubGroup());
18955 m_group.unlink();
18956 m_group.link(group, this);
18957 m_group.setSubGroup((uint8)subgroup);
18960 void Player::RemoveFromBattleGroundRaid()
18962 //remove existing reference
18963 m_group.unlink();
18964 if( Group* group = GetOriginalGroup() )
18966 m_group.link(group, this);
18967 m_group.setSubGroup(GetOriginalSubGroup());
18969 SetOriginalGroup(NULL);
18972 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18974 if( group == NULL )
18975 m_originalGroup.unlink();
18976 else
18978 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18979 assert(subgroup >= 0);
18980 m_originalGroup.link(group, this);
18981 m_originalGroup.setSubGroup((uint8)subgroup);
18985 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18987 LiquidData liquid_status;
18988 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18989 if (!res)
18991 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18992 // Small hack for enable breath in WMO
18993 if (IsInWater())
18994 m_MirrorTimerFlags|=UNDERWATER_INWATER;
18995 return;
18998 // All liquids type - check under water position
18999 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19001 if ( res & LIQUID_MAP_UNDER_WATER)
19002 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19003 else
19004 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19007 // Allow travel in dark water on taxi or transport
19008 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19009 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19010 else
19011 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19013 // in lava check, anywhere in lava level
19014 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19016 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19017 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19018 else
19019 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19021 // in slime check, anywhere in slime level
19022 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19024 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19025 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19026 else
19027 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19031 void Player::SetCanParry( bool value )
19033 if(m_canParry==value)
19034 return;
19036 m_canParry = value;
19037 UpdateParryPercentage();
19040 void Player::SetCanBlock( bool value )
19042 if(m_canBlock==value)
19043 return;
19045 m_canBlock = value;
19046 UpdateBlockPercentage();
19049 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19051 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19052 if(itr->pos == pos)
19053 return true;
19055 return false;
19058 bool Player::CanUseBattleGroundObject()
19060 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19061 // maybe gameobject code should handle that ForceReaction usage
19062 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19063 return ( //InBattleGround() && // in battleground - not need, check in other cases
19064 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19065 //player cannot use object when he is invulnerable (immune)
19066 !isTotalImmune() && // not totally immune
19067 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19068 !HasStealthAura() && // not stealthed
19069 !HasInvisibilityAura() && // not invisible
19070 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19071 isAlive() // live player
19075 bool Player::CanCaptureTowerPoint()
19077 return ( !HasStealthAura() && // not stealthed
19078 !HasInvisibilityAura() && // not invisible
19079 isAlive() // live player
19083 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19085 uint32 level = getLevel();
19087 if(level > GT_MAX_LEVEL)
19088 level = GT_MAX_LEVEL; // max level in this dbc
19090 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19091 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19092 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19094 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19095 return 0;
19097 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19099 if(!bsc) // shouldn't happen
19100 return 0xFFFFFFFF;
19102 float cost = 0;
19104 if(hairstyle != newhairstyle)
19105 cost += bsc->cost; // full price
19107 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19108 cost += bsc->cost * 0.5f; // +1/2 of price
19110 if(facialhair != newfacialhair)
19111 cost += bsc->cost * 0.75f; // +3/4 of price
19113 return uint32(cost);
19116 void Player::InitGlyphsForLevel()
19118 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19119 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19120 if(gs->Order)
19121 SetGlyphSlot(gs->Order - 1, gs->Id);
19123 uint32 level = getLevel();
19124 uint32 value = 0;
19126 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19127 if(level >= 15)
19128 value |= (0x01 | 0x02);
19129 if(level >= 30)
19130 value |= 0x08;
19131 if(level >= 50)
19132 value |= 0x04;
19133 if(level >= 70)
19134 value |= 0x10;
19135 if(level >= 80)
19136 value |= 0x20;
19138 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19141 void Player::EnterVehicle(Vehicle *vehicle)
19143 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19144 if(!ve)
19145 return;
19147 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19148 if(!veSeat)
19149 return;
19151 vehicle->SetCharmerGUID(GetGUID());
19152 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19153 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19154 vehicle->setFaction(getFaction());
19156 SetCharm(vehicle); // charm
19157 SetFarSightGUID(vehicle->GetGUID()); // set view
19159 SetClientControl(vehicle, 1); // redirect controls to vehicle
19161 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19162 GetSession()->SendPacket(&data);
19164 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19165 data.append(GetPackGUID());
19166 data << uint32(0); // counter?
19167 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19168 data << uint16(0); // special flags
19169 data << uint32(getMSTime()); // time
19170 data << vehicle->GetPositionX(); // x
19171 data << vehicle->GetPositionY(); // y
19172 data << vehicle->GetPositionZ(); // z
19173 data << vehicle->GetOrientation(); // o
19174 // transport part, TODO: load/calculate seat offsets
19175 data << uint64(vehicle->GetGUID()); // transport guid
19176 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19177 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19178 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19179 data << float(0); // transport orientation
19180 data << uint32(getMSTime()); // transport time
19181 data << uint8(0); // seat
19182 // end of transport part
19183 data << uint32(0); // fall time
19184 GetSession()->SendPacket(&data);
19186 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19187 data << uint64(vehicle->GetGUID());
19188 data << uint32(0x00000000);
19189 data << uint32(0x00000000);
19190 data << uint32(0x00000101);
19192 for(uint32 i = 0; i < 10; ++i)
19193 data << uint16(0) << uint8(0) << uint8(i+8);
19195 data << uint8(0);
19196 data << uint8(0);
19197 GetSession()->SendPacket(&data);
19200 void Player::ExitVehicle(Vehicle *vehicle)
19202 vehicle->SetCharmerGUID(0);
19203 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19204 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19205 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19207 SetCharm(NULL);
19208 SetFarSightGUID(0);
19210 SetClientControl(vehicle, 0);
19212 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19213 data.append(GetPackGUID());
19214 data << uint32(0); // counter?
19215 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19216 data << uint16(0x40); // special flags
19217 data << uint32(getMSTime()); // time
19218 data << vehicle->GetPositionX(); // x
19219 data << vehicle->GetPositionY(); // y
19220 data << vehicle->GetPositionZ(); // z
19221 data << vehicle->GetOrientation(); // o
19222 data << uint32(0); // fall time
19223 GetSession()->SendPacket(&data);
19225 data.Initialize(SMSG_PET_SPELLS, 8+4);
19226 data << uint64(0);
19227 data << uint32(0);
19228 GetSession()->SendPacket(&data);
19230 // maybe called at dummy aura remove?
19231 // CastSpell(this, 45472, true); // Parachute
19234 bool Player::isTotalImmune()
19236 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19238 uint32 immuneMask = 0;
19239 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19241 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19242 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19243 return true;
19245 return false;
19248 bool Player::HasTitle(uint32 bitIndex)
19250 if (bitIndex > 128)
19251 return false;
19253 uint32 fieldIndexOffset = bitIndex/32;
19254 uint32 flag = 1 << (bitIndex%32);
19255 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19258 void Player::SetTitle(CharTitlesEntry const* title)
19260 uint32 fieldIndexOffset = title->bit_index/32;
19261 uint32 flag = 1 << (title->bit_index%32);
19262 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19265 void Player::ConvertRune(uint8 index, uint8 newType)
19267 SetCurrentRune(index, newType);
19269 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19270 data << uint8(index);
19271 data << uint8(newType);
19272 GetSession()->SendPacket(&data);
19275 void Player::ResyncRunes(uint8 count)
19277 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19278 for(uint32 i = 0; i < count; ++i)
19280 data << uint8(GetCurrentRune(i)); // rune type
19281 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19283 GetSession()->SendPacket(&data);
19286 void Player::AddRunePower(uint8 index)
19288 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19289 data << uint32(1 << index); // mask (0x00-0x3F probably)
19290 GetSession()->SendPacket(&data);
19293 void Player::InitRunes()
19295 if(getClass() != CLASS_DEATH_KNIGHT)
19296 return;
19298 m_runes = new Runes;
19300 m_runes->runeState = 0;
19302 for(uint32 i = 0; i < MAX_RUNES; ++i)
19304 SetBaseRune(i, i / 2); // init base types
19305 SetCurrentRune(i, i / 2); // init current types
19306 SetRuneCooldown(i, 0); // reset cooldowns
19307 m_runes->SetRuneState(i);
19310 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19311 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19314 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19316 Loot loot;
19317 loot.FillLoot (loot_id,store,this,true);
19319 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19320 for(uint32 i = 0; i < max_slot; ++i)
19322 LootItem* lootItem = loot.LootItemInSlot(i,this);
19324 ItemPosCountVec dest;
19325 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19326 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19327 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19328 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19329 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19330 if(msg != EQUIP_ERR_OK)
19332 SendEquipError( msg, NULL, NULL );
19333 continue;
19336 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19337 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19341 uint32 Player::CalculateTalentsPoints() const
19343 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19345 if(getClass() != CLASS_DEATH_KNIGHT)
19346 return base_talent;
19348 uint32 talentPointsForLevel =
19349 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19350 + m_questRewardTalentCount;
19352 if(talentPointsForLevel > base_talent)
19353 talentPointsForLevel = base_talent;
19355 return talentPointsForLevel;
19358 bool Player::IsAllowUseFlyMountsHere() const
19360 if (isGameMaster())
19361 return true;
19363 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19364 return v_map == 530 || v_map == 571 && HasSpell(54197);
19367 void Player::learnSpellHighRank(uint32 spellid)
19369 learnSpell(spellid,false);
19371 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19372 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19373 learnSpellHighRank(itr->second);
19376 void Player::_LoadSkills()
19378 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19380 // reset skill modifiers and set correct unlearn flags
19381 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19383 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19385 // set correct unlearn bit
19386 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19387 if(!id) continue;
19389 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19390 if(!pSkill) continue;
19392 // enable unlearn button for primary professions only
19393 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19394 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19395 else
19396 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19398 // set fixed skill ranges
19399 switch(GetSkillRangeType(pSkill,false))
19401 case SKILL_RANGE_LANGUAGE: // 300..300
19402 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19403 break;
19404 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19405 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19406 break;
19407 default:
19408 break;
19411 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19412 learnSkillRewardedSpells(id, vskill);
19415 // special settings
19416 if(getClass()==CLASS_DEATH_KNIGHT)
19418 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19419 if(base_level < 1)
19420 base_level = 1;
19421 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19422 if(base_skill < 1)
19423 base_skill = 1; // skill mast be known and then > 0 in any case
19425 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19426 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19427 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19428 SetSkill(SKILL_AXES, base_skill,base_skill);
19429 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19430 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19431 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19432 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19433 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19434 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19435 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19436 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19437 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19438 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19439 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19440 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19444 uint32 Player::GetPhaseMaskForSpawn() const
19446 uint32 phase = PHASEMASK_NORMAL;
19447 if(!isGameMaster())
19448 phase = GetPhaseMask();
19449 else
19451 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19452 if(!phases.empty())
19453 phase = phases.front()->GetMiscValue();
19456 // some aura phases include 1 normal map in addition to phase itself
19457 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19458 return n_phase;
19460 return PHASEMASK_NORMAL;
19463 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19465 ItemPrototype const* pProto = pItem->GetProto();
19467 // proto based limitations
19468 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19469 return res;
19471 // check unique-equipped on gems
19472 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19474 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19475 if(!enchant_id)
19476 continue;
19477 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19478 if(!enchantEntry)
19479 continue;
19481 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19482 if(!pGem)
19483 continue;
19485 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19486 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19487 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19489 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19490 return res;
19493 return EQUIP_ERR_OK;
19496 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19498 // check unique-equipped on item
19499 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19501 // there is an equip limit on this item
19502 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19503 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19506 // check unique-equipped limit
19507 if (itemProto->ItemLimitCategory)
19509 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19510 if(!limitEntry)
19511 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19513 if(limit_count > limitEntry->maxCount)
19514 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19516 // there is an equip limit on this item
19517 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19518 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19521 return EQUIP_ERR_OK;
19524 void Player::HandleFall(MovementInfo const& movementInfo)
19526 // calculate total z distance of the fall
19527 float z_diff = m_lastFallZ - movementInfo.z;
19528 sLog.outDebug("zDiff = %f", z_diff);
19530 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19531 // 14.57 can be calculated by resolving damageperc formula below to 0
19532 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19533 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19534 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19536 //Safe fall, fall height reduction
19537 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19539 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19541 if(damageperc >0 )
19543 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19545 float height = movementInfo.z;
19546 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19548 if (damage > 0)
19550 //Prevent fall damage from being more than the player maximum health
19551 if (damage > GetMaxHealth())
19552 damage = GetMaxHealth();
19554 // Gust of Wind
19555 if (GetDummyAura(43621))
19556 damage = GetMaxHealth()/2;
19558 EnvironmentalDamage(DAMAGE_FALL, damage);
19560 // recheck alive, might have died of EnvironmentalDamage
19561 if (isAlive())
19562 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19565 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19566 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);
19571 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19573 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19576 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19578 uint32 CurTalentPoints = GetFreeTalentPoints();
19580 if(CurTalentPoints == 0)
19581 return;
19583 if (talentRank >= MAX_TALENT_RANK)
19584 return;
19586 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19588 if(!talentInfo)
19589 return;
19591 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19593 if(!talentTabInfo)
19594 return;
19596 // prevent learn talent for different class (cheating)
19597 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19598 return;
19600 // find current max talent rank
19601 int32 curtalent_maxrank = 0;
19602 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19604 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19606 curtalent_maxrank = k + 1;
19607 break;
19611 // we already have same or higher talent rank learned
19612 if(curtalent_maxrank >= (talentRank + 1))
19613 return;
19615 // check if we have enough talent points
19616 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19617 return;
19619 // Check if it requires another talent
19620 if (talentInfo->DependsOn > 0)
19622 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19624 bool hasEnoughRank = false;
19625 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19627 if (depTalentInfo->RankID[i] != 0)
19628 if (HasSpell(depTalentInfo->RankID[i]))
19629 hasEnoughRank = true;
19631 if (!hasEnoughRank)
19632 return;
19636 // Find out how many points we have in this field
19637 uint32 spentPoints = 0;
19639 uint32 tTab = talentInfo->TalentTab;
19640 if (talentInfo->Row > 0)
19642 unsigned int numRows = sTalentStore.GetNumRows();
19643 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19645 // Someday, someone needs to revamp
19646 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19647 if (tmpTalent) // the way talents are tracked
19649 if (tmpTalent->TalentTab == tTab)
19651 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19653 if (tmpTalent->RankID[j] != 0)
19655 if (HasSpell(tmpTalent->RankID[j]))
19657 spentPoints += j + 1;
19666 // not have required min points spent in talent tree
19667 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19668 return;
19670 // spell not set in talent.dbc
19671 uint32 spellid = talentInfo->RankID[talentRank];
19672 if( spellid == 0 )
19674 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19675 return;
19678 // already known
19679 if(HasSpell(spellid))
19680 return;
19682 // learn! (other talent ranks will unlearned at learning)
19683 learnSpell(spellid, false);
19684 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19686 // update free talent points
19687 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19690 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19692 Pet *pet = GetPet();
19694 if(!pet)
19695 return;
19697 if(petGuid != pet->GetGUID())
19698 return;
19700 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19702 if(CurTalentPoints == 0)
19703 return;
19705 if (talentRank >= MAX_PET_TALENT_RANK)
19706 return;
19708 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19710 if(!talentInfo)
19711 return;
19713 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19715 if(!talentTabInfo)
19716 return;
19718 CreatureInfo const *ci = pet->GetCreatureInfo();
19720 if(!ci)
19721 return;
19723 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19725 if(!pet_family)
19726 return;
19728 if(pet_family->petTalentType < 0) // not hunter pet
19729 return;
19731 // prevent learn talent for different family (cheating)
19732 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19733 return;
19735 // find current max talent rank
19736 int32 curtalent_maxrank = 0;
19737 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19739 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19741 curtalent_maxrank = k + 1;
19742 break;
19746 // we already have same or higher talent rank learned
19747 if(curtalent_maxrank >= (talentRank + 1))
19748 return;
19750 // check if we have enough talent points
19751 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19752 return;
19754 // Check if it requires another talent
19755 if (talentInfo->DependsOn > 0)
19757 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19759 bool hasEnoughRank = false;
19760 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19762 if (depTalentInfo->RankID[i] != 0)
19763 if (pet->HasSpell(depTalentInfo->RankID[i]))
19764 hasEnoughRank = true;
19766 if (!hasEnoughRank)
19767 return;
19771 // Find out how many points we have in this field
19772 uint32 spentPoints = 0;
19774 uint32 tTab = talentInfo->TalentTab;
19775 if (talentInfo->Row > 0)
19777 unsigned int numRows = sTalentStore.GetNumRows();
19778 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19780 // Someday, someone needs to revamp
19781 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19782 if (tmpTalent) // the way talents are tracked
19784 if (tmpTalent->TalentTab == tTab)
19786 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19788 if (tmpTalent->RankID[j] != 0)
19790 if (pet->HasSpell(tmpTalent->RankID[j]))
19792 spentPoints += j + 1;
19801 // not have required min points spent in talent tree
19802 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19803 return;
19805 // spell not set in talent.dbc
19806 uint32 spellid = talentInfo->RankID[talentRank];
19807 if( spellid == 0 )
19809 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19810 return;
19813 // already known
19814 if(pet->HasSpell(spellid))
19815 return;
19817 // learn! (other talent ranks will unlearned at learning)
19818 pet->learnSpell(spellid);
19819 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19821 // update free talent points
19822 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19825 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19827 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19829 if(apply)
19830 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19831 else
19832 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19836 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19838 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19839 SetFallInformation(minfo.fallTime, minfo.z);
19842 void Player::UnsummonPetTemporaryIfAny()
19844 Pet* pet = GetPet();
19845 if(!pet)
19846 return;
19848 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19850 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19851 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19854 RemovePet(pet, PET_SAVE_AS_CURRENT);
19857 void Player::ResummonPetTemporaryUnSummonedIfAny()
19859 if(!m_temporaryUnsummonedPetNumber)
19860 return;
19862 // not resummon in not appropriate state
19863 if(IsPetNeedBeTemporaryUnsummoned())
19864 return;
19866 if(GetPetGUID())
19867 return;
19869 Pet* NewPet = new Pet;
19870 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19871 delete NewPet;
19873 m_temporaryUnsummonedPetNumber = 0;
19876 bool Player::canSeeSpellClickOn(Creature const *c) const
19878 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
19879 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(c->GetEntry()); itr != map.upper_bound(c->GetEntry()); ++itr)
19881 if(itr->second.questId == 0 || GetQuestStatus(itr->second.questId) == QUEST_STATUS_INCOMPLETE)
19882 return true;
19884 return false;