[7669] Some lost commented code patch for currencies trading item move to empty slot.
[AHbot.git] / src / game / Player.cpp
blob994783e83546d9e1459754ad006797e6a0e781de
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::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
489 delete *itr;
491 for (ItemMap::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 uint8 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 data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
867 GetSession()->SendPacket(&data);
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( !IsNonMeleeSpellCasted(false) && pVictim)
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 = ObjectAccessor::GetGameObject(*this, 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 break;
1878 // Mana regen calculated in Player::UpdateManaRegen()
1879 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1880 if(power != POWER_MANA)
1882 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1883 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1884 if ((*i)->GetModifier()->m_miscvalue == power)
1885 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1888 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1890 curValue += uint32(addvalue);
1891 if (curValue > maxValue)
1892 curValue = maxValue;
1894 else
1896 if(curValue <= uint32(addvalue))
1897 curValue = 0;
1898 else
1899 curValue -= uint32(addvalue);
1901 SetPower(power, curValue);
1904 void Player::RegenerateHealth()
1906 uint32 curValue = GetHealth();
1907 uint32 maxValue = GetMaxHealth();
1909 if (curValue >= maxValue) return;
1911 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1913 float addvalue = 0.0f;
1915 // polymorphed case
1916 if ( IsPolymorphed() )
1917 addvalue = GetMaxHealth()/3;
1918 // normal regen case (maybe partly in combat case)
1919 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1921 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1922 if (!isInCombat())
1924 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1925 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1926 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1928 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1929 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1931 if(!IsStandState())
1932 addvalue *= 1.5;
1935 // always regeneration bonus (including combat)
1936 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1938 if(addvalue < 0)
1939 addvalue = 0;
1941 ModifyHealth(int32(addvalue));
1944 bool Player::CanInteractWithNPCs(bool alive) const
1946 if(alive && !isAlive())
1947 return false;
1948 if(isInFlight())
1949 return false;
1951 return true;
1954 bool Player::IsUnderWater() const
1956 return IsInWater() &&
1957 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1960 void Player::SetInWater(bool apply)
1962 if(m_isInWater==apply)
1963 return;
1965 //define player in water by opcodes
1966 //move player's guid into HateOfflineList of those mobs
1967 //which can't swim and move guid back into ThreatList when
1968 //on surface.
1969 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1970 m_isInWater = apply;
1972 // remove auras that need water/land
1973 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1975 getHostilRefManager().updateThreatTables();
1978 void Player::SetGameMaster(bool on)
1980 if(on)
1982 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1983 setFaction(35);
1984 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1986 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
1987 ResetContestedPvP();
1989 getHostilRefManager().setOnlineOfflineState(false);
1990 CombatStop();
1992 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
1994 else
1996 // restore phase
1997 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
1998 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2000 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2001 setFactionForRace(getRace());
2002 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2004 // restore FFA PvP Server state
2005 if(sWorld.IsFFAPvPRealm())
2006 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2008 // restore FFA PvP area state, remove not allowed for GM mounts
2009 UpdateArea(m_areaUpdateId);
2011 getHostilRefManager().setOnlineOfflineState(true);
2014 ObjectAccessor::UpdateVisibilityForPlayer(this);
2017 void Player::SetGMVisible(bool on)
2019 if(on)
2021 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2023 // Reapply stealth/invisibility if active or show if not any
2024 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2025 SetVisibility(VISIBILITY_GROUP_STEALTH);
2026 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2027 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2028 else
2029 SetVisibility(VISIBILITY_ON);
2031 else
2033 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2035 SetAcceptWhispers(false);
2036 SetGameMaster(true);
2038 SetVisibility(VISIBILITY_OFF);
2042 bool Player::IsGroupVisibleFor(Player* p) const
2044 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2046 default: return IsInSameGroupWith(p);
2047 case 1: return IsInSameRaidWith(p);
2048 case 2: return GetTeam()==p->GetTeam();
2052 bool Player::IsInSameGroupWith(Player const* p) const
2054 return p==this || GetGroup() != NULL &&
2055 GetGroup() == p->GetGroup() &&
2056 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2059 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2060 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2061 void Player::UninviteFromGroup()
2063 Group* group = GetGroupInvite();
2064 if(!group)
2065 return;
2067 group->RemoveInvite(this);
2069 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2071 if(group->IsCreated())
2073 group->Disband(true);
2074 objmgr.RemoveGroup(group);
2076 else
2077 group->RemoveAllInvites();
2079 delete group;
2083 void Player::RemoveFromGroup(Group* group, uint64 guid)
2085 if(group)
2087 if (group->RemoveMember(guid, 0) <= 1)
2089 // group->Disband(); already disbanded in RemoveMember
2090 objmgr.RemoveGroup(group);
2091 delete group;
2092 // removemember sets the player's group pointer to NULL
2097 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2099 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2100 data << uint64(victim ? victim->GetGUID() : 0); // guid
2101 data << uint32(GivenXP+RestXP); // given experience
2102 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2103 if(victim)
2105 data << uint32(GivenXP); // experience without rested bonus
2106 data << float(1); // 1 - none 0 - 100% group bonus output
2108 data << uint8(0); // new 2.4.0
2109 GetSession()->SendPacket(&data);
2112 void Player::GiveXP(uint32 xp, Unit* victim)
2114 if ( xp < 1 )
2115 return;
2117 if(!isAlive())
2118 return;
2120 uint32 level = getLevel();
2122 // XP to money conversion processed in Player::RewardQuest
2123 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2124 return;
2126 // handle SPELL_AURA_MOD_XP_PCT auras
2127 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2128 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2129 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2131 // XP resting bonus for kill
2132 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2134 SendLogXPGain(xp,victim,rested_bonus_xp);
2136 uint32 curXP = GetUInt32Value(PLAYER_XP);
2137 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2138 uint32 newXP = curXP + xp + rested_bonus_xp;
2140 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2142 newXP -= nextLvlXP;
2144 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2145 GiveLevel(level + 1);
2147 level = getLevel();
2148 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2151 SetUInt32Value(PLAYER_XP, newXP);
2154 // Update player to next level
2155 // Current player experience not update (must be update by caller)
2156 void Player::GiveLevel(uint32 level)
2158 if ( level == getLevel() )
2159 return;
2161 PlayerLevelInfo info;
2162 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2164 PlayerClassLevelInfo classInfo;
2165 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2167 // send levelup info to client
2168 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2169 data << uint32(level);
2170 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2171 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2172 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2173 data << uint32(0);
2174 data << uint32(0);
2175 data << uint32(0);
2176 data << uint32(0);
2177 data << uint32(0);
2178 data << uint32(0);
2179 // end for
2180 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2181 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2183 GetSession()->SendPacket(&data);
2185 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2187 //update level, max level of skills
2188 if(getLevel()!= level)
2189 m_Played_time[1] = 0; // Level Played Time reset
2190 SetLevel(level);
2191 UpdateSkillsForLevel ();
2193 // save base values (bonuses already included in stored stats
2194 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2195 SetCreateStat(Stats(i), info.stats[i]);
2197 SetCreateHealth(classInfo.basehealth);
2198 SetCreateMana(classInfo.basemana);
2200 InitTalentForLevel();
2201 InitTaxiNodesForLevel();
2202 InitGlyphsForLevel();
2204 UpdateAllStats();
2206 // set current level health and mana/energy to maximum after applying all mods.
2207 SetHealth(GetMaxHealth());
2208 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2209 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2210 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2211 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2212 SetPower(POWER_FOCUS, 0);
2213 SetPower(POWER_HAPPINESS, 0);
2215 // give level to summoned pet
2216 Pet* pet = GetPet();
2217 if(pet && pet->getPetType()==SUMMON_PET)
2218 pet->GivePetLevel(level);
2219 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2222 void Player::InitTalentForLevel()
2224 uint32 level = getLevel();
2225 // talents base at level diff ( talents = level - 9 but some can be used already)
2226 if(level < 10)
2228 // Remove all talent points
2229 if(m_usedTalentCount > 0) // Free any used talents
2231 resetTalents(true);
2232 SetFreeTalentPoints(0);
2235 else
2237 uint32 talentPointsForLevel = CalculateTalentsPoints();
2239 // if used more that have then reset
2240 if(m_usedTalentCount > talentPointsForLevel)
2242 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2243 resetTalents(true);
2244 else
2245 SetFreeTalentPoints(0);
2247 // else update amount of free points
2248 else
2249 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2253 void Player::InitStatsForLevel(bool reapplyMods)
2255 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2256 _RemoveAllStatBonuses();
2258 PlayerClassLevelInfo classInfo;
2259 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2261 PlayerLevelInfo info;
2262 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2264 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2265 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2267 UpdateSkillsForLevel ();
2269 // set default cast time multiplier
2270 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2272 // reset size before reapply auras
2273 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2275 // save base values (bonuses already included in stored stats
2276 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2277 SetCreateStat(Stats(i), info.stats[i]);
2279 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2280 SetStat(Stats(i), info.stats[i]);
2282 SetCreateHealth(classInfo.basehealth);
2284 //set create powers
2285 SetCreateMana(classInfo.basemana);
2287 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2289 InitStatBuffMods();
2291 //reset rating fields values
2292 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2293 SetUInt32Value(index, 0);
2295 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2296 for (int i = 0; i < 7; i++)
2298 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2299 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2300 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2303 //reset attack power, damage and attack speed fields
2304 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2305 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2306 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2308 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2309 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2310 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2311 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2312 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2313 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2315 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2316 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2317 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2318 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2319 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2320 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2322 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2323 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2324 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2325 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2327 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2328 for (uint8 i = 0; i < 7; ++i)
2329 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2331 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2332 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2333 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2335 // Dodge percentage
2336 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2338 // set armor (resistance 0) to original value (create_agility*2)
2339 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2340 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2341 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2342 // set other resistance to original value (0)
2343 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2345 SetResistance(SpellSchools(i), 0);
2346 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2347 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2350 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2351 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2352 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2354 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2355 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2357 // Reset no reagent cost field
2358 for(int i = 0; i < 3; i++)
2359 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2360 // Init data for form but skip reapply item mods for form
2361 InitDataForForm(reapplyMods);
2363 // save new stats
2364 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2365 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2367 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2369 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2370 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2372 // cleanup unit flags (will be re-applied if need at aura load).
2373 RemoveFlag( UNIT_FIELD_FLAGS,
2374 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2375 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2376 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2377 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2378 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2379 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2381 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2383 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2384 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2386 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2387 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2389 // restore if need some important flags
2390 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2392 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2393 _ApplyAllStatBonuses();
2395 // set current level health and mana/energy to maximum after applying all mods.
2396 SetHealth(GetMaxHealth());
2397 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2398 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2399 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2400 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2401 SetPower(POWER_FOCUS, 0);
2402 SetPower(POWER_HAPPINESS, 0);
2403 SetPower(POWER_RUNIC_POWER, 0);
2406 void Player::SendInitialSpells()
2408 time_t curTime = time(NULL);
2409 time_t infTime = curTime + MONTH/2;
2411 uint16 spellCount = 0;
2413 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2414 data << uint8(0);
2416 size_t countPos = data.wpos();
2417 data << uint16(spellCount); // spell count placeholder
2419 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2421 if(itr->second->state == PLAYERSPELL_REMOVED)
2422 continue;
2424 if(!itr->second->active || itr->second->disabled)
2425 continue;
2427 data << uint16(itr->first);
2428 data << uint16(0); // it's not slot id
2430 spellCount +=1;
2433 data.put<uint16>(countPos,spellCount); // write real count value
2435 uint16 spellCooldowns = m_spellCooldowns.size();
2436 data << uint16(spellCooldowns);
2437 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2439 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2440 if(!sEntry)
2441 continue;
2443 // not send infinity cooldown
2444 if(itr->second.end > infTime)
2445 continue;
2447 data << uint16(itr->first);
2449 time_t cooldown = 0;
2450 if(itr->second.end > curTime)
2451 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2453 data << uint16(itr->second.itemid); // cast item id
2454 data << uint16(sEntry->Category); // spell category
2455 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2457 data << uint32(0); // cooldown
2458 data << uint32(cooldown); // category cooldown
2460 else
2462 data << uint32(cooldown); // cooldown
2463 data << uint32(0); // category cooldown
2467 GetSession()->SendPacket(&data);
2469 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2472 void Player::RemoveMail(uint32 id)
2474 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2476 if ((*itr)->messageID == id)
2478 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2479 m_mail.erase(itr);
2480 return;
2485 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2487 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2488 data << (uint32) mailId;
2489 data << (uint32) mailAction;
2490 data << (uint32) mailError;
2491 if ( mailError == MAIL_ERR_BAG_FULL )
2492 data << (uint32) equipError;
2493 else if( mailAction == MAIL_ITEM_TAKEN )
2495 data << (uint32) item_guid; // item guid low?
2496 data << (uint32) item_count; // item count?
2498 GetSession()->SendPacket(&data);
2501 void Player::SendNewMail()
2503 // deliver undelivered mail
2504 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2505 data << (uint32) 0;
2506 GetSession()->SendPacket(&data);
2509 void Player::UpdateNextMailTimeAndUnreads()
2511 // calculate next delivery time (min. from non-delivered mails
2512 // and recalculate unReadMail
2513 time_t cTime = time(NULL);
2514 m_nextMailDelivereTime = 0;
2515 unReadMails = 0;
2516 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2518 if((*itr)->deliver_time > cTime)
2520 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2521 m_nextMailDelivereTime = (*itr)->deliver_time;
2523 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2524 ++unReadMails;
2528 void Player::AddNewMailDeliverTime(time_t deliver_time)
2530 if(deliver_time <= time(NULL)) // ready now
2532 ++unReadMails;
2533 SendNewMail();
2535 else // not ready and no have ready mails
2537 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2538 m_nextMailDelivereTime = deliver_time;
2542 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2544 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2545 if (!spellInfo)
2547 // do character spell book cleanup (all characters)
2548 if(!IsInWorld() && !learning) // spell load case
2550 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2551 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2553 else
2554 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2556 return false;
2559 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2561 // do character spell book cleanup (all characters)
2562 if(!IsInWorld() && !learning) // spell load case
2564 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2565 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2567 else
2568 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2570 return false;
2573 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2575 bool dependent_set = false;
2576 bool disabled_case = false;
2577 bool superceded_old = false;
2579 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2580 if (itr != m_spells.end())
2582 uint32 next_active_spell_id = 0;
2583 // fix activate state for non-stackable low rank (and find next spell for !active case)
2584 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2586 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2587 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2589 if(HasSpell(next_itr->second))
2591 // high rank already known so this must !active
2592 active = false;
2593 next_active_spell_id = next_itr->second;
2594 break;
2599 // not do anything if already known in expected state
2600 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2601 itr->second->dependent == dependent && itr->second->disabled == disabled)
2603 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2604 itr->second->state = PLAYERSPELL_UNCHANGED;
2606 return false;
2609 // dependent spell known as not dependent, overwrite state
2610 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2612 itr->second->dependent = dependent;
2613 if (itr->second->state != PLAYERSPELL_NEW)
2614 itr->second->state = PLAYERSPELL_CHANGED;
2615 dependent_set = true;
2618 // update active state for known spell
2619 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2621 itr->second->active = active;
2623 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2624 itr->second->state = PLAYERSPELL_UNCHANGED;
2625 else if(itr->second->state != PLAYERSPELL_NEW)
2626 itr->second->state = PLAYERSPELL_CHANGED;
2628 if(active)
2630 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2631 CastSpell (this,spell_id,true);
2633 else if(IsInWorld())
2635 if(next_active_spell_id)
2637 // update spell ranks in spellbook and action bar
2638 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2639 data << uint16(spell_id);
2640 data << uint16(next_active_spell_id);
2641 GetSession()->SendPacket( &data );
2643 else
2645 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2646 data << uint16(spell_id);
2647 GetSession()->SendPacket(&data);
2651 return active; // learn (show in spell book if active now)
2654 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2656 if(itr->second->state != PLAYERSPELL_NEW)
2657 itr->second->state = PLAYERSPELL_CHANGED;
2658 itr->second->disabled = disabled;
2660 if(disabled)
2661 return false;
2663 disabled_case = true;
2665 else switch(itr->second->state)
2667 case PLAYERSPELL_UNCHANGED: // known saved spell
2668 return false;
2669 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2671 delete itr->second;
2672 m_spells.erase(itr);
2673 state = PLAYERSPELL_CHANGED;
2674 break; // need re-add
2676 default: // known not saved yet spell (new or modified)
2678 // can be in case spell loading but learned at some previous spell loading
2679 if(!IsInWorld() && !learning && !dependent_set)
2680 itr->second->state = PLAYERSPELL_UNCHANGED;
2682 return false;
2687 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2689 // talent: unlearn all other talent ranks (high and low)
2690 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2692 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2694 for(int i=0; i < MAX_TALENT_RANK; ++i)
2696 // skip learning spell and no rank spell case
2697 uint32 rankSpellId = talentInfo->RankID[i];
2698 if(!rankSpellId || rankSpellId==spell_id)
2699 continue;
2701 removeSpell(rankSpellId);
2705 // non talent spell: learn low ranks (recursive call)
2706 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2708 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2709 addSpell(prev_spell,active,true,true,disabled);
2710 else // at normal learning
2711 learnSpell(prev_spell,true);
2714 PlayerSpell *newspell = new PlayerSpell;
2715 newspell->state = state;
2716 newspell->active = active;
2717 newspell->dependent = dependent;
2718 newspell->disabled = disabled;
2720 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2721 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2723 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2725 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2726 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2727 if(!i_spellInfo) continue;
2729 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2731 if(itr->second->active)
2733 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2735 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2737 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2738 data << uint16(itr->first);
2739 data << uint16(spell_id);
2740 GetSession()->SendPacket( &data );
2743 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2744 itr->second->active = false;
2745 if(itr->second->state != PLAYERSPELL_NEW)
2746 itr->second->state = PLAYERSPELL_CHANGED;
2747 superceded_old = true; // new spell replace old in action bars and spell book.
2749 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2751 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2753 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2754 data << uint16(spell_id);
2755 data << uint16(itr->first);
2756 GetSession()->SendPacket( &data );
2759 // mark new spell as disable (not learned yet for client and will not learned)
2760 newspell->active = false;
2761 if(newspell->state != PLAYERSPELL_NEW)
2762 newspell->state = PLAYERSPELL_CHANGED;
2769 m_spells[spell_id] = newspell;
2771 // return false if spell disabled
2772 if (newspell->disabled)
2773 return false;
2776 uint32 talentCost = GetTalentSpellCost(spell_id);
2778 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2779 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2780 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2782 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2783 CastSpell(this, spell_id, true);
2785 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2786 else if (IsPassiveSpell(spell_id))
2788 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2789 CastSpell(this, spell_id, true);
2791 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2793 CastSpell(this, spell_id, true);
2794 return false;
2797 // update used talent points count
2798 m_usedTalentCount += talentCost;
2800 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2801 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2803 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2804 SetFreePrimaryProffesions(freeProfs-1);
2807 // add dependent skills
2808 uint16 maxskill = GetMaxSkillValueForLevel();
2810 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2812 if(spellLearnSkill)
2814 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2815 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2817 if(skill_value < spellLearnSkill->value)
2818 skill_value = spellLearnSkill->value;
2820 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2822 if(skill_max_value < new_skill_max_value)
2823 skill_max_value = new_skill_max_value;
2825 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2827 else
2829 // not ranked skills
2830 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2831 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2833 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2835 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2836 if(!pSkill)
2837 continue;
2839 if(HasSkill(pSkill->id))
2840 continue;
2842 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2843 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2844 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2846 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2848 case SKILL_RANGE_LANGUAGE:
2849 SetSkill(pSkill->id, 300, 300 );
2850 break;
2851 case SKILL_RANGE_LEVEL:
2852 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2853 break;
2854 case SKILL_RANGE_MONO:
2855 SetSkill(pSkill->id, 1, 1 );
2856 break;
2857 default:
2858 break;
2864 // learn dependent spells
2865 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2866 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2868 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2870 if(!itr->second.autoLearned)
2872 if(!IsInWorld() || !itr->second.active) // at spells loading, no output, but allow save
2873 addSpell(itr->second.spell,itr->second.active,true,true,false);
2874 else // at normal learning
2875 learnSpell(itr->second.spell,true);
2879 if(IsInWorld())
2881 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2882 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,spell_id);
2885 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2886 return active && !disabled && !superceded_old;
2889 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2891 bool need_cast = false;
2893 switch(spellInfo->Id)
2895 // some spells not have stance data expacted cast at form change or present
2896 case 5420: need_cast = (m_form == FORM_TREE); break;
2897 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2898 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2899 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2900 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2901 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2902 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2903 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2904 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2905 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2906 // another spells have proper stance data
2907 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2910 //Check CasterAuraStates
2911 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
2914 void Player::learnSpell(uint32 spell_id, bool dependent)
2916 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2918 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2919 bool active = disabled ? itr->second->active : true;
2921 bool learning = addSpell(spell_id,active,true,dependent,false);
2923 // learn all disabled higher ranks (recursive)
2924 if(disabled)
2926 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2927 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2929 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2930 if (iter != m_spells.end() && iter->second->disabled)
2931 learnSpell(i->second,false);
2935 // prevent duplicated entires in spell book, also not send if not in world (loading)
2936 if(!learning || !IsInWorld ())
2937 return;
2939 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2940 data << uint32(spell_id);
2941 GetSession()->SendPacket(&data);
2944 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
2946 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2947 if (itr == m_spells.end())
2948 return;
2950 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2951 return;
2953 // unlearn non talent higher ranks (recursive)
2954 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2955 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2956 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2957 removeSpell(itr2->second,disabled);
2959 bool cur_active = itr->second->active;
2960 bool cur_dependent = itr->second->dependent;
2962 if (disabled)
2964 itr->second->disabled = disabled;
2965 if(itr->second->state != PLAYERSPELL_NEW)
2966 itr->second->state = PLAYERSPELL_CHANGED;
2968 else
2970 if(itr->second->state == PLAYERSPELL_NEW)
2972 delete itr->second;
2973 m_spells.erase(itr);
2975 else
2976 itr->second->state = PLAYERSPELL_REMOVED;
2979 RemoveAurasDueToSpell(spell_id);
2981 // remove pet auras
2982 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2983 RemovePetAura(petSpell);
2985 // free talent points
2986 uint32 talentCosts = GetTalentSpellCost(spell_id);
2987 if(talentCosts > 0)
2989 if(talentCosts < m_usedTalentCount)
2990 m_usedTalentCount -= talentCosts;
2991 else
2992 m_usedTalentCount = 0;
2995 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2996 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2998 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2999 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3000 SetFreePrimaryProffesions(freeProfs);
3003 // remove dependent skill
3004 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3005 if(spellLearnSkill)
3007 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3008 if(!prev_spell) // first rank, remove skill
3009 SetSkill(spellLearnSkill->skill,0,0);
3010 else
3012 // search prev. skill setting by spell ranks chain
3013 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3014 while(!prevSkill && prev_spell)
3016 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3017 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3020 if(!prevSkill) // not found prev skill setting, remove skill
3021 SetSkill(spellLearnSkill->skill,0,0);
3022 else // set to prev. skill setting values
3024 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3025 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3027 if(skill_value > prevSkill->value)
3028 skill_value = prevSkill->value;
3030 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3032 if(skill_max_value > new_skill_max_value)
3033 skill_max_value = new_skill_max_value;
3035 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3040 else
3042 // not ranked skills
3043 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3044 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3046 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3048 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3049 if(!pSkill)
3050 continue;
3052 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3053 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3054 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3056 // not reset skills for professions and racial abilities
3057 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3058 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3059 continue;
3061 SetSkill(pSkill->id, 0, 0 );
3066 // remove dependent spells
3067 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3068 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3070 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3071 removeSpell(itr2->second.spell, disabled);
3073 // activate lesser rank in spellbook/action bar, and cast it if need
3074 bool prev_activate = false;
3076 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3078 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3080 // if talent then lesser rank also talent and need learn
3081 if(talentCosts)
3082 learnSpell (prev_id,false);
3083 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3084 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3086 // need manually update dependence state (learn spell ignore like attempts)
3087 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3088 if (prev_itr != m_spells.end())
3090 if(prev_itr->second->dependent != cur_dependent)
3092 prev_itr->second->dependent = cur_dependent;
3093 if(prev_itr->second->state != PLAYERSPELL_NEW)
3094 prev_itr->second->state = PLAYERSPELL_CHANGED;
3097 // now re-learn if need re-activate
3098 if(cur_active && !prev_itr->second->active)
3100 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3102 if(update_action_bar_for_low_rank)
3104 // downgrade spell ranks in spellbook and action bar
3105 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3106 data << uint16(spell_id);
3107 data << uint16(prev_id);
3108 GetSession()->SendPacket( &data );
3109 prev_activate = true;
3117 // remove from spell book if not replaced by lesser rank
3118 if(!prev_activate)
3120 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3121 data << uint16(spell_id);
3122 GetSession()->SendPacket(&data);
3126 void Player::RemoveArenaSpellCooldowns()
3128 // remove cooldowns on spells that has < 15 min CD
3129 SpellCooldowns::iterator itr, next;
3130 // iterate spell cooldowns
3131 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3133 next = itr;
3134 ++next;
3135 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3136 // check if spellentry is present and if the cooldown is less than 15 mins
3137 if( entry &&
3138 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3139 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3141 // notify player
3142 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3143 data << uint32(itr->first);
3144 data << uint64(GetGUID());
3145 GetSession()->SendPacket(&data);
3146 // remove cooldown
3147 m_spellCooldowns.erase(itr);
3152 void Player::RemoveAllSpellCooldown()
3154 if(!m_spellCooldowns.empty())
3156 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3158 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3159 data << uint32(itr->first);
3160 data << uint64(GetGUID());
3161 GetSession()->SendPacket(&data);
3163 m_spellCooldowns.clear();
3167 void Player::_LoadSpellCooldowns(QueryResult *result)
3169 // some cooldowns can be already set at aura loading...
3171 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3173 if(result)
3175 time_t curTime = time(NULL);
3179 Field *fields = result->Fetch();
3181 uint32 spell_id = fields[0].GetUInt32();
3182 uint32 item_id = fields[1].GetUInt32();
3183 time_t db_time = (time_t)fields[2].GetUInt64();
3185 if(!sSpellStore.LookupEntry(spell_id))
3187 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3188 continue;
3191 // skip outdated cooldown
3192 if(db_time <= curTime)
3193 continue;
3195 AddSpellCooldown(spell_id, item_id, db_time);
3197 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3199 while( result->NextRow() );
3201 delete result;
3205 void Player::_SaveSpellCooldowns()
3207 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3209 time_t curTime = time(NULL);
3210 time_t infTime = curTime + MONTH/2;
3212 // remove outdated and save active
3213 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3215 if(itr->second.end <= curTime)
3216 m_spellCooldowns.erase(itr++);
3217 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3219 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));
3220 ++itr;
3222 else
3223 ++itr;
3227 uint32 Player::resetTalentsCost() const
3229 // The first time reset costs 1 gold
3230 if(m_resetTalentsCost < 1*GOLD)
3231 return 1*GOLD;
3232 // then 5 gold
3233 else if(m_resetTalentsCost < 5*GOLD)
3234 return 5*GOLD;
3235 // After that it increases in increments of 5 gold
3236 else if(m_resetTalentsCost < 10*GOLD)
3237 return 10*GOLD;
3238 else
3240 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3241 if(months > 0)
3243 // This cost will be reduced by a rate of 5 gold per month
3244 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3245 // to a minimum of 10 gold.
3246 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3248 else
3250 // After that it increases in increments of 5 gold
3251 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3252 // until it hits a cap of 50 gold.
3253 if(new_cost > 50*GOLD)
3254 new_cost = 50*GOLD;
3255 return new_cost;
3260 bool Player::resetTalents(bool no_cost)
3262 // not need after this call
3263 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3265 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3266 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3269 uint32 talentPointsForLevel = CalculateTalentsPoints();
3271 if (m_usedTalentCount == 0)
3273 SetFreeTalentPoints(talentPointsForLevel);
3274 return false;
3277 uint32 cost = 0;
3279 if(!no_cost)
3281 cost = resetTalentsCost();
3283 if (GetMoney() < cost)
3285 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3286 return false;
3290 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3292 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3294 if (!talentInfo) continue;
3296 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3298 if(!talentTabInfo)
3299 continue;
3301 // unlearn only talents for character class
3302 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3303 // to prevent unexpected lost normal learned spell skip another class talents
3304 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3305 continue;
3307 for (int j = 0; j < MAX_TALENT_RANK; j++)
3309 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3311 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3313 ++itr;
3314 continue;
3317 // remove learned spells (all ranks)
3318 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3320 // unlearn if first rank is talent or learned by talent
3321 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3323 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3324 itr = GetSpellMap().begin();
3325 continue;
3327 else
3328 ++itr;
3333 SetFreeTalentPoints(talentPointsForLevel);
3335 if(!no_cost)
3337 ModifyMoney(-(int32)cost);
3338 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3340 m_resetTalentsCost = cost;
3341 m_resetTalentsTime = time(NULL);
3344 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3345 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3347 if(m_canTitanGrip)
3349 m_canTitanGrip = false;
3350 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3351 AutoUnequipOffhandIfNeed();
3354 return true;
3357 Mail* Player::GetMail(uint32 id)
3359 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3361 if ((*itr)->messageID == id)
3363 return (*itr);
3366 return NULL;
3369 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3371 if(target == this)
3373 Object::_SetCreateBits(updateMask, target);
3375 else
3377 for(uint16 index = 0; index < m_valuesCount; index++)
3379 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3380 updateMask->SetBit(index);
3385 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3387 if(target == this)
3389 Object::_SetUpdateBits(updateMask, target);
3391 else
3393 Object::_SetUpdateBits(updateMask, target);
3394 *updateMask &= updateVisualBits;
3398 void Player::InitVisibleBits()
3400 updateVisualBits.SetCount(PLAYER_END);
3402 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3403 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3404 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3405 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3406 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3407 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3408 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3409 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3410 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3411 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3412 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3413 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3414 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3415 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3416 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3417 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3418 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3419 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3420 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3421 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3422 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3423 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3424 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3425 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3426 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3427 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3428 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3429 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3430 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3431 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3432 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3433 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3434 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3435 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3436 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3437 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3438 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3439 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3440 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3441 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3442 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3443 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3444 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3445 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3446 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3447 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3448 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3449 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3450 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3451 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3452 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3453 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3454 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3455 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3456 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3458 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3459 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3460 updateVisualBits.SetBit(PLAYER_FLAGS);
3461 updateVisualBits.SetBit(PLAYER_GUILDID);
3462 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3463 updateVisualBits.SetBit(PLAYER_BYTES);
3464 updateVisualBits.SetBit(PLAYER_BYTES_2);
3465 updateVisualBits.SetBit(PLAYER_BYTES_3);
3466 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3467 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3469 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3470 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3471 updateVisualBits.SetBit(i);
3473 // Players visible items are not inventory stuff
3474 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3476 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3478 // item creator
3479 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3480 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3482 // item entry
3483 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3485 // item enchantments
3486 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3487 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3489 // random properties
3490 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3491 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3492 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3495 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3498 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3500 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3502 if(m_items[i] == NULL)
3503 continue;
3505 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3508 if(target == this)
3510 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3512 if(m_items[i] == NULL)
3513 continue;
3515 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3517 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3519 if(m_items[i] == NULL)
3520 continue;
3522 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3526 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3529 void Player::DestroyForPlayer( Player *target ) const
3531 Unit::DestroyForPlayer( target );
3533 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3535 if(m_items[i] == NULL)
3536 continue;
3538 m_items[i]->DestroyForPlayer( target );
3541 if(target == this)
3543 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3545 if(m_items[i] == NULL)
3546 continue;
3548 m_items[i]->DestroyForPlayer( target );
3550 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3552 if(m_items[i] == NULL)
3553 continue;
3555 m_items[i]->DestroyForPlayer( target );
3560 bool Player::HasSpell(uint32 spell) const
3562 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3563 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3564 !itr->second->disabled);
3567 bool Player::HasActiveSpell(uint32 spell) const
3569 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3570 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3571 itr->second->active && !itr->second->disabled);
3574 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3576 if (!trainer_spell)
3577 return TRAINER_SPELL_RED;
3579 if (!trainer_spell->learnedSpell)
3580 return TRAINER_SPELL_RED;
3582 // known spell
3583 if(HasSpell(trainer_spell->learnedSpell))
3584 return TRAINER_SPELL_GRAY;
3586 // check race/class requirement
3587 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3588 return TRAINER_SPELL_RED;
3590 // check level requirement
3591 if(getLevel() < trainer_spell->reqLevel)
3592 return TRAINER_SPELL_RED;
3594 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3596 // check prev.rank requirement
3597 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3598 return TRAINER_SPELL_RED;
3600 // check additional spell requirement
3601 if(spell_chain->req && !HasSpell(spell_chain->req))
3602 return TRAINER_SPELL_RED;
3605 // check skill requirement
3606 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3607 return TRAINER_SPELL_RED;
3609 // exist, already checked at loading
3610 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3612 // secondary prof. or not prof. spell
3613 uint32 skill = spell->EffectMiscValue[1];
3615 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3616 return TRAINER_SPELL_GREEN;
3618 // check primary prof. limit
3619 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3620 return TRAINER_SPELL_RED;
3622 return TRAINER_SPELL_GREEN;
3625 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3627 uint32 guid = GUID_LOPART(playerguid);
3629 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3630 // bones will be deleted by corpse/bones deleting thread shortly
3631 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3633 // remove from guild
3634 uint32 guildId = GetGuildIdFromDB(playerguid);
3635 if(guildId != 0)
3637 Guild* guild = objmgr.GetGuildById(guildId);
3638 if(guild)
3639 guild->DelMember(guid);
3642 // remove from arena teams
3643 LeaveAllArenaTeams(playerguid);
3645 // the player was uninvited already on logout so just remove from group
3646 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3647 if(resultGroup)
3649 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3650 delete resultGroup;
3651 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3652 if(group)
3654 RemoveFromGroup(group, playerguid);
3658 // remove signs from petitions (also remove petitions if owner);
3659 RemovePetitionsAndSigns(playerguid, 10);
3661 // return back all mails with COD and Item 0 1 2 3 4 5 6
3662 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);
3663 if(resultMail)
3667 Field *fields = resultMail->Fetch();
3669 uint32 mail_id = fields[0].GetUInt32();
3670 uint16 mailTemplateId= fields[1].GetUInt16();
3671 uint32 sender = fields[2].GetUInt32();
3672 std::string subject = fields[3].GetCppString();
3673 uint32 itemTextId = fields[4].GetUInt32();
3674 uint32 money = fields[5].GetUInt32();
3675 bool has_items = fields[6].GetBool();
3677 //we can return mail now
3678 //so firstly delete the old one
3679 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3681 MailItemsInfo mi;
3682 if(has_items)
3684 // data needs to be at first place for Item::LoadFromDB
3685 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);
3686 if(resultItems)
3690 Field *fields2 = resultItems->Fetch();
3692 uint32 item_guidlow = fields2[1].GetUInt32();
3693 uint32 item_template = fields2[2].GetUInt32();
3695 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3696 if(!itemProto)
3698 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3699 continue;
3702 Item *pItem = NewItemOrBag(itemProto);
3703 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3705 pItem->FSetState(ITEM_REMOVED);
3706 pItem->SaveToDB(); // it also deletes item object !
3707 continue;
3710 mi.AddItem(item_guidlow, item_template, pItem);
3712 while (resultItems->NextRow());
3714 delete resultItems;
3718 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3720 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3722 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3724 while (resultMail->NextRow());
3726 delete resultMail;
3729 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3730 // Get guids of character's pets, will deleted in transaction
3731 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3733 // NOW we can finally clear other DB data related to character
3734 CharacterDatabase.BeginTransaction();
3735 if (resultPets)
3739 Field *fields3 = resultPets->Fetch();
3740 uint32 petguidlow = fields3[0].GetUInt32();
3741 Pet::DeleteFromDB(petguidlow);
3742 } while (resultPets->NextRow());
3743 delete resultPets;
3746 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3747 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3748 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3749 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3750 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3751 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3752 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3753 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3754 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3755 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3756 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3757 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3758 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3759 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3760 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3761 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3762 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3763 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3764 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3765 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3766 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3767 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3768 CharacterDatabase.CommitTransaction();
3770 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3771 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3774 void Player::SetMovement(PlayerMovementType pType)
3776 WorldPacket data;
3777 switch(pType)
3779 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3780 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3781 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3782 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3783 default:
3784 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3785 return;
3787 data.append(GetPackGUID());
3788 data << uint32(0);
3789 GetSession()->SendPacket( &data );
3792 /* Preconditions:
3793 - a resurrectable corpse must not be loaded for the player (only bones)
3794 - the player must be in world
3796 void Player::BuildPlayerRepop()
3798 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3799 data.append(GetPackGUID());
3800 GetSession()->SendPacket(&data);
3802 if(getRace() == RACE_NIGHTELF)
3803 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)
3804 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3806 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3807 // there must be SMSG.STOP_MIRROR_TIMER
3808 // there we must send 888 opcode
3810 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3811 if(GetCorpse())
3813 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3814 assert(false);
3817 // create a corpse and place it at the player's location
3818 CreateCorpse();
3819 Corpse *corpse = GetCorpse();
3820 if(!corpse)
3822 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3823 return;
3825 GetMap()->Add(corpse);
3827 // convert player body to ghost
3828 SetHealth( 1 );
3830 SetMovement(MOVE_WATER_WALK);
3831 if(!GetSession()->isLogingOut())
3832 SetMovement(MOVE_UNROOT);
3834 // BG - remove insignia related
3835 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3837 SendCorpseReclaimDelay();
3839 // to prevent cheating
3840 corpse->ResetGhostTime();
3842 StopMirrorTimers(); //disable timers(bars)
3844 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3846 // set and clear other
3847 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3850 void Player::SendDelayResponse(const uint32 ml_seconds)
3852 //FIXME: is this delay time arg really need? 50msec by default in code
3853 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3854 data << (uint32)time(NULL);
3855 data << (uint32)0;
3856 GetSession()->SendPacket( &data );
3859 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3861 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3862 data << uint32(-1);
3863 data << float(0);
3864 data << float(0);
3865 data << float(0);
3866 GetSession()->SendPacket(&data);
3868 // speed change, land walk
3870 // remove death flag + set aura
3871 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3872 if(getRace() == RACE_NIGHTELF)
3873 RemoveAurasDueToSpell(20584); // speed bonuses
3874 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3876 setDeathState(ALIVE);
3878 SetMovement(MOVE_LAND_WALK);
3879 SetMovement(MOVE_UNROOT);
3881 m_deathTimer = 0;
3883 // set health/powers (0- will be set in caller)
3884 if(restore_percent>0.0f)
3886 SetHealth(uint32(GetMaxHealth()*restore_percent));
3887 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3888 SetPower(POWER_RAGE, 0);
3889 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3892 // trigger update zone for alive state zone updates
3893 uint32 newzone, newarea;
3894 GetZoneAndAreaId(newzone,newarea);
3895 UpdateZone(newzone,newarea);
3897 // update visibility
3898 ObjectAccessor::UpdateVisibilityForPlayer(this);
3900 if(!applySickness)
3901 return;
3903 //Characters from level 1-10 are not affected by resurrection sickness.
3904 //Characters from level 11-19 will suffer from one minute of sickness
3905 //for each level they are above 10.
3906 //Characters level 20 and up suffer from ten minutes of sickness.
3907 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3909 if(int32(getLevel()) >= startLevel)
3911 // set resurrection sickness
3912 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3914 // not full duration
3915 if(int32(getLevel()) < startLevel+9)
3917 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3919 for(int i =0; i < 3; ++i)
3921 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3923 Aur->SetAuraDuration(delta*IN_MILISECONDS);
3924 Aur->SendAuraUpdate(false);
3931 void Player::KillPlayer()
3933 SetMovement(MOVE_ROOT);
3935 StopMirrorTimers(); //disable timers(bars)
3937 setDeathState(CORPSE);
3938 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3940 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3941 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3943 // 6 minutes until repop at graveyard
3944 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
3946 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3948 // don't create corpse at this moment, player might be falling
3950 // update visibility
3951 ObjectAccessor::UpdateObjectVisibility(this);
3954 void Player::CreateCorpse()
3956 // prevent existence 2 corpse for player
3957 SpawnCorpseBones();
3959 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3961 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3962 SetPvPDeath(false);
3964 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
3966 delete corpse;
3967 return;
3970 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3971 _pb = GetUInt32Value(PLAYER_BYTES);
3972 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3974 uint8 race = (uint8)(_uf);
3975 uint8 skin = (uint8)(_pb);
3976 uint8 face = (uint8)(_pb >> 8);
3977 uint8 hairstyle = (uint8)(_pb >> 16);
3978 uint8 haircolor = (uint8)(_pb >> 24);
3979 uint8 facialhair = (uint8)(_pb2);
3981 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3982 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3984 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3985 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3987 uint32 flags = CORPSE_FLAG_UNK2;
3988 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3989 flags |= CORPSE_FLAG_HIDE_HELM;
3990 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3991 flags |= CORPSE_FLAG_HIDE_CLOAK;
3992 if(InBattleGround() && !InArena())
3993 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3994 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3996 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3998 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4000 uint32 iDisplayID;
4001 uint16 iIventoryType;
4002 uint32 _cfi;
4003 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
4005 if(m_items[i])
4007 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4008 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4010 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4011 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4015 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4016 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4017 assert(entry);
4018 if(entry->map_type != MAP_BATTLEGROUND)
4019 corpse->SaveToDB();
4021 // register for player, but not show
4022 ObjectAccessor::Instance().AddCorpse(corpse);
4025 void Player::SpawnCorpseBones()
4027 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4028 SaveToDB(); // prevent loading as ghost without corpse
4031 Corpse* Player::GetCorpse() const
4033 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4036 void Player::DurabilityLossAll(double percent, bool inventory)
4038 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4039 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4040 DurabilityLoss(pItem,percent);
4042 if(inventory)
4044 // bags not have durability
4045 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4047 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4048 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4049 DurabilityLoss(pItem,percent);
4051 // keys not have durability
4052 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4054 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4055 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4056 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4057 if(Item* pItem = GetItemByPos( i, j ))
4058 DurabilityLoss(pItem,percent);
4062 void Player::DurabilityLoss(Item* item, double percent)
4064 if(!item )
4065 return;
4067 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4069 if(!pMaxDurability)
4070 return;
4072 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4074 if(pDurabilityLoss < 1 )
4075 pDurabilityLoss = 1;
4077 DurabilityPointsLoss(item,pDurabilityLoss);
4080 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4082 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
4083 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4084 DurabilityPointsLoss(pItem,points);
4086 if(inventory)
4088 // bags not have durability
4089 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4091 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
4092 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4093 DurabilityPointsLoss(pItem,points);
4095 // keys not have durability
4096 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4098 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4099 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4100 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
4101 if(Item* pItem = GetItemByPos( i, j ))
4102 DurabilityPointsLoss(pItem,points);
4106 void Player::DurabilityPointsLoss(Item* item, int32 points)
4108 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4109 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4110 int32 pNewDurability = pOldDurability - points;
4112 if (pNewDurability < 0)
4113 pNewDurability = 0;
4114 else if (pNewDurability > pMaxDurability)
4115 pNewDurability = pMaxDurability;
4117 if (pOldDurability != pNewDurability)
4119 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4120 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4121 _ApplyItemMods(item,item->GetSlot(), false);
4123 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4125 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4126 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4127 _ApplyItemMods(item,item->GetSlot(), true);
4129 item->SetState(ITEM_CHANGED, this);
4133 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4135 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4136 DurabilityPointsLoss(pItem,1);
4139 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4141 uint32 TotalCost = 0;
4142 // equipped, backpack, bags itself
4143 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
4144 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4146 // bank, buyback and keys not repaired
4148 // items in inventory bags
4149 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4150 for(int i = 0; i < MAX_BAG_SIZE; i++)
4151 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4152 return TotalCost;
4155 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4157 Item* item = GetItemByPos(pos);
4159 uint32 TotalCost = 0;
4160 if(!item)
4161 return TotalCost;
4163 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4164 if(!maxDurability)
4165 return TotalCost;
4167 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4169 if(cost)
4171 uint32 LostDurability = maxDurability - curDurability;
4172 if(LostDurability>0)
4174 ItemPrototype const *ditemProto = item->GetProto();
4176 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4177 if(!dcost)
4179 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4180 return TotalCost;
4183 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4184 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4185 if(!dQualitymodEntry)
4187 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4188 return TotalCost;
4191 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4192 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4194 costs = uint32(costs * discountMod);
4196 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4197 costs = 1;
4199 if (guildBank)
4201 if (GetGuildId()==0)
4203 DEBUG_LOG("You are not member of a guild");
4204 return TotalCost;
4207 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4208 if (!pGuild)
4209 return TotalCost;
4211 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4213 DEBUG_LOG("You do not have rights to withdraw for repairs");
4214 return TotalCost;
4217 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4219 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4220 return TotalCost;
4223 if (pGuild->GetGuildBankMoney() < costs)
4225 DEBUG_LOG("There is not enough money in bank");
4226 return TotalCost;
4229 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4230 TotalCost = costs;
4232 else if (GetMoney() < costs)
4234 DEBUG_LOG("You do not have enough money");
4235 return TotalCost;
4237 else
4238 ModifyMoney( -int32(costs) );
4242 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4243 item->SetState(ITEM_CHANGED, this);
4245 // reapply mods for total broken and repaired item if equipped
4246 if(IsEquipmentPos(pos) && !curDurability)
4247 _ApplyItemMods(item,pos & 255, true);
4248 return TotalCost;
4251 void Player::RepopAtGraveyard()
4253 // note: this can be called also when the player is alive
4254 // for example from WorldSession::HandleMovementOpcodes
4256 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4258 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4259 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4261 ResurrectPlayer(0.5f);
4262 SpawnCorpseBones();
4265 WorldSafeLocsEntry const *ClosestGrave = NULL;
4267 // Special handle for battleground maps
4268 if( BattleGround *bg = GetBattleGround() )
4269 ClosestGrave = bg->GetClosestGraveYard(this);
4270 else
4271 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4273 // stop countdown until repop
4274 m_deathTimer = 0;
4276 // if no grave found, stay at the current location
4277 // and don't show spirit healer location
4278 if(ClosestGrave)
4280 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4281 if(isDead()) // not send if alive, because it used in TeleportTo()
4283 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4284 data << ClosestGrave->map_id;
4285 data << ClosestGrave->x;
4286 data << ClosestGrave->y;
4287 data << ClosestGrave->z;
4288 GetSession()->SendPacket(&data);
4293 void Player::JoinedChannel(Channel *c)
4295 m_channels.push_back(c);
4298 void Player::LeftChannel(Channel *c)
4300 m_channels.remove(c);
4303 void Player::CleanupChannels()
4305 while(!m_channels.empty())
4307 Channel* ch = *m_channels.begin();
4308 m_channels.erase(m_channels.begin()); // remove from player's channel list
4309 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4310 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4311 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4314 sLog.outDebug("Player: channels cleaned up!");
4317 void Player::UpdateLocalChannels(uint32 newZone )
4319 if(m_channels.empty())
4320 return;
4322 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4323 if(!current_zone)
4324 return;
4326 ChannelMgr* cMgr = channelMgr(GetTeam());
4327 if(!cMgr)
4328 return;
4330 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4332 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4334 next = i; ++next;
4336 // skip non built-in channels
4337 if(!(*i)->IsConstant())
4338 continue;
4340 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4341 if(!ch)
4342 continue;
4344 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4345 continue;
4347 // new channel
4348 char new_channel_name_buf[100];
4349 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4350 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4352 if((*i)!=new_channel)
4354 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4356 // leave old channel
4357 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4358 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4359 LeftChannel(*i); // remove from player's channel list
4360 cMgr->LeftChannel(name); // delete if empty
4363 sLog.outDebug("Player: channels cleaned up!");
4366 void Player::LeaveLFGChannel()
4368 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4370 if((*i)->IsLFG())
4372 (*i)->Leave(GetGUID());
4373 break;
4378 void Player::UpdateDefense()
4380 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4382 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4384 // update dependent from defense skill part
4385 UpdateDefenseBonusesMod();
4389 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4391 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4393 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4394 return;
4397 float val = 1.0f;
4399 switch(modType)
4401 case FLAT_MOD:
4402 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4403 break;
4404 case PCT_MOD:
4405 if(amount <= -100.0f)
4406 amount = -200.0f;
4408 val = (100.0f + amount) / 100.0f;
4409 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4410 break;
4413 if(!CanModifyStats())
4414 return;
4416 switch(modGroup)
4418 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4419 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4420 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4421 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4422 default: break;
4426 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4428 if(modGroup >= BASEMOD_END || modType > MOD_END)
4430 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4431 return 0.0f;
4434 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4435 return 0.0f;
4437 return m_auraBaseMod[modGroup][modType];
4440 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4442 if(modGroup >= BASEMOD_END)
4444 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4445 return 0.0f;
4448 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4449 return 0.0f;
4451 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4454 uint32 Player::GetShieldBlockValue() const
4456 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4458 value = (value < 0) ? 0 : value;
4460 return uint32(value);
4463 float Player::GetMeleeCritFromAgility()
4465 uint32 level = getLevel();
4466 uint32 pclass = getClass();
4468 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4470 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4471 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4472 if (critBase==NULL || critRatio==NULL)
4473 return 0.0f;
4475 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4476 return crit*100.0f;
4479 float Player::GetDodgeFromAgility()
4481 // Table for base dodge values
4482 float dodge_base[MAX_CLASSES] = {
4483 0.0075f, // Warrior
4484 0.00652f, // Paladin
4485 -0.0545f, // Hunter
4486 -0.0059f, // Rogue
4487 0.03183f, // Priest
4488 0.0114f, // DK
4489 0.0167f, // Shaman
4490 0.034575f, // Mage
4491 0.02011f, // Warlock
4492 0.0f, // ??
4493 -0.0187f // Druid
4495 // Crit/agility to dodge/agility coefficient multipliers
4496 float crit_to_dodge[MAX_CLASSES] = {
4497 1.1f, // Warrior
4498 1.0f, // Paladin
4499 1.6f, // Hunter
4500 2.0f, // Rogue
4501 1.0f, // Priest
4502 1.0f, // DK?
4503 1.0f, // Shaman
4504 1.0f, // Mage
4505 1.0f, // Warlock
4506 0.0f, // ??
4507 1.7f // Druid
4510 uint32 level = getLevel();
4511 uint32 pclass = getClass();
4513 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4515 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4516 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4517 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4518 return 0.0f;
4520 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4521 return dodge*100.0f;
4524 float Player::GetSpellCritFromIntellect()
4526 uint32 level = getLevel();
4527 uint32 pclass = getClass();
4529 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4531 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4532 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4533 if (critBase==NULL || critRatio==NULL)
4534 return 0.0f;
4536 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4537 return crit*100.0f;
4540 float Player::GetRatingCoefficient(CombatRating cr) const
4542 uint32 level = getLevel();
4544 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4546 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4547 if (Rating == NULL)
4548 return 1.0f; // By default use minimum coefficient (not must be called)
4550 return Rating->ratio;
4553 float Player::GetRatingBonusValue(CombatRating cr) const
4555 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4558 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4560 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4561 if (melee>33.0f) melee = 33.0f;
4562 return uint32 (melee * damage /100.0f);
4565 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4567 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4568 if (ranged>33.0f) ranged=33.0f;
4569 return uint32 (ranged * damage /100.0f);
4572 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4574 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4575 // In wow script resilience limited to 33%
4576 if (spell>33.0f)
4577 spell = 33.0f;
4578 return uint32 (spell * damage / 100.0f);
4581 uint32 Player::GetDotDamageReduction(uint32 damage) const
4583 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4584 // Dot resilience not limited (limit it by 100%)
4585 if (spellDot > 100.0f)
4586 spellDot = 100.0f;
4587 return uint32 (spellDot * damage / 100.0f);
4590 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4592 switch (attType)
4594 case BASE_ATTACK:
4595 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4596 case OFF_ATTACK:
4597 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4598 default:
4599 break;
4601 return 0.0f;
4604 float Player::OCTRegenHPPerSpirit()
4606 uint32 level = getLevel();
4607 uint32 pclass = getClass();
4609 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4611 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4612 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4613 if (baseRatio==NULL || moreRatio==NULL)
4614 return 0.0f;
4616 // Formula from PaperDollFrame script
4617 float spirit = GetStat(STAT_SPIRIT);
4618 float baseSpirit = spirit;
4619 if (baseSpirit>50) baseSpirit = 50;
4620 float moreSpirit = spirit - baseSpirit;
4621 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4622 return regen;
4625 float Player::OCTRegenMPPerSpirit()
4627 uint32 level = getLevel();
4628 uint32 pclass = getClass();
4630 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4632 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4633 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4634 if (moreRatio==NULL)
4635 return 0.0f;
4637 // Formula get from PaperDollFrame script
4638 float spirit = GetStat(STAT_SPIRIT);
4639 float regen = spirit * moreRatio->ratio;
4640 return regen;
4643 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4645 m_baseRatingValue[cr]+=(apply ? value : -value);
4647 int32 amount = uint32(m_baseRatingValue[cr]);
4648 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4649 // stat used stored in miscValueB for this aura
4650 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4651 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4652 if ((*i)->GetMiscValue() & (1<<cr))
4653 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4654 if (amount < 0)
4655 amount = 0;
4656 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4658 float RatingCoeffecient = GetRatingCoefficient(cr);
4659 float RatingChange = 0.0f;
4661 bool affectStats = CanModifyStats();
4663 switch (cr)
4665 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4666 case CR_DEFENSE_SKILL:
4667 UpdateDefenseBonusesMod();
4668 break;
4669 case CR_DODGE:
4670 UpdateDodgePercentage();
4671 break;
4672 case CR_PARRY:
4673 UpdateParryPercentage();
4674 break;
4675 case CR_BLOCK:
4676 UpdateBlockPercentage();
4677 break;
4678 case CR_HIT_MELEE:
4679 UpdateMeleeHitChances();
4680 break;
4681 case CR_HIT_RANGED:
4682 UpdateRangedHitChances();
4683 break;
4684 case CR_HIT_SPELL:
4685 UpdateSpellHitChances();
4686 break;
4687 case CR_CRIT_MELEE:
4688 if(affectStats)
4690 UpdateCritPercentage(BASE_ATTACK);
4691 UpdateCritPercentage(OFF_ATTACK);
4693 break;
4694 case CR_CRIT_RANGED:
4695 if(affectStats)
4696 UpdateCritPercentage(RANGED_ATTACK);
4697 break;
4698 case CR_CRIT_SPELL:
4699 if(affectStats)
4700 UpdateAllSpellCritChances();
4701 break;
4702 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4703 case CR_HIT_TAKEN_RANGED:
4704 break;
4705 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4706 break;
4707 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4708 case CR_CRIT_TAKEN_RANGED:
4709 break;
4710 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4711 break;
4712 case CR_HASTE_MELEE:
4713 RatingChange = value / RatingCoeffecient;
4714 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4715 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4716 break;
4717 case CR_HASTE_RANGED:
4718 RatingChange = value / RatingCoeffecient;
4719 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4720 break;
4721 case CR_HASTE_SPELL:
4722 RatingChange = value / RatingCoeffecient;
4723 ApplyCastTimePercentMod(RatingChange,apply);
4724 break;
4725 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4726 case CR_WEAPON_SKILL_OFFHAND:
4727 case CR_WEAPON_SKILL_RANGED:
4728 break;
4729 case CR_EXPERTISE:
4730 if(affectStats)
4732 UpdateExpertise(BASE_ATTACK);
4733 UpdateExpertise(OFF_ATTACK);
4735 break;
4739 void Player::SetRegularAttackTime()
4741 for(int i = 0; i < MAX_ATTACK; ++i)
4743 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4744 if(tmpitem && !tmpitem->IsBroken())
4746 ItemPrototype const *proto = tmpitem->GetProto();
4747 if(proto->Delay)
4748 SetAttackTime(WeaponAttackType(i), proto->Delay);
4749 else
4750 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4755 //skill+step, checking for max value
4756 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4758 if(!skill_id)
4759 return false;
4761 uint16 i=0;
4762 for (; i < PLAYER_MAX_SKILLS; i++)
4763 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4764 break;
4766 if(i>=PLAYER_MAX_SKILLS)
4767 return false;
4769 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4770 uint32 value = SKILL_VALUE(data);
4771 uint32 max = SKILL_MAX(data);
4773 if ((!max) || (!value) || (value >= max))
4774 return false;
4776 if (value*512 < max*urand(0,512))
4778 uint32 new_value = value+step;
4779 if(new_value > max)
4780 new_value = max;
4782 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4783 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4784 return true;
4787 return false;
4790 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4792 if ( SkillValue >= GrayLevel )
4793 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4794 if ( SkillValue >= GreenLevel )
4795 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4796 if ( SkillValue >= YellowLevel )
4797 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4798 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4801 bool Player::UpdateCraftSkill(uint32 spellid)
4803 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4805 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4806 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4808 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4810 if(_spell_idx->second->skillId)
4812 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4814 // Alchemy Discoveries here
4815 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4816 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4818 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4819 learnSpell(discoveredSpell,false);
4822 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4824 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4825 _spell_idx->second->max_value,
4826 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4827 _spell_idx->second->min_value),
4828 craft_skill_gain);
4831 return false;
4834 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4836 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4838 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4840 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4841 switch (SkillId)
4843 case SKILL_HERBALISM:
4844 case SKILL_LOCKPICKING:
4845 case SKILL_JEWELCRAFTING:
4846 case SKILL_INSCRIPTION:
4847 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4848 case SKILL_SKINNING:
4849 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4850 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4851 else
4852 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4853 case SKILL_MINING:
4854 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4855 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4856 else
4857 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4859 return false;
4862 bool Player::UpdateFishingSkill()
4864 sLog.outDebug("UpdateFishingSkill");
4866 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4868 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4870 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4872 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4875 // levels sync. with spell requirement for skill levels to learn
4876 // bonus abilities in sSkillLineAbilityStore
4877 // Used only to avoid scan DBC at each skill grow
4878 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4880 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4882 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4883 if ( !SkillId )
4884 return false;
4886 if(Chance <= 0) // speedup in 0 chance case
4888 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4889 return false;
4892 uint16 i=0;
4893 for (; i < PLAYER_MAX_SKILLS; i++)
4894 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4895 if ( i >= PLAYER_MAX_SKILLS )
4896 return false;
4898 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4899 uint16 SkillValue = SKILL_VALUE(data);
4900 uint16 MaxValue = SKILL_MAX(data);
4902 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4903 return false;
4905 int32 Roll = irand(1,1000);
4907 if ( Roll <= Chance )
4909 uint32 new_value = SkillValue+step;
4910 if(new_value > MaxValue)
4911 new_value = MaxValue;
4913 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4914 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4916 if((SkillValue < *bsl && new_value >= *bsl))
4918 learnSkillRewardedSpells( SkillId, new_value);
4919 break;
4922 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
4923 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4924 return true;
4927 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4928 return false;
4931 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4933 // no skill gain in pvp
4934 Unit *pVictim = getVictim();
4935 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4936 return;
4938 if(IsInFeralForm())
4939 return; // always maximized SKILL_FERAL_COMBAT in fact
4941 if(m_form == FORM_TREE)
4942 return; // use weapon but not skill up
4944 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4946 switch(attType)
4948 case BASE_ATTACK:
4950 Item *tmpitem = GetWeaponForAttack(attType,true);
4952 if (!tmpitem)
4953 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4954 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4955 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4956 break;
4958 case OFF_ATTACK:
4959 case RANGED_ATTACK:
4961 Item *tmpitem = GetWeaponForAttack(attType,true);
4962 if (tmpitem)
4963 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4964 break;
4967 UpdateAllCritPercentages();
4970 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
4972 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4973 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4974 uint32 moblevel = pVictim->getLevelForTarget(this);
4975 if(moblevel < greylevel)
4976 return;
4978 if (moblevel > plevel + 5)
4979 moblevel = plevel + 5;
4981 uint32 lvldif = moblevel - greylevel;
4982 if(lvldif < 3)
4983 lvldif = 3;
4985 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4986 if(skilldif <= 0)
4987 return;
4989 float chance = float(3 * lvldif * skilldif) / plevel;
4990 if(!defence)
4992 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4993 chance *= 0.1f * GetStat(STAT_INTELLECT);
4996 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4998 if(roll_chance_f(chance))
5000 if(defence)
5001 UpdateDefense();
5002 else
5003 UpdateWeaponSkill(attType);
5005 else
5006 return;
5009 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5011 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5012 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5014 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5015 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5016 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5018 if(talent) // permanent bonus stored in high part
5019 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5020 else // temporary/item bonus stored in low part
5021 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5022 return;
5026 void Player::UpdateSkillsForLevel()
5028 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5029 uint32 maxSkill = GetMaxSkillValueForLevel();
5031 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5033 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5034 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5036 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5038 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5039 if(!pSkill)
5040 continue;
5042 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5043 continue;
5045 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5046 uint32 max = SKILL_MAX(data);
5047 uint32 val = SKILL_VALUE(data);
5049 /// update only level dependent max skill values
5050 if(max!=1)
5052 /// miximize skill always
5053 if(alwaysMaxSkill)
5054 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5055 /// update max skill value if current max skill not maximized
5056 else if(max != maxconfskill)
5057 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5062 void Player::UpdateSkillsToMaxSkillsForLevel()
5064 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5065 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5067 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5068 if( IsProfessionOrRidingSkill(pskill))
5069 continue;
5070 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5072 uint32 max = SKILL_MAX(data);
5074 if(max > 1)
5075 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5077 if(pskill == SKILL_DEFENSE)
5078 UpdateDefenseBonusesMod();
5082 // This functions sets a skill line value (and adds if doesn't exist yet)
5083 // To "remove" a skill line, set it's values to zero
5084 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5086 if(!id)
5087 return;
5089 uint16 i=0;
5090 for (; i < PLAYER_MAX_SKILLS; i++)
5091 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5093 if(i<PLAYER_MAX_SKILLS) //has skill
5095 if(currVal)
5097 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5098 learnSkillRewardedSpells(id, currVal);
5099 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5100 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5102 else //remove
5104 // clear skill fields
5105 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5106 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5107 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5109 // remove all spells that related to this skill
5110 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5111 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5112 if (pAbility->skillId==id)
5113 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5116 else if(currVal) //add
5118 for (i=0; i < PLAYER_MAX_SKILLS; i++)
5119 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5121 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5122 if(!pSkill)
5124 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5125 return;
5127 // enable unlearn button for primary professions only
5128 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5129 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5130 else
5131 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5132 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5133 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5134 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5136 // apply skill bonuses
5137 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5139 // temporary bonuses
5140 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5141 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5142 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5143 (*i)->ApplyModifier(true);
5145 // permanent bonuses
5146 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5147 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5148 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5149 (*i)->ApplyModifier(true);
5151 // Learn all spells for skill
5152 learnSkillRewardedSpells(id, currVal);
5153 return;
5158 bool Player::HasSkill(uint32 skill) const
5160 if(!skill)return false;
5161 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5163 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5165 return true;
5168 return false;
5171 uint16 Player::GetSkillValue(uint32 skill) const
5173 if(!skill)
5174 return 0;
5176 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5178 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5180 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5182 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5183 result += SKILL_TEMP_BONUS(bonus);
5184 result += SKILL_PERM_BONUS(bonus);
5185 return result < 0 ? 0 : result;
5188 return 0;
5191 uint16 Player::GetMaxSkillValue(uint32 skill) const
5193 if(!skill)return 0;
5194 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5196 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5198 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5200 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5201 result += SKILL_TEMP_BONUS(bonus);
5202 result += SKILL_PERM_BONUS(bonus);
5203 return result < 0 ? 0 : result;
5206 return 0;
5209 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5211 if(!skill)return 0;
5212 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5214 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5216 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5219 return 0;
5222 uint16 Player::GetBaseSkillValue(uint32 skill) const
5224 if(!skill)return 0;
5225 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5227 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5229 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5230 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5231 return result < 0 ? 0 : result;
5234 return 0;
5237 uint16 Player::GetPureSkillValue(uint32 skill) const
5239 if(!skill)return 0;
5240 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5242 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5244 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5247 return 0;
5250 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5252 if(!skill)
5253 return 0;
5255 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5257 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5259 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5263 return 0;
5266 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5268 if(!skill)
5269 return 0;
5271 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5273 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5275 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5279 return 0;
5282 void Player::SendInitialActionButtons()
5284 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5286 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5287 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5289 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5290 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5292 data << uint16(itr->second.action);
5293 data << uint8(itr->second.misc);
5294 data << uint8(itr->second.type);
5296 else
5298 data << uint32(0);
5302 GetSession()->SendPacket( &data );
5303 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5306 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5308 if(button >= MAX_ACTION_BUTTONS)
5310 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5311 return false;
5314 // check cheating with adding non-known spells to action bar
5315 if(type==ACTION_BUTTON_SPELL)
5317 if(!sSpellStore.LookupEntry(action))
5319 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5320 return false;
5323 if(!HasSpell(action))
5325 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5326 return false;
5330 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5332 if (buttonItr==m_actionButtons.end())
5333 { // just add new button
5334 m_actionButtons[button] = ActionButton(action,type,misc);
5336 else
5337 { // change state of current button
5338 ActionButtonUpdateState uState = buttonItr->second.uState;
5339 buttonItr->second = ActionButton(action,type,misc);
5340 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5343 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5344 return true;
5347 void Player::removeActionButton(uint8 button)
5349 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5350 if (buttonItr==m_actionButtons.end())
5351 return;
5353 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5354 m_actionButtons.erase(buttonItr); // new and not saved
5355 else
5356 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5358 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5361 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5363 // prevent crash when a bad coord is sent by the client
5364 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5366 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5367 return false;
5370 Map *m = GetMap();
5372 const float old_x = GetPositionX();
5373 const float old_y = GetPositionY();
5374 const float old_z = GetPositionZ();
5375 const float old_r = GetOrientation();
5377 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5379 if (teleport || old_x != x || old_y != y || old_z != z)
5380 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5381 else
5382 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5384 // move and update visible state if need
5385 m->PlayerRelocation(this, x, y, z, orientation);
5387 // reread after Map::Relocation
5388 m = GetMap();
5389 x = GetPositionX();
5390 y = GetPositionY();
5391 z = GetPositionZ();
5393 // group update
5394 if(GetGroup() && (old_x != x || old_y != y))
5395 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5398 // code block for underwater state update
5399 UpdateUnderwaterState(m, x, y, z);
5401 CheckExploreSystem();
5403 return true;
5406 void Player::SaveRecallPosition()
5408 m_recallMap = GetMapId();
5409 m_recallX = GetPositionX();
5410 m_recallY = GetPositionY();
5411 m_recallZ = GetPositionZ();
5412 m_recallO = GetOrientation();
5415 void Player::SendMessageToSet(WorldPacket *data, bool self)
5417 GetMap()->MessageBroadcast(this, data, self);
5420 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5422 GetMap()->MessageDistBroadcast(this, data, dist, self);
5425 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5427 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5430 void Player::SendDirectMessage(WorldPacket *data)
5432 GetSession()->SendPacket(data);
5435 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5437 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5438 data << uint32(CinematicSequenceId);
5439 SendDirectMessage(&data);
5442 void Player::SendMovieStart(uint32 MovieId)
5444 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5445 data << uint32(MovieId);
5446 SendDirectMessage(&data);
5449 void Player::CheckExploreSystem()
5451 if (!isAlive())
5452 return;
5454 if (isInFlight())
5455 return;
5457 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5458 if(areaFlag==0xffff)
5459 return;
5460 int offset = areaFlag / 32;
5462 if(offset >= 128)
5464 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);
5465 return;
5468 uint32 val = (uint32)(1 << (areaFlag % 32));
5469 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5471 if( !(currFields & val) )
5473 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5475 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5477 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5478 if(!p)
5480 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5482 else if(p->area_level > 0)
5484 uint32 area = p->ID;
5485 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5487 SendExplorationExperience(area,0);
5489 else
5491 int32 diff = int32(getLevel()) - p->area_level;
5492 uint32 XP = 0;
5493 if (diff < -5)
5495 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5497 else if (diff > 5)
5499 int32 exploration_percent = (100-((diff-5)*5));
5500 if (exploration_percent > 100)
5501 exploration_percent = 100;
5502 else if (exploration_percent < 0)
5503 exploration_percent = 0;
5505 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5507 else
5509 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5512 GiveXP( XP, NULL );
5513 SendExplorationExperience(area,XP);
5515 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5520 uint32 Player::TeamForRace(uint8 race)
5522 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5523 if(!rEntry)
5525 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5526 return ALLIANCE;
5529 switch(rEntry->TeamID)
5531 case 7: return ALLIANCE;
5532 case 1: return HORDE;
5535 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5536 return ALLIANCE;
5539 uint32 Player::getFactionForRace(uint8 race)
5541 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5542 if(!rEntry)
5544 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5545 return 0;
5548 return rEntry->FactionID;
5551 void Player::setFactionForRace(uint8 race)
5553 m_team = TeamForRace(race);
5554 setFaction( getFactionForRace(race) );
5557 ReputationRank Player::GetReputationRank(uint32 faction) const
5559 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5560 return GetReputationMgr().GetRank(factionEntry);
5563 //Calculate total reputation percent player gain with quest/creature level
5564 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5566 float percent = 100.0f;
5568 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5570 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5571 percent *= rate;
5573 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5575 percent += rep > 0 ? repMod : -repMod;
5577 if(percent <= 0.0f)
5578 return 0;
5580 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5583 //Calculates how many reputation points player gains in victim's enemy factions
5584 void Player::RewardReputation(Unit *pVictim, float rate)
5586 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5587 return;
5589 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5591 if(!Rep)
5592 return;
5594 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5596 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5597 donerep1 = int32(donerep1*rate);
5598 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5599 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5600 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5601 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5603 // Wiki: Team factions value divided by 2
5604 if(Rep->is_teamaward1)
5606 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5607 if(team1_factionEntry)
5608 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5612 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5614 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5615 donerep2 = int32(donerep2*rate);
5616 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5617 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5618 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5619 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5621 // Wiki: Team factions value divided by 2
5622 if(Rep->is_teamaward2)
5624 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5625 if(team2_factionEntry)
5626 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5631 //Calculate how many reputation points player gain with the quest
5632 void Player::RewardReputation(Quest const *pQuest)
5634 // quest reputation reward/loss
5635 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5637 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5639 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5640 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5641 if(factionEntry)
5642 GetReputationMgr().ModifyReputation(factionEntry, rep);
5646 // TODO: implement reputation spillover
5649 void Player::UpdateArenaFields(void)
5651 /* arena calcs go here */
5654 void Player::UpdateHonorFields()
5656 /// called when rewarding honor and at each save
5657 uint64 now = time(NULL);
5658 uint64 today = uint64(time(NULL) / DAY) * DAY;
5660 if(m_lastHonorUpdateTime < today)
5662 uint64 yesterday = today - DAY;
5664 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5666 // update yesterday's contribution
5667 if(m_lastHonorUpdateTime >= yesterday )
5669 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5671 // this is the first update today, reset today's contribution
5672 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5673 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5675 else
5677 // no honor/kills yesterday or today, reset
5678 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5679 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5683 m_lastHonorUpdateTime = now;
5686 ///Calculate the amount of honor gained based on the victim
5687 ///and the size of the group for which the honor is divided
5688 ///An exact honor value can also be given (overriding the calcs)
5689 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5691 // do not reward honor in arenas, but enable onkill spellproc
5692 if(InArena())
5694 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5695 return false;
5697 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5698 return false;
5700 return true;
5703 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5704 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5705 return false;
5707 uint64 victim_guid = 0;
5708 uint32 victim_rank = 0;
5710 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5711 UpdateHonorFields();
5713 if(honor <= 0)
5715 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5716 return false;
5718 victim_guid = uVictim->GetGUID();
5720 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5722 Player *pVictim = (Player *)uVictim;
5724 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5725 return false;
5727 float f = 1; //need for total kills (?? need more info)
5728 uint32 k_grey = 0;
5729 uint32 k_level = getLevel();
5730 uint32 v_level = pVictim->getLevel();
5733 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5734 // [0] Just name
5735 // [1..14] Alliance honor titles and player name
5736 // [15..28] Horde honor titles and player name
5737 // [29..38] Other title and player name
5738 // [39+] Nothing
5739 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5740 // Get Killer titles, CharTitlesEntry::bit_index
5741 // Ranks:
5742 // title[1..14] -> rank[5..18]
5743 // title[15..28] -> rank[5..18]
5744 // title[other] -> 0
5745 if (victim_title == 0)
5746 victim_guid = 0; // Don't show HK: <rank> message, only log.
5747 else if (victim_title < 15)
5748 victim_rank = victim_title + 4;
5749 else if (victim_title < 29)
5750 victim_rank = victim_title - 14 + 4;
5751 else
5752 victim_guid = 0; // Don't show HK: <rank> message, only log.
5755 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5757 if(v_level<=k_grey)
5758 return false;
5760 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5762 int32 v_rank =1; //need more info
5764 honor = ((f * diff_level * (190 + v_rank*10))/6);
5765 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5767 // count the number of playerkills in one day
5768 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5769 // and those in a lifetime
5770 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5772 else
5774 Creature *cVictim = (Creature *)uVictim;
5776 if (!cVictim->isRacialLeader())
5777 return false;
5779 honor = 100; // ??? need more info
5780 victim_rank = 19; // HK: Leader
5784 if (uVictim != NULL)
5786 honor *= sWorld.getRate(RATE_HONOR);
5788 if(groupsize > 1)
5789 honor /= groupsize;
5791 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5794 // honor - for show honor points in log
5795 // victim_guid - for show victim name in log
5796 // victim_rank [1..4] HK: <dishonored rank>
5797 // victim_rank [5..19] HK: <alliance\horde rank>
5798 // victim_rank [0,20+] HK: <>
5799 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5800 data << (uint32) honor;
5801 data << (uint64) victim_guid;
5802 data << (uint32) victim_rank;
5804 GetSession()->SendPacket(&data);
5806 // add honor points
5807 ModifyHonorPoints(int32(honor));
5809 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5810 return true;
5813 void Player::ModifyHonorPoints( int32 value )
5815 if(value < 0)
5817 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5818 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5819 else
5820 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5822 else
5823 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5826 void Player::ModifyArenaPoints( int32 value )
5828 if(value < 0)
5830 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5831 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5832 else
5833 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5835 else
5836 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5839 uint32 Player::GetGuildIdFromDB(uint64 guid)
5841 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5842 if(!result)
5843 return 0;
5845 uint32 id = result->Fetch()[0].GetUInt32();
5846 delete result;
5847 return id;
5850 uint32 Player::GetRankFromDB(uint64 guid)
5852 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5853 if( result )
5855 uint32 v = result->Fetch()[0].GetUInt32();
5856 delete result;
5857 return v;
5859 else
5860 return 0;
5863 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5865 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);
5866 if(!result)
5867 return 0;
5869 uint32 id = (*result)[0].GetUInt32();
5870 delete result;
5871 return id;
5874 uint32 Player::GetZoneIdFromDB(uint64 guid)
5876 uint32 guidLow = GUID_LOPART(guid);
5877 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5878 if (!result)
5879 return 0;
5880 Field* fields = result->Fetch();
5881 uint32 zone = fields[0].GetUInt32();
5882 delete result;
5884 if (!zone)
5886 // stored zone is zero, use generic and slow zone detection
5887 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5888 if( !result )
5889 return 0;
5890 fields = result->Fetch();
5891 uint32 map = fields[0].GetUInt32();
5892 float posx = fields[1].GetFloat();
5893 float posy = fields[2].GetFloat();
5894 float posz = fields[3].GetFloat();
5895 delete result;
5897 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5899 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5902 return zone;
5905 void Player::UpdateArea(uint32 newArea)
5907 // FFA_PVP flags are area and not zone id dependent
5908 // so apply them accordingly
5909 m_areaUpdateId = newArea;
5911 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
5913 if(area && (area->flags & AREA_FLAG_ARENA))
5915 if(!isGameMaster())
5916 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
5918 else
5920 // remove ffa flag only if not ffapvp realm
5921 // removal in sanctuaries and capitals is handled in zone update
5922 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
5923 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
5926 UpdateAreaDependentAuras(newArea);
5929 void Player::UpdateZone(uint32 newZone, uint32 newArea)
5931 if(m_zoneUpdateId != newZone)
5932 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
5934 m_zoneUpdateId = newZone;
5935 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
5937 // zone changed, so area changed as well, update it
5938 UpdateArea(newArea);
5940 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
5941 if(!zone)
5942 return;
5944 if (sWorld.getConfig(CONFIG_WEATHER))
5946 Weather *wth = sWorld.FindWeather(zone->ID);
5947 if(wth)
5949 wth->SendWeatherUpdateToPlayer(this);
5951 else
5953 if(!sWorld.AddWeather(zone->ID))
5955 // send fine weather packet to remove old zone's weather
5956 Weather::SendFineWeatherUpdateToPlayer(this);
5961 pvpInfo.inHostileArea =
5962 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
5963 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
5964 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
5965 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
5967 if(pvpInfo.inHostileArea) // in hostile area
5969 if(!IsPvP() || pvpInfo.endTimer != 0)
5970 UpdatePvP(true, true);
5972 else // in friendly area
5974 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
5975 pvpInfo.endTimer = time(0); // start toggle-off
5978 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
5980 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
5981 if(sWorld.IsFFAPvPRealm())
5982 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
5984 else
5986 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
5989 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
5991 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
5992 SetRestType(REST_TYPE_IN_CITY);
5993 InnEnter(time(0),GetMapId(),0,0,0);
5995 if(sWorld.IsFFAPvPRealm())
5996 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
5998 else // anywhere else
6000 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6002 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6004 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6006 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6007 SetRestType(REST_TYPE_NO);
6009 if(sWorld.IsFFAPvPRealm())
6010 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6013 else // not in tavern (leave city then)
6015 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6016 SetRestType(REST_TYPE_NO);
6018 // Set player to FFA PVP when not in rested environment.
6019 if(sWorld.IsFFAPvPRealm())
6020 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6025 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6026 // if player resurrected at teleport this will be applied in resurrect code
6027 if(isAlive())
6028 DestroyZoneLimitedItem( true, newZone );
6030 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6031 AutoUnequipOffhandIfNeed();
6033 // recent client version not send leave/join channel packets for built-in local channels
6034 UpdateLocalChannels( newZone );
6036 // group update
6037 if(GetGroup())
6038 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6040 UpdateZoneDependentAuras(newZone);
6043 //If players are too far way of duel flag... then player loose the duel
6044 void Player::CheckDuelDistance(time_t currTime)
6046 if(!duel)
6047 return;
6049 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6050 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6051 if(!obj)
6052 return;
6054 if(duel->outOfBound == 0)
6056 if(!IsWithinDistInMap(obj, 50))
6058 duel->outOfBound = currTime;
6060 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6061 GetSession()->SendPacket(&data);
6064 else
6066 if(IsWithinDistInMap(obj, 40))
6068 duel->outOfBound = 0;
6070 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6071 GetSession()->SendPacket(&data);
6073 else if(currTime >= (duel->outOfBound+10))
6075 DuelComplete(DUEL_FLED);
6080 void Player::DuelComplete(DuelCompleteType type)
6082 // duel not requested
6083 if(!duel)
6084 return;
6086 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6087 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6088 GetSession()->SendPacket(&data);
6089 duel->opponent->GetSession()->SendPacket(&data);
6091 if(type != DUEL_INTERUPTED)
6093 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6094 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6095 data << duel->opponent->GetName();
6096 data << GetName();
6097 SendMessageToSet(&data,true);
6100 // cool-down duel spell
6101 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6103 data<<GetGUID();
6104 data<<uint8(0x0);
6106 data<<(uint32)7266;
6107 data<<uint32(0x0);
6108 GetSession()->SendPacket(&data);
6109 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6110 data<<duel->opponent->GetGUID();
6111 data<<uint8(0x0);
6112 data<<(uint32)7266;
6113 data<<uint32(0x0);
6114 duel->opponent->GetSession()->SendPacket(&data);*/
6116 //Remove Duel Flag object
6117 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6118 if(obj)
6119 duel->initiator->RemoveGameObject(obj,true);
6121 /* remove auras */
6122 std::vector<uint32> auras2remove;
6123 AuraMap const& vAuras = duel->opponent->GetAuras();
6124 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6126 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6127 auras2remove.push_back(i->second->GetId());
6130 for(size_t i=0; i<auras2remove.size(); i++)
6131 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6133 auras2remove.clear();
6134 AuraMap const& auras = GetAuras();
6135 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6137 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6138 auras2remove.push_back(i->second->GetId());
6140 for(size_t i=0; i<auras2remove.size(); i++)
6141 RemoveAurasDueToSpell(auras2remove[i]);
6143 // cleanup combo points
6144 if(GetComboTarget()==duel->opponent->GetGUID())
6145 ClearComboPoints();
6146 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6147 ClearComboPoints();
6149 if(duel->opponent->GetComboTarget()==GetGUID())
6150 duel->opponent->ClearComboPoints();
6151 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6152 duel->opponent->ClearComboPoints();
6154 //cleanups
6155 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6156 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6157 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6158 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6160 delete duel->opponent->duel;
6161 duel->opponent->duel = NULL;
6162 delete duel;
6163 duel = NULL;
6166 //---------------------------------------------------------//
6168 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6170 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6171 return;
6173 // not apply/remove mods for broken item
6174 if(item->IsBroken())
6175 return;
6177 ItemPrototype const *proto = item->GetProto();
6179 if(!proto)
6180 return;
6182 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6184 uint32 attacktype = Player::GetAttackBySlot(slot);
6185 if(attacktype < MAX_ATTACK)
6186 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6188 _ApplyItemBonuses(proto,slot,apply);
6190 if( slot==EQUIPMENT_SLOT_RANGED )
6191 _ApplyAmmoBonuses();
6193 ApplyItemEquipSpell(item,apply);
6194 ApplyEnchantment(item, apply);
6196 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6197 CorrectMetaGemEnchants(slot, apply);
6199 sLog.outDebug("_ApplyItemMods complete.");
6202 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6204 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6205 return;
6207 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6209 uint32 statType = 0;
6210 int32 val = 0;
6212 if(proto->ScalingStatDistribution)
6214 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6216 statType = ssd->StatMod[i];
6218 if(uint32 modifier = ssd->Modifier[i])
6220 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6221 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6223 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6224 val = (multiplier * modifier) / 10000;
6229 else
6231 statType = proto->ItemStat[i].ItemStatType;
6232 val = proto->ItemStat[i].ItemStatValue;
6235 if(val == 0)
6236 continue;
6238 switch (statType)
6240 case ITEM_MOD_MANA:
6241 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6242 break;
6243 case ITEM_MOD_HEALTH: // modify HP
6244 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6245 break;
6246 case ITEM_MOD_AGILITY: // modify agility
6247 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6248 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6249 break;
6250 case ITEM_MOD_STRENGTH: //modify strength
6251 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6252 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6253 break;
6254 case ITEM_MOD_INTELLECT: //modify intellect
6255 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6256 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6257 break;
6258 case ITEM_MOD_SPIRIT: //modify spirit
6259 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6260 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6261 break;
6262 case ITEM_MOD_STAMINA: //modify stamina
6263 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6264 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6265 break;
6266 case ITEM_MOD_DEFENSE_SKILL_RATING:
6267 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6268 break;
6269 case ITEM_MOD_DODGE_RATING:
6270 ApplyRatingMod(CR_DODGE, int32(val), apply);
6271 break;
6272 case ITEM_MOD_PARRY_RATING:
6273 ApplyRatingMod(CR_PARRY, int32(val), apply);
6274 break;
6275 case ITEM_MOD_BLOCK_RATING:
6276 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6277 break;
6278 case ITEM_MOD_HIT_MELEE_RATING:
6279 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6280 break;
6281 case ITEM_MOD_HIT_RANGED_RATING:
6282 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6283 break;
6284 case ITEM_MOD_HIT_SPELL_RATING:
6285 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6286 break;
6287 case ITEM_MOD_CRIT_MELEE_RATING:
6288 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6289 break;
6290 case ITEM_MOD_CRIT_RANGED_RATING:
6291 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6292 break;
6293 case ITEM_MOD_CRIT_SPELL_RATING:
6294 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6295 break;
6296 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6297 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6298 break;
6299 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6300 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6301 break;
6302 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6303 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6304 break;
6305 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6306 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6307 break;
6308 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6309 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6310 break;
6311 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6312 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6313 break;
6314 case ITEM_MOD_HASTE_MELEE_RATING:
6315 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6316 break;
6317 case ITEM_MOD_HASTE_RANGED_RATING:
6318 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6319 break;
6320 case ITEM_MOD_HASTE_SPELL_RATING:
6321 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6322 break;
6323 case ITEM_MOD_HIT_RATING:
6324 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6325 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6326 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6327 break;
6328 case ITEM_MOD_CRIT_RATING:
6329 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6330 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6331 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6332 break;
6333 case ITEM_MOD_HIT_TAKEN_RATING:
6334 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6335 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6336 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6337 break;
6338 case ITEM_MOD_CRIT_TAKEN_RATING:
6339 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6340 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6341 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6342 break;
6343 case ITEM_MOD_RESILIENCE_RATING:
6344 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6345 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6346 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6347 break;
6348 case ITEM_MOD_HASTE_RATING:
6349 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6350 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6351 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6352 break;
6353 case ITEM_MOD_EXPERTISE_RATING:
6354 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6355 break;
6356 case ITEM_MOD_ATTACK_POWER:
6357 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6358 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6359 break;
6360 case ITEM_MOD_RANGED_ATTACK_POWER:
6361 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6362 break;
6363 case ITEM_MOD_FERAL_ATTACK_POWER:
6364 ApplyFeralAPBonus(int32(val), apply);
6365 break;
6366 case ITEM_MOD_SPELL_HEALING_DONE:
6367 ApplySpellHealingBonus(int32(val), apply);
6368 break;
6369 case ITEM_MOD_SPELL_DAMAGE_DONE:
6370 ApplySpellDamageBonus(int32(val), apply);
6371 break;
6372 case ITEM_MOD_MANA_REGENERATION:
6373 ApplyManaRegenBonus(int32(val), apply);
6374 break;
6375 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6376 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6377 break;
6378 case ITEM_MOD_SPELL_POWER:
6379 ApplySpellHealingBonus(int32(val), apply);
6380 ApplySpellDamageBonus(int32(val), apply);
6381 break;
6385 if (proto->Armor)
6386 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6388 if (proto->Block)
6389 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6391 if (proto->HolyRes)
6392 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6394 if (proto->FireRes)
6395 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6397 if (proto->NatureRes)
6398 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6400 if (proto->FrostRes)
6401 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6403 if (proto->ShadowRes)
6404 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6406 if (proto->ArcaneRes)
6407 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6409 WeaponAttackType attType = BASE_ATTACK;
6410 float damage = 0.0f;
6412 if( slot == EQUIPMENT_SLOT_RANGED && (
6413 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6414 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6416 attType = RANGED_ATTACK;
6418 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6420 attType = OFF_ATTACK;
6423 if (proto->Damage[0].DamageMin > 0 )
6425 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6426 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6427 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6430 if (proto->Damage[0].DamageMax > 0 )
6432 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6433 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6436 // Druids get feral AP bonus from weapon dps
6437 if(getClass() == CLASS_DRUID)
6439 int32 feral_bonus = proto->getFeralBonus();
6440 if (feral_bonus > 0)
6441 ApplyFeralAPBonus(feral_bonus, apply);
6444 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6445 return;
6447 if (proto->Delay)
6449 if(slot == EQUIPMENT_SLOT_RANGED)
6450 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6451 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6452 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6453 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6454 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6457 if(CanModifyStats() && (damage || proto->Delay))
6458 UpdateDamagePhysical(attType);
6461 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6463 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6464 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6465 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6467 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6468 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6469 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6471 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6472 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6473 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6476 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6478 // generic not weapon specific case processes in aura code
6479 if(aura->GetSpellProto()->EquippedItemClass == -1)
6480 return;
6482 BaseModGroup mod = BASEMOD_END;
6483 switch(attackType)
6485 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6486 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6487 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6488 default: return;
6491 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6493 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6497 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6499 // ignore spell mods for not wands
6500 Modifier const* modifier = aura->GetModifier();
6501 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6502 return;
6504 // generic not weapon specific case processes in aura code
6505 if(aura->GetSpellProto()->EquippedItemClass == -1)
6506 return;
6508 UnitMods unitMod = UNIT_MOD_END;
6509 switch(attackType)
6511 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6512 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6513 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6514 default: return;
6517 UnitModifierType unitModType = TOTAL_VALUE;
6518 switch(modifier->m_auraname)
6520 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6521 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6522 default: return;
6525 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6527 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6531 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6533 if(!item)
6534 return;
6536 ItemPrototype const *proto = item->GetProto();
6537 if(!proto)
6538 return;
6540 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6542 _Spell const& spellData = proto->Spells[i];
6544 // no spell
6545 if(!spellData.SpellId )
6546 continue;
6548 // wrong triggering type
6549 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6550 continue;
6552 // check if it is valid spell
6553 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6554 if(!spellproto)
6555 continue;
6557 ApplyEquipSpell(spellproto,item,apply,form_change);
6561 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6563 if(apply)
6565 // Cannot be used in this stance/form
6566 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6567 return;
6569 if(form_change) // check aura active state from other form
6571 bool found = false;
6572 for (int k=0; k < 3; ++k)
6574 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6575 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6577 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6579 found = true;
6580 break;
6583 if(found)
6584 break;
6587 if(found) // and skip re-cast already active aura at form change
6588 return;
6591 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6593 CastSpell(this,spellInfo,true,item);
6595 else
6597 if(form_change) // check aura compatibility
6599 // Cannot be used in this stance/form
6600 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6601 return; // and remove only not compatible at form change
6604 if(item)
6605 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6606 else
6607 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6611 void Player::UpdateEquipSpellsAtFormChange()
6613 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6615 if(m_items[i] && !m_items[i]->IsBroken())
6617 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6618 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6622 // item set bonuses not dependent from item broken state
6623 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6625 ItemSetEffect* eff = ItemSetEff[setindex];
6626 if(!eff)
6627 continue;
6629 for(uint32 y=0;y<8; ++y)
6631 SpellEntry const* spellInfo = eff->spells[y];
6632 if(!spellInfo)
6633 continue;
6635 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6636 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6641 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6643 if(!item || item->IsBroken())
6644 return;
6646 ItemPrototype const *proto = item->GetProto();
6647 if(!proto)
6648 return;
6650 if (!Target || Target == this )
6651 return;
6653 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6655 _Spell const& spellData = proto->Spells[i];
6657 // no spell
6658 if(!spellData.SpellId )
6659 continue;
6661 // wrong triggering type
6662 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6663 continue;
6665 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6666 if(!spellInfo)
6668 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6669 continue;
6672 // not allow proc extra attack spell at extra attack
6673 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6674 return;
6676 float chance = spellInfo->procChance;
6678 if(spellData.SpellPPMRate)
6680 uint32 WeaponSpeed = GetAttackTime(attType);
6681 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6683 else if(chance > 100.0f)
6685 chance = GetWeaponProcChance();
6688 if (roll_chance_f(chance))
6689 CastSpell(Target, spellInfo->Id, true, item);
6692 // item combat enchantments
6693 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6695 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6696 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6697 if(!pEnchant) continue;
6698 for (int s=0;s<3;s++)
6700 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6701 continue;
6703 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6704 if (!spellInfo)
6706 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6707 continue;
6710 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6711 if (roll_chance_f(chance))
6713 if(IsPositiveSpell(pEnchant->spellid[s]))
6714 CastSpell(this, pEnchant->spellid[s], true, item);
6715 else
6716 CastSpell(Target, pEnchant->spellid[s], true, item);
6722 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6724 ItemPrototype const* proto = item->GetProto();
6725 // special learning case
6726 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6728 uint32 learn_spell_id = proto->Spells[0].SpellId;
6729 uint32 learning_spell_id = proto->Spells[1].SpellId;
6731 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6732 if(!spellInfo)
6734 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6735 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6736 return;
6739 Spell *spell = new Spell(this, spellInfo, false);
6740 spell->m_CastItem = item;
6741 spell->m_cast_count = cast_count; //set count of casts
6742 spell->m_currentBasePoints[0] = learning_spell_id;
6743 spell->prepare(&targets);
6744 return;
6747 // use triggered flag only for items with many spell casts and for not first cast
6748 int count = 0;
6750 // item spells casted at use
6751 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6753 _Spell const& spellData = proto->Spells[i];
6755 // no spell
6756 if(!spellData.SpellId)
6757 continue;
6759 // wrong triggering type
6760 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6761 continue;
6763 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6764 if(!spellInfo)
6766 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6767 continue;
6770 Spell *spell = new Spell(this, spellInfo, (count > 0));
6771 spell->m_CastItem = item;
6772 spell->m_cast_count = cast_count; // set count of casts
6773 spell->m_glyphIndex = glyphIndex; // glyph index
6774 spell->prepare(&targets);
6776 ++count;
6779 // Item enchantments spells casted at use
6780 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6782 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6783 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6784 if(!pEnchant) continue;
6785 for (int s=0;s<3;s++)
6787 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6788 continue;
6790 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6791 if (!spellInfo)
6793 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6794 continue;
6797 Spell *spell = new Spell(this, spellInfo, (count > 0));
6798 spell->m_CastItem = item;
6799 spell->m_cast_count = cast_count; // set count of casts
6800 spell->m_glyphIndex = glyphIndex; // glyph index
6801 spell->prepare(&targets);
6803 ++count;
6808 void Player::_RemoveAllItemMods()
6810 sLog.outDebug("_RemoveAllItemMods start.");
6812 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6814 if(m_items[i])
6816 ItemPrototype const *proto = m_items[i]->GetProto();
6817 if(!proto)
6818 continue;
6820 // item set bonuses not dependent from item broken state
6821 if(proto->ItemSet)
6822 RemoveItemsSetItem(this,proto);
6824 if(m_items[i]->IsBroken())
6825 continue;
6827 ApplyItemEquipSpell(m_items[i],false);
6828 ApplyEnchantment(m_items[i], false);
6832 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6834 if(m_items[i])
6836 if(m_items[i]->IsBroken())
6837 continue;
6838 ItemPrototype const *proto = m_items[i]->GetProto();
6839 if(!proto)
6840 continue;
6842 uint32 attacktype = Player::GetAttackBySlot(i);
6843 if(attacktype < MAX_ATTACK)
6844 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6846 _ApplyItemBonuses(proto,i, false);
6848 if( i == EQUIPMENT_SLOT_RANGED )
6849 _ApplyAmmoBonuses();
6853 sLog.outDebug("_RemoveAllItemMods complete.");
6856 void Player::_ApplyAllItemMods()
6858 sLog.outDebug("_ApplyAllItemMods start.");
6860 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6862 if(m_items[i])
6864 if(m_items[i]->IsBroken())
6865 continue;
6867 ItemPrototype const *proto = m_items[i]->GetProto();
6868 if(!proto)
6869 continue;
6871 uint32 attacktype = Player::GetAttackBySlot(i);
6872 if(attacktype < MAX_ATTACK)
6873 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6875 _ApplyItemBonuses(proto,i, true);
6877 if( i == EQUIPMENT_SLOT_RANGED )
6878 _ApplyAmmoBonuses();
6882 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6884 if(m_items[i])
6886 ItemPrototype const *proto = m_items[i]->GetProto();
6887 if(!proto)
6888 continue;
6890 // item set bonuses not dependent from item broken state
6891 if(proto->ItemSet)
6892 AddItemsSetItem(this,m_items[i]);
6894 if(m_items[i]->IsBroken())
6895 continue;
6897 ApplyItemEquipSpell(m_items[i],true);
6898 ApplyEnchantment(m_items[i], true);
6902 sLog.outDebug("_ApplyAllItemMods complete.");
6905 void Player::_ApplyAmmoBonuses()
6907 // check ammo
6908 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6909 if(!ammo_id)
6910 return;
6912 float currentAmmoDPS;
6914 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6915 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6916 currentAmmoDPS = 0.0f;
6917 else
6918 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6920 if(currentAmmoDPS == GetAmmoDPS())
6921 return;
6923 m_ammoDPS = currentAmmoDPS;
6925 if(CanModifyStats())
6926 UpdateDamagePhysical(RANGED_ATTACK);
6929 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
6931 if(!ammo_proto)
6932 return false;
6934 // check ranged weapon
6935 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
6936 if(!weapon || weapon->IsBroken() )
6937 return false;
6939 ItemPrototype const* weapon_proto = weapon->GetProto();
6940 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
6941 return false;
6943 // check ammo ws. weapon compatibility
6944 switch(weapon_proto->SubClass)
6946 case ITEM_SUBCLASS_WEAPON_BOW:
6947 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
6948 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
6949 return false;
6950 break;
6951 case ITEM_SUBCLASS_WEAPON_GUN:
6952 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
6953 return false;
6954 break;
6955 default:
6956 return false;
6959 return true;
6962 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
6963 Called by remove insignia spell effect */
6964 void Player::RemovedInsignia(Player* looterPlr)
6966 if (!GetBattleGroundId())
6967 return;
6969 // If not released spirit, do it !
6970 if(m_deathTimer > 0)
6972 m_deathTimer = 0;
6973 BuildPlayerRepop();
6974 RepopAtGraveyard();
6977 Corpse *corpse = GetCorpse();
6978 if (!corpse)
6979 return;
6981 // We have to convert player corpse to bones, not to be able to resurrect there
6982 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
6983 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
6984 if (!bones)
6985 return;
6987 // Now we must make bones lootable, and send player loot
6988 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
6990 // We store the level of our player in the gold field
6991 // We retrieve this information at Player::SendLoot()
6992 bones->loot.gold = getLevel();
6993 bones->lootRecipient = looterPlr;
6994 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
6997 /*Loot type MUST be
6998 1-corpse, go
6999 2-skinning
7000 3-Fishing
7003 void Player::SendLootRelease( uint64 guid )
7005 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7006 data << uint64(guid) << uint8(1);
7007 SendDirectMessage( &data );
7010 void Player::SendLoot(uint64 guid, LootType loot_type)
7012 if (uint64 lguid = GetLootGUID())
7013 m_session->DoLootRelease(lguid);
7015 Loot *loot = 0;
7016 PermissionTypes permission = ALL_PERMISSION;
7018 sLog.outDebug("Player::SendLoot");
7019 if (IS_GAMEOBJECT_GUID(guid))
7021 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7022 GameObject *go =
7023 ObjectAccessor::GetGameObject(*this, guid);
7025 // not check distance for GO in case owned GO (fishing bobber case, for example)
7026 // And permit out of range GO with no owner in case fishing hole
7027 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7029 SendLootRelease(guid);
7030 return;
7033 loot = &go->loot;
7035 if(go->getLootState() == GO_READY)
7037 uint32 lootid = go->GetLootId();
7039 if(lootid)
7041 sLog.outDebug(" if(lootid)");
7042 loot->clear();
7043 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7046 if(loot_type == LOOT_FISHING)
7047 go->getFishLoot(loot,this);
7049 go->SetLootState(GO_ACTIVATED);
7052 else if (IS_ITEM_GUID(guid))
7054 Item *item = GetItemByGuid( guid );
7056 if (!item)
7058 SendLootRelease(guid);
7059 return;
7062 if(loot_type == LOOT_DISENCHANTING)
7064 loot = &item->loot;
7066 if(!item->m_lootGenerated)
7068 item->m_lootGenerated = true;
7069 loot->clear();
7070 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7073 else if(loot_type == LOOT_PROSPECTING)
7075 loot = &item->loot;
7077 if(!item->m_lootGenerated)
7079 item->m_lootGenerated = true;
7080 loot->clear();
7081 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7084 else if(loot_type == LOOT_MILLING)
7086 loot = &item->loot;
7088 if(!item->m_lootGenerated)
7090 item->m_lootGenerated = true;
7091 loot->clear();
7092 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7095 else
7097 loot = &item->loot;
7099 if(!item->m_lootGenerated)
7101 item->m_lootGenerated = true;
7102 loot->clear();
7103 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7105 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7109 else if (IS_CORPSE_GUID(guid)) // remove insignia
7111 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7113 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7115 SendLootRelease(guid);
7116 return;
7119 loot = &bones->loot;
7121 if (!bones->lootForBody)
7123 bones->lootForBody = true;
7124 uint32 pLevel = bones->loot.gold;
7125 bones->loot.clear();
7126 // It may need a better formula
7127 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7128 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7131 if (bones->lootRecipient != this)
7132 permission = NONE_PERMISSION;
7134 else
7136 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7138 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7139 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7141 SendLootRelease(guid);
7142 return;
7145 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7147 SendLootRelease(guid);
7148 return;
7151 loot = &creature->loot;
7153 if(loot_type == LOOT_PICKPOCKETING)
7155 if ( !creature->lootForPickPocketed )
7157 creature->lootForPickPocketed = true;
7158 loot->clear();
7160 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7161 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7163 // Generate extra money for pick pocket loot
7164 const uint32 a = urand(0, creature->getLevel()/2);
7165 const uint32 b = urand(0, getLevel()/2);
7166 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7169 else
7171 // the player whose group may loot the corpse
7172 Player *recipient = creature->GetLootRecipient();
7173 if (!recipient)
7175 creature->SetLootRecipient(this);
7176 recipient = this;
7179 if (creature->lootForPickPocketed)
7181 creature->lootForPickPocketed = false;
7182 loot->clear();
7185 if(!creature->lootForBody)
7187 creature->lootForBody = true;
7188 loot->clear();
7190 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7191 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7193 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7195 if(Group* group = recipient->GetGroup())
7197 group->UpdateLooterGuid(creature,true);
7199 switch (group->GetLootMethod())
7201 case GROUP_LOOT:
7202 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7203 group->GroupLoot(recipient->GetGUID(), loot, creature);
7204 break;
7205 case NEED_BEFORE_GREED:
7206 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7207 break;
7208 case MASTER_LOOT:
7209 group->MasterLoot(recipient->GetGUID(), loot, creature);
7210 break;
7211 default:
7212 break;
7217 // possible only if creature->lootForBody && loot->empty() at spell cast check
7218 if (loot_type == LOOT_SKINNING)
7220 loot->clear();
7221 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7223 // set group rights only for loot_type != LOOT_SKINNING
7224 else
7226 if(Group* group = GetGroup())
7228 if( group == recipient->GetGroup() )
7230 if(group->GetLootMethod() == FREE_FOR_ALL)
7231 permission = ALL_PERMISSION;
7232 else if(group->GetLooterGuid() == GetGUID())
7234 if(group->GetLootMethod() == MASTER_LOOT)
7235 permission = MASTER_PERMISSION;
7236 else
7237 permission = ALL_PERMISSION;
7239 else
7240 permission = GROUP_PERMISSION;
7242 else
7243 permission = NONE_PERMISSION;
7245 else if(recipient == this)
7246 permission = ALL_PERMISSION;
7247 else
7248 permission = NONE_PERMISSION;
7253 SetLootGUID(guid);
7255 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7256 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7257 loot_type = LOOT_SKINNING;
7259 if(loot_type == LOOT_FISHINGHOLE)
7260 loot_type = LOOT_FISHING;
7262 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7264 data << uint64(guid);
7265 data << uint8(loot_type);
7266 data << LootView(*loot, this, permission);
7268 SendDirectMessage(&data);
7270 // add 'this' player as one of the players that are looting 'loot'
7271 if (permission != NONE_PERMISSION)
7272 loot->AddLooter(GetGUID());
7274 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7275 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7278 void Player::SendNotifyLootMoneyRemoved()
7280 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7281 GetSession()->SendPacket( &data );
7284 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7286 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7287 data << uint8(lootSlot);
7288 GetSession()->SendPacket( &data );
7291 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7293 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7294 data << Field;
7295 data << Value;
7296 GetSession()->SendPacket(&data);
7299 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7301 // data depends on zoneid/mapid...
7302 BattleGround* bg = GetBattleGround();
7303 uint16 NumberOfFields = 0;
7304 uint32 mapid = GetMapId();
7306 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7308 // may be exist better way to do this...
7309 switch(zoneid)
7311 case 0:
7312 case 1:
7313 case 4:
7314 case 8:
7315 case 10:
7316 case 11:
7317 case 12:
7318 case 36:
7319 case 38:
7320 case 40:
7321 case 41:
7322 case 51:
7323 case 267:
7324 case 1519:
7325 case 1537:
7326 case 2257:
7327 case 2918:
7328 NumberOfFields = 8;
7329 break;
7330 case 139:
7331 NumberOfFields = 41;
7332 break;
7333 case 1377:
7334 NumberOfFields = 15;
7335 break;
7336 case 2597:
7337 NumberOfFields = 83;
7338 break;
7339 case 3277:
7340 NumberOfFields = 16;
7341 break;
7342 case 3358:
7343 case 3820:
7344 NumberOfFields = 40;
7345 break;
7346 case 3483:
7347 NumberOfFields = 27;
7348 break;
7349 case 3518:
7350 NumberOfFields = 39;
7351 break;
7352 case 3519:
7353 NumberOfFields = 38;
7354 break;
7355 case 3521:
7356 NumberOfFields = 37;
7357 break;
7358 case 3698:
7359 case 3702:
7360 case 3968:
7361 NumberOfFields = 11;
7362 break;
7363 case 3703:
7364 NumberOfFields = 11;
7365 break;
7366 default:
7367 NumberOfFields = 12;
7368 break;
7371 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7372 data << uint32(mapid); // mapid
7373 data << uint32(zoneid); // zone id
7374 data << uint32(areaid); // area id, new 2.1.0
7375 data << uint16(NumberOfFields); // count of uint64 blocks
7376 data << uint32(0x8d8) << uint32(0x0); // 1
7377 data << uint32(0x8d7) << uint32(0x0); // 2
7378 data << uint32(0x8d6) << uint32(0x0); // 3
7379 data << uint32(0x8d5) << uint32(0x0); // 4
7380 data << uint32(0x8d4) << uint32(0x0); // 5
7381 data << uint32(0x8d3) << uint32(0x0); // 6
7382 // 7 1 - Arena season in progress, 0 - end of season
7383 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7384 // 8 Arena season id
7385 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7386 if(mapid == 530) // Outland
7388 data << uint32(0x9bf) << uint32(0x0); // 7
7389 data << uint32(0x9bd) << uint32(0xF); // 8
7390 data << uint32(0x9bb) << uint32(0xF); // 9
7392 switch(zoneid)
7394 case 1:
7395 case 11:
7396 case 12:
7397 case 38:
7398 case 40:
7399 case 51:
7400 case 1519:
7401 case 1537:
7402 case 2257:
7403 break;
7404 case 2597: // AV
7405 data << uint32(0x7ae) << uint32(0x1); // 7
7406 data << uint32(0x532) << uint32(0x1); // 8
7407 data << uint32(0x531) << uint32(0x0); // 9
7408 data << uint32(0x52e) << uint32(0x0); // 10
7409 data << uint32(0x571) << uint32(0x0); // 11
7410 data << uint32(0x570) << uint32(0x0); // 12
7411 data << uint32(0x567) << uint32(0x1); // 13
7412 data << uint32(0x566) << uint32(0x1); // 14
7413 data << uint32(0x550) << uint32(0x1); // 15
7414 data << uint32(0x544) << uint32(0x0); // 16
7415 data << uint32(0x536) << uint32(0x0); // 17
7416 data << uint32(0x535) << uint32(0x1); // 18
7417 data << uint32(0x518) << uint32(0x0); // 19
7418 data << uint32(0x517) << uint32(0x0); // 20
7419 data << uint32(0x574) << uint32(0x0); // 21
7420 data << uint32(0x573) << uint32(0x0); // 22
7421 data << uint32(0x572) << uint32(0x0); // 23
7422 data << uint32(0x56f) << uint32(0x0); // 24
7423 data << uint32(0x56e) << uint32(0x0); // 25
7424 data << uint32(0x56d) << uint32(0x0); // 26
7425 data << uint32(0x56c) << uint32(0x0); // 27
7426 data << uint32(0x56b) << uint32(0x0); // 28
7427 data << uint32(0x56a) << uint32(0x1); // 29
7428 data << uint32(0x569) << uint32(0x1); // 30
7429 data << uint32(0x568) << uint32(0x1); // 13
7430 data << uint32(0x565) << uint32(0x0); // 32
7431 data << uint32(0x564) << uint32(0x0); // 33
7432 data << uint32(0x563) << uint32(0x0); // 34
7433 data << uint32(0x562) << uint32(0x0); // 35
7434 data << uint32(0x561) << uint32(0x0); // 36
7435 data << uint32(0x560) << uint32(0x0); // 37
7436 data << uint32(0x55f) << uint32(0x0); // 38
7437 data << uint32(0x55e) << uint32(0x0); // 39
7438 data << uint32(0x55d) << uint32(0x0); // 40
7439 data << uint32(0x3c6) << uint32(0x4); // 41
7440 data << uint32(0x3c4) << uint32(0x6); // 42
7441 data << uint32(0x3c2) << uint32(0x4); // 43
7442 data << uint32(0x516) << uint32(0x1); // 44
7443 data << uint32(0x515) << uint32(0x0); // 45
7444 data << uint32(0x3b6) << uint32(0x6); // 46
7445 data << uint32(0x55c) << uint32(0x0); // 47
7446 data << uint32(0x55b) << uint32(0x0); // 48
7447 data << uint32(0x55a) << uint32(0x0); // 49
7448 data << uint32(0x559) << uint32(0x0); // 50
7449 data << uint32(0x558) << uint32(0x0); // 51
7450 data << uint32(0x557) << uint32(0x0); // 52
7451 data << uint32(0x556) << uint32(0x0); // 53
7452 data << uint32(0x555) << uint32(0x0); // 54
7453 data << uint32(0x554) << uint32(0x1); // 55
7454 data << uint32(0x553) << uint32(0x1); // 56
7455 data << uint32(0x552) << uint32(0x1); // 57
7456 data << uint32(0x551) << uint32(0x1); // 58
7457 data << uint32(0x54f) << uint32(0x0); // 59
7458 data << uint32(0x54e) << uint32(0x0); // 60
7459 data << uint32(0x54d) << uint32(0x1); // 61
7460 data << uint32(0x54c) << uint32(0x0); // 62
7461 data << uint32(0x54b) << uint32(0x0); // 63
7462 data << uint32(0x545) << uint32(0x0); // 64
7463 data << uint32(0x543) << uint32(0x1); // 65
7464 data << uint32(0x542) << uint32(0x0); // 66
7465 data << uint32(0x540) << uint32(0x0); // 67
7466 data << uint32(0x53f) << uint32(0x0); // 68
7467 data << uint32(0x53e) << uint32(0x0); // 69
7468 data << uint32(0x53d) << uint32(0x0); // 70
7469 data << uint32(0x53c) << uint32(0x0); // 71
7470 data << uint32(0x53b) << uint32(0x0); // 72
7471 data << uint32(0x53a) << uint32(0x1); // 73
7472 data << uint32(0x539) << uint32(0x0); // 74
7473 data << uint32(0x538) << uint32(0x0); // 75
7474 data << uint32(0x537) << uint32(0x0); // 76
7475 data << uint32(0x534) << uint32(0x0); // 77
7476 data << uint32(0x533) << uint32(0x0); // 78
7477 data << uint32(0x530) << uint32(0x0); // 79
7478 data << uint32(0x52f) << uint32(0x0); // 80
7479 data << uint32(0x52d) << uint32(0x1); // 81
7480 break;
7481 case 3277: // WS
7482 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7483 bg->FillInitialWorldStates(data);
7484 else
7486 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7487 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7488 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7489 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7490 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7491 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7492 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7493 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7495 break;
7496 case 3358: // AB
7497 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7498 bg->FillInitialWorldStates(data);
7499 else
7501 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7502 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7503 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7504 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7505 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7506 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7507 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7508 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7509 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7510 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7511 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7512 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7513 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7514 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7515 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7516 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7517 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7518 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7519 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7520 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7521 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7522 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7523 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7524 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7525 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7526 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7527 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7528 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7529 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7530 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7531 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7532 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7534 break;
7535 case 3820: // EY
7536 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7537 bg->FillInitialWorldStates(data);
7538 else
7540 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7541 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7542 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7543 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7544 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7545 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7546 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7547 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7548 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7549 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7550 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7551 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7552 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7553 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7554 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7555 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7556 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7557 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7558 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7559 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7560 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7561 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7562 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7563 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7564 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7565 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7566 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7567 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7568 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7569 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7570 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7571 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7572 // and some more ... unknown
7574 break;
7575 case 3483: // Hellfire Peninsula
7576 data << uint32(0x9ba) << uint32(0x1); // 10
7577 data << uint32(0x9b9) << uint32(0x1); // 11
7578 data << uint32(0x9b5) << uint32(0x0); // 12
7579 data << uint32(0x9b4) << uint32(0x1); // 13
7580 data << uint32(0x9b3) << uint32(0x0); // 14
7581 data << uint32(0x9b2) << uint32(0x0); // 15
7582 data << uint32(0x9b1) << uint32(0x1); // 16
7583 data << uint32(0x9b0) << uint32(0x0); // 17
7584 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7585 data << uint32(0x9ac) << uint32(0x0); // 19
7586 data << uint32(0x9a8) << uint32(0x0); // 20
7587 data << uint32(0x9a7) << uint32(0x0); // 21
7588 data << uint32(0x9a6) << uint32(0x1); // 22
7589 break;
7590 case 3519: // Terokkar Forest
7591 data << uint32(0xa41) << uint32(0x0); // 10
7592 data << uint32(0xa40) << uint32(0x14); // 11
7593 data << uint32(0xa3f) << uint32(0x0); // 12
7594 data << uint32(0xa3e) << uint32(0x0); // 13
7595 data << uint32(0xa3d) << uint32(0x5); // 14
7596 data << uint32(0xa3c) << uint32(0x0); // 15
7597 data << uint32(0xa87) << uint32(0x0); // 16
7598 data << uint32(0xa86) << uint32(0x0); // 17
7599 data << uint32(0xa85) << uint32(0x0); // 18
7600 data << uint32(0xa84) << uint32(0x0); // 19
7601 data << uint32(0xa83) << uint32(0x0); // 20
7602 data << uint32(0xa82) << uint32(0x0); // 21
7603 data << uint32(0xa81) << uint32(0x0); // 22
7604 data << uint32(0xa80) << uint32(0x0); // 23
7605 data << uint32(0xa7e) << uint32(0x0); // 24
7606 data << uint32(0xa7d) << uint32(0x0); // 25
7607 data << uint32(0xa7c) << uint32(0x0); // 26
7608 data << uint32(0xa7b) << uint32(0x0); // 27
7609 data << uint32(0xa7a) << uint32(0x0); // 28
7610 data << uint32(0xa79) << uint32(0x0); // 29
7611 data << uint32(0x9d0) << uint32(0x5); // 30
7612 data << uint32(0x9ce) << uint32(0x0); // 31
7613 data << uint32(0x9cd) << uint32(0x0); // 32
7614 data << uint32(0x9cc) << uint32(0x0); // 33
7615 data << uint32(0xa88) << uint32(0x0); // 34
7616 data << uint32(0xad0) << uint32(0x0); // 35
7617 data << uint32(0xacf) << uint32(0x1); // 36
7618 break;
7619 case 3521: // Zangarmarsh
7620 data << uint32(0x9e1) << uint32(0x0); // 10
7621 data << uint32(0x9e0) << uint32(0x0); // 11
7622 data << uint32(0x9df) << uint32(0x0); // 12
7623 data << uint32(0xa5d) << uint32(0x1); // 13
7624 data << uint32(0xa5c) << uint32(0x0); // 14
7625 data << uint32(0xa5b) << uint32(0x1); // 15
7626 data << uint32(0xa5a) << uint32(0x0); // 16
7627 data << uint32(0xa59) << uint32(0x1); // 17
7628 data << uint32(0xa58) << uint32(0x0); // 18
7629 data << uint32(0xa57) << uint32(0x0); // 19
7630 data << uint32(0xa56) << uint32(0x0); // 20
7631 data << uint32(0xa55) << uint32(0x1); // 21
7632 data << uint32(0xa54) << uint32(0x0); // 22
7633 data << uint32(0x9e7) << uint32(0x0); // 23
7634 data << uint32(0x9e6) << uint32(0x0); // 24
7635 data << uint32(0x9e5) << uint32(0x0); // 25
7636 data << uint32(0xa00) << uint32(0x0); // 26
7637 data << uint32(0x9ff) << uint32(0x1); // 27
7638 data << uint32(0x9fe) << uint32(0x0); // 28
7639 data << uint32(0x9fd) << uint32(0x0); // 29
7640 data << uint32(0x9fc) << uint32(0x1); // 30
7641 data << uint32(0x9fb) << uint32(0x0); // 31
7642 data << uint32(0xa62) << uint32(0x0); // 32
7643 data << uint32(0xa61) << uint32(0x1); // 33
7644 data << uint32(0xa60) << uint32(0x1); // 34
7645 data << uint32(0xa5f) << uint32(0x0); // 35
7646 break;
7647 case 3698: // Nagrand Arena
7648 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7649 bg->FillInitialWorldStates(data);
7650 else
7652 data << uint32(0xa0f) << uint32(0x0); // 7
7653 data << uint32(0xa10) << uint32(0x0); // 8
7654 data << uint32(0xa11) << uint32(0x0); // 9 show
7656 break;
7657 case 3702: // Blade's Edge Arena
7658 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7659 bg->FillInitialWorldStates(data);
7660 else
7662 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7663 data << uint32(0x9f1) << uint32(0x0); // 8 green
7664 data << uint32(0x9f3) << uint32(0x0); // 9 show
7666 break;
7667 case 3968: // Ruins of Lordaeron
7668 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7669 bg->FillInitialWorldStates(data);
7670 else
7672 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7673 data << uint32(0xbb9) << uint32(0x0); // 8 green
7674 data << uint32(0xbba) << uint32(0x0); // 9 show
7676 break;
7677 case 3703: // Shattrath City
7678 break;
7679 default:
7680 data << uint32(0x914) << uint32(0x0); // 7
7681 data << uint32(0x913) << uint32(0x0); // 8
7682 data << uint32(0x912) << uint32(0x0); // 9
7683 data << uint32(0x915) << uint32(0x0); // 10
7684 break;
7686 GetSession()->SendPacket(&data);
7689 uint32 Player::GetXPRestBonus(uint32 xp)
7691 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7693 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7694 rested_bonus = xp;
7696 SetRestBonus( GetRestBonus() - rested_bonus);
7698 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7699 return rested_bonus;
7702 void Player::SetBindPoint(uint64 guid)
7704 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7705 data << uint64(guid);
7706 GetSession()->SendPacket( &data );
7709 void Player::SendTalentWipeConfirm(uint64 guid)
7711 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7712 data << uint64(guid);
7713 data << uint32(resetTalentsCost());
7714 GetSession()->SendPacket( &data );
7717 void Player::SendPetSkillWipeConfirm()
7719 Pet* pet = GetPet();
7720 if(!pet)
7721 return;
7722 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7723 data << pet->GetGUID();
7724 data << uint32(pet->resetTalentsCost());
7725 GetSession()->SendPacket( &data );
7728 /*********************************************************/
7729 /*** STORAGE SYSTEM ***/
7730 /*********************************************************/
7732 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7734 assert(i < 3);
7735 if(i < 2 && item)
7737 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7738 return;
7739 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7740 if(charges == 0)
7741 return;
7742 if(charges > 1)
7743 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7744 else if(charges <= 1)
7746 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7747 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7752 void Player::SetSheath( uint32 sheathed )
7754 switch (sheathed)
7756 case SHEATH_STATE_UNARMED: // no prepared weapon
7757 SetVirtualItemSlot(0,NULL);
7758 SetVirtualItemSlot(1,NULL);
7759 SetVirtualItemSlot(2,NULL);
7760 break;
7761 case SHEATH_STATE_MELEE: // prepared melee weapon
7763 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7764 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7765 SetVirtualItemSlot(2,NULL);
7766 }; break;
7767 case SHEATH_STATE_RANGED: // prepared ranged weapon
7768 SetVirtualItemSlot(0,NULL);
7769 SetVirtualItemSlot(1,NULL);
7770 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7771 break;
7772 default:
7773 SetVirtualItemSlot(0,NULL);
7774 SetVirtualItemSlot(1,NULL);
7775 SetVirtualItemSlot(2,NULL);
7776 break;
7778 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7781 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7783 uint8 pClass = getClass();
7785 uint8 slots[4];
7786 slots[0] = NULL_SLOT;
7787 slots[1] = NULL_SLOT;
7788 slots[2] = NULL_SLOT;
7789 slots[3] = NULL_SLOT;
7790 switch( proto->InventoryType )
7792 case INVTYPE_HEAD:
7793 slots[0] = EQUIPMENT_SLOT_HEAD;
7794 break;
7795 case INVTYPE_NECK:
7796 slots[0] = EQUIPMENT_SLOT_NECK;
7797 break;
7798 case INVTYPE_SHOULDERS:
7799 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7800 break;
7801 case INVTYPE_BODY:
7802 slots[0] = EQUIPMENT_SLOT_BODY;
7803 break;
7804 case INVTYPE_CHEST:
7805 slots[0] = EQUIPMENT_SLOT_CHEST;
7806 break;
7807 case INVTYPE_ROBE:
7808 slots[0] = EQUIPMENT_SLOT_CHEST;
7809 break;
7810 case INVTYPE_WAIST:
7811 slots[0] = EQUIPMENT_SLOT_WAIST;
7812 break;
7813 case INVTYPE_LEGS:
7814 slots[0] = EQUIPMENT_SLOT_LEGS;
7815 break;
7816 case INVTYPE_FEET:
7817 slots[0] = EQUIPMENT_SLOT_FEET;
7818 break;
7819 case INVTYPE_WRISTS:
7820 slots[0] = EQUIPMENT_SLOT_WRISTS;
7821 break;
7822 case INVTYPE_HANDS:
7823 slots[0] = EQUIPMENT_SLOT_HANDS;
7824 break;
7825 case INVTYPE_FINGER:
7826 slots[0] = EQUIPMENT_SLOT_FINGER1;
7827 slots[1] = EQUIPMENT_SLOT_FINGER2;
7828 break;
7829 case INVTYPE_TRINKET:
7830 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7831 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7832 break;
7833 case INVTYPE_CLOAK:
7834 slots[0] = EQUIPMENT_SLOT_BACK;
7835 break;
7836 case INVTYPE_WEAPON:
7838 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7840 // suggest offhand slot only if know dual wielding
7841 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7842 if(CanDualWield())
7843 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7844 break;
7846 case INVTYPE_SHIELD:
7847 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7848 break;
7849 case INVTYPE_RANGED:
7850 slots[0] = EQUIPMENT_SLOT_RANGED;
7851 break;
7852 case INVTYPE_2HWEAPON:
7853 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7854 if (CanDualWield() && CanTitanGrip())
7855 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7856 break;
7857 case INVTYPE_TABARD:
7858 slots[0] = EQUIPMENT_SLOT_TABARD;
7859 break;
7860 case INVTYPE_WEAPONMAINHAND:
7861 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7862 break;
7863 case INVTYPE_WEAPONOFFHAND:
7864 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7865 break;
7866 case INVTYPE_HOLDABLE:
7867 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7868 break;
7869 case INVTYPE_THROWN:
7870 slots[0] = EQUIPMENT_SLOT_RANGED;
7871 break;
7872 case INVTYPE_RANGEDRIGHT:
7873 slots[0] = EQUIPMENT_SLOT_RANGED;
7874 break;
7875 case INVTYPE_BAG:
7876 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7877 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7878 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7879 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7880 break;
7881 case INVTYPE_RELIC:
7883 switch(proto->SubClass)
7885 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7886 if (pClass == CLASS_PALADIN)
7887 slots[0] = EQUIPMENT_SLOT_RANGED;
7888 break;
7889 case ITEM_SUBCLASS_ARMOR_IDOL:
7890 if (pClass == CLASS_DRUID)
7891 slots[0] = EQUIPMENT_SLOT_RANGED;
7892 break;
7893 case ITEM_SUBCLASS_ARMOR_TOTEM:
7894 if (pClass == CLASS_SHAMAN)
7895 slots[0] = EQUIPMENT_SLOT_RANGED;
7896 break;
7897 case ITEM_SUBCLASS_ARMOR_MISC:
7898 if (pClass == CLASS_WARLOCK)
7899 slots[0] = EQUIPMENT_SLOT_RANGED;
7900 break;
7901 case ITEM_SUBCLASS_ARMOR_SIGIL:
7902 if (pClass == CLASS_DEATH_KNIGHT)
7903 slots[0] = EQUIPMENT_SLOT_RANGED;
7904 break;
7906 break;
7908 default :
7909 return NULL_SLOT;
7912 if( slot != NULL_SLOT )
7914 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7916 for (int i = 0; i < 4; i++)
7918 if ( slots[i] == slot )
7919 return slot;
7923 else
7925 // search free slot at first
7926 for (int i = 0; i < 4; i++)
7928 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7930 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
7931 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
7932 return slots[i];
7936 // if not found free and can swap return first appropriate from used
7937 for (int i = 0; i < 4; i++)
7939 if ( slots[i] != NULL_SLOT && swap )
7940 return slots[i];
7944 // no free position
7945 return NULL_SLOT;
7948 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
7950 Item *pItem;
7951 uint32 tempcount = 0;
7953 uint8 res = EQUIP_ERR_OK;
7955 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
7957 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7958 if( pItem && pItem->GetEntry() == item )
7960 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
7961 if(ires==EQUIP_ERR_OK)
7963 tempcount += pItem->GetCount();
7964 if( tempcount >= count )
7965 return EQUIP_ERR_OK;
7967 else
7968 res = ires;
7971 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
7973 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7974 if( pItem && pItem->GetEntry() == item )
7976 tempcount += pItem->GetCount();
7977 if( tempcount >= count )
7978 return EQUIP_ERR_OK;
7981 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
7983 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7984 if( pItem && pItem->GetEntry() == item )
7986 tempcount += pItem->GetCount();
7987 if( tempcount >= count )
7988 return EQUIP_ERR_OK;
7991 Bag *pBag;
7992 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
7994 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7995 if( pBag )
7997 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
7999 pItem = GetItemByPos( i, j );
8000 if( pItem && pItem->GetEntry() == item )
8002 tempcount += pItem->GetCount();
8003 if( tempcount >= count )
8004 return EQUIP_ERR_OK;
8010 // not found req. item count and have unequippable items
8011 return res;
8014 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8016 uint32 count = 0;
8017 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8019 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8020 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8021 count += pItem->GetCount();
8023 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8025 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8026 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8027 count += pItem->GetCount();
8029 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8031 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8032 if( pBag )
8033 count += pBag->GetItemCount(item,skipItem);
8036 if(skipItem && skipItem->GetProto()->GemProperties)
8038 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8040 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8041 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8042 count += pItem->GetGemCountWithID(item);
8046 if(inBankAlso)
8048 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8050 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8051 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8052 count += pItem->GetCount();
8054 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8056 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8057 if( pBag )
8058 count += pBag->GetItemCount(item,skipItem);
8061 if(skipItem && skipItem->GetProto()->GemProperties)
8063 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8065 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8066 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8067 count += pItem->GetGemCountWithID(item);
8072 return count;
8075 Item* Player::GetItemByGuid( uint64 guid ) const
8077 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8079 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8080 if( pItem && pItem->GetGUID() == guid )
8081 return pItem;
8083 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8085 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8086 if( pItem && pItem->GetGUID() == guid )
8087 return pItem;
8090 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8092 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8093 if( pBag )
8095 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8097 Item* pItem = pBag->GetItemByPos( j );
8098 if( pItem && pItem->GetGUID() == guid )
8099 return pItem;
8103 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8105 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8106 if( pBag )
8108 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8110 Item* pItem = pBag->GetItemByPos( j );
8111 if( pItem && pItem->GetGUID() == guid )
8112 return pItem;
8117 return NULL;
8120 Item* Player::GetItemByPos( uint16 pos ) const
8122 uint8 bag = pos >> 8;
8123 uint8 slot = pos & 255;
8124 return GetItemByPos( bag, slot );
8127 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8129 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8130 return m_items[slot];
8131 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8132 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8134 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8135 if ( pBag )
8136 return pBag->GetItemByPos(slot);
8138 return NULL;
8141 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8143 uint16 slot;
8144 switch (attackType)
8146 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8147 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8148 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8149 default: return NULL;
8152 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8153 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8154 return NULL;
8156 if(!useable)
8157 return item;
8159 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8160 return NULL;
8162 return item;
8165 Item* Player::GetShield(bool useable) const
8167 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8168 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8169 return NULL;
8171 if(!useable)
8172 return item;
8174 if( item->IsBroken())
8175 return NULL;
8177 return item;
8180 uint32 Player::GetAttackBySlot( uint8 slot )
8182 switch(slot)
8184 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8185 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8186 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8187 default: return MAX_ATTACK;
8191 bool Player::HasBankBagSlot( uint8 slot ) const
8193 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8194 if( slot < maxslot )
8195 return true;
8196 return false;
8199 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8201 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8202 return true;
8203 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8204 return true;
8205 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8206 return true;
8207 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8208 return true;
8209 return false;
8212 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8214 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8215 return true;
8216 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8217 return true;
8218 return false;
8221 bool Player::IsBankPos( uint8 bag, uint8 slot )
8223 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8224 return true;
8225 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8226 return true;
8227 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8228 return true;
8229 return false;
8232 bool Player::IsBagPos( uint16 pos )
8234 uint8 bag = pos >> 8;
8235 uint8 slot = pos & 255;
8236 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8237 return true;
8238 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8239 return true;
8240 return false;
8243 bool Player::IsValidPos( uint8 bag, uint8 slot )
8245 // post selected
8246 if(bag == NULL_BAG)
8247 return true;
8249 if (bag == INVENTORY_SLOT_BAG_0)
8251 // any post selected
8252 if (slot == NULL_SLOT)
8253 return true;
8255 // equipment
8256 if (slot < EQUIPMENT_SLOT_END)
8257 return true;
8259 // bag equip slots
8260 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8261 return true;
8263 // backpack slots
8264 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8265 return true;
8267 // keyring slots
8268 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8269 return true;
8271 // bank main slots
8272 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8273 return true;
8275 // bank bag slots
8276 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8277 return true;
8279 return false;
8282 // bag content slots
8283 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8285 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8286 if(!pBag)
8287 return false;
8289 // any post selected
8290 if (slot == NULL_SLOT)
8291 return true;
8293 return slot < pBag->GetBagSize();
8296 // bank bag content slots
8297 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8299 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8300 if(!pBag)
8301 return false;
8303 // any post selected
8304 if (slot == NULL_SLOT)
8305 return true;
8307 return slot < pBag->GetBagSize();
8310 // where this?
8311 return false;
8315 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8317 uint32 tempcount = 0;
8318 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8320 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8321 if( pItem && pItem->GetEntry() == item )
8323 tempcount += pItem->GetCount();
8324 if( tempcount >= count )
8325 return true;
8328 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8330 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8331 if( pItem && pItem->GetEntry() == item )
8333 tempcount += pItem->GetCount();
8334 if( tempcount >= count )
8335 return true;
8338 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8340 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8342 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8344 Item* pItem = GetItemByPos( i, j );
8345 if( pItem && pItem->GetEntry() == item )
8347 tempcount += pItem->GetCount();
8348 if( tempcount >= count )
8349 return true;
8355 if(inBankAlso)
8357 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8359 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8360 if( pItem && pItem->GetEntry() == item )
8362 tempcount += pItem->GetCount();
8363 if( tempcount >= count )
8364 return true;
8367 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8369 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8371 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8373 Item* pItem = GetItemByPos( i, j );
8374 if( pItem && pItem->GetEntry() == item )
8376 tempcount += pItem->GetCount();
8377 if( tempcount >= count )
8378 return true;
8385 return false;
8388 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8390 uint32 tempcount = 0;
8391 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8393 if(i==int(except_slot))
8394 continue;
8396 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8397 if( pItem && pItem->GetEntry() == item)
8399 tempcount += pItem->GetCount();
8400 if( tempcount >= count )
8401 return true;
8405 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8406 if (pProto && pProto->GemProperties)
8408 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8410 if(i==int(except_slot))
8411 continue;
8413 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8414 if( pItem && pItem->GetProto()->Socket[0].Color)
8416 tempcount += pItem->GetGemCountWithID(item);
8417 if( tempcount >= count )
8418 return true;
8423 return false;
8426 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8428 uint32 tempcount = 0;
8429 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8431 if(i==int(except_slot))
8432 continue;
8434 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8435 if (!pItem)
8436 continue;
8438 ItemPrototype const *pProto = pItem->GetProto();
8439 if (!pProto)
8440 continue;
8442 if (pProto->ItemLimitCategory == limitCategory)
8444 tempcount += pItem->GetCount();
8445 if( tempcount >= count )
8446 return true;
8449 if( pProto->Socket[0].Color)
8451 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8452 if( tempcount >= count )
8453 return true;
8457 return false;
8460 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8462 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8463 if( !pProto )
8465 if(no_space_count)
8466 *no_space_count = count;
8467 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8470 // no maximum
8471 if(pProto->MaxCount <= 0)
8472 return EQUIP_ERR_OK;
8474 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8476 if (curcount + count > uint32(pProto->MaxCount))
8478 if(no_space_count)
8479 *no_space_count = count +curcount - pProto->MaxCount;
8480 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8483 return EQUIP_ERR_OK;
8486 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8488 Item *pItem;
8489 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8491 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8492 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8493 return true;
8495 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8497 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8498 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8499 return true;
8501 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8503 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8505 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8507 pItem = GetItemByPos( i, j );
8508 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8509 return true;
8513 return false;
8516 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8518 Item* pItem2 = GetItemByPos( bag, slot );
8520 // ignore move item (this slot will be empty at move)
8521 if(pItem2==pSrcItem)
8522 pItem2 = NULL;
8524 uint32 need_space;
8526 // empty specific slot - check item fit to slot
8527 if( !pItem2 || swap )
8529 if( bag == INVENTORY_SLOT_BAG_0 )
8531 // keyring case
8532 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8533 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8535 // vanitypet case (not use, vanity pets stored as spells)
8536 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8537 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8539 // currencytoken case (disabled until proper implement)
8540 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8541 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8543 // guestbag case (not use)
8544 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END)
8545 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8547 // prevent cheating
8548 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8549 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8551 else
8553 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8554 if( !pBag )
8555 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8557 ItemPrototype const* pBagProto = pBag->GetProto();
8558 if( !pBagProto )
8559 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8561 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8562 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8565 // non empty stack with space
8566 need_space = pProto->GetMaxStackSize();
8568 // non empty slot, check item type
8569 else
8571 // check item type
8572 if(pItem2->GetEntry() != pProto->ItemId)
8573 return EQUIP_ERR_ITEM_CANT_STACK;
8575 // check free space
8576 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8577 return EQUIP_ERR_ITEM_CANT_STACK;
8579 // free stack space or infinity
8580 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8583 if(need_space > count)
8584 need_space = count;
8586 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8587 if(!newPosition.isContainedIn(dest))
8589 dest.push_back(newPosition);
8590 count -= need_space;
8592 return EQUIP_ERR_OK;
8595 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
8597 // skip specific bag already processed in first called _CanStoreItem_InBag
8598 if(bag==skip_bag)
8599 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8601 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8602 if( !pBag )
8603 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8605 ItemPrototype const* pBagProto = pBag->GetProto();
8606 if( !pBagProto )
8607 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8609 // specialized bag mode or non-specilized
8610 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8611 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8613 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8614 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8616 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8618 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8619 if(j==skip_slot)
8620 continue;
8622 Item* pItem2 = GetItemByPos( bag, j );
8624 // ignore move item (this slot will be empty at move)
8625 if(pItem2==pSrcItem)
8626 pItem2 = NULL;
8628 // if merge skip empty, if !merge skip non-empty
8629 if((pItem2!=NULL)!=merge)
8630 continue;
8632 if( pItem2 )
8634 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8636 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8637 if(need_space > count)
8638 need_space = count;
8640 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8641 if(!newPosition.isContainedIn(dest))
8643 dest.push_back(newPosition);
8644 count -= need_space;
8646 if(count==0)
8647 return EQUIP_ERR_OK;
8651 else
8653 uint32 need_space = pProto->GetMaxStackSize();
8654 if(need_space > count)
8655 need_space = count;
8657 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8658 if(!newPosition.isContainedIn(dest))
8660 dest.push_back(newPosition);
8661 count -= need_space;
8663 if(count==0)
8664 return EQUIP_ERR_OK;
8668 return EQUIP_ERR_OK;
8671 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
8673 for(uint32 j = slot_begin; j < slot_end; j++)
8675 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8676 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8677 continue;
8679 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8681 // ignore move item (this slot will be empty at move)
8682 if(pItem2==pSrcItem)
8683 pItem2 = NULL;
8685 // if merge skip empty, if !merge skip non-empty
8686 if((pItem2!=NULL)!=merge)
8687 continue;
8689 if( pItem2 )
8691 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8693 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8694 if(need_space > count)
8695 need_space = count;
8696 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8697 if(!newPosition.isContainedIn(dest))
8699 dest.push_back(newPosition);
8700 count -= need_space;
8702 if(count==0)
8703 return EQUIP_ERR_OK;
8707 else
8709 uint32 need_space = pProto->GetMaxStackSize();
8710 if(need_space > count)
8711 need_space = count;
8713 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8714 if(!newPosition.isContainedIn(dest))
8716 dest.push_back(newPosition);
8717 count -= need_space;
8719 if(count==0)
8720 return EQUIP_ERR_OK;
8724 return EQUIP_ERR_OK;
8727 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8729 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8731 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8732 if( !pProto )
8734 if(no_space_count)
8735 *no_space_count = count;
8736 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8739 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8741 if(no_space_count)
8742 *no_space_count = count;
8743 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8746 // check count of items (skip for auto move for same player from bank)
8747 uint32 no_similar_count = 0; // can't store this amount similar items
8748 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8749 if(res!=EQUIP_ERR_OK)
8751 if(count==no_similar_count)
8753 if(no_space_count)
8754 *no_space_count = no_similar_count;
8755 return res;
8757 count -= no_similar_count;
8760 // in specific slot
8761 if( bag != NULL_BAG && slot != NULL_SLOT )
8763 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8764 if(res!=EQUIP_ERR_OK)
8766 if(no_space_count)
8767 *no_space_count = count + no_similar_count;
8768 return res;
8771 if(count==0)
8773 if(no_similar_count==0)
8774 return EQUIP_ERR_OK;
8776 if(no_space_count)
8777 *no_space_count = count + no_similar_count;
8778 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8782 // not specific slot or have space for partly store only in specific slot
8784 // in specific bag
8785 if( bag != NULL_BAG )
8787 // search stack in bag for merge to
8788 if( pProto->Stackable != 1 )
8790 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8792 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8793 if(res!=EQUIP_ERR_OK)
8795 if(no_space_count)
8796 *no_space_count = count + no_similar_count;
8797 return res;
8800 if(count==0)
8802 if(no_similar_count==0)
8803 return EQUIP_ERR_OK;
8805 if(no_space_count)
8806 *no_space_count = count + no_similar_count;
8807 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8810 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8811 if(res!=EQUIP_ERR_OK)
8813 if(no_space_count)
8814 *no_space_count = count + no_similar_count;
8815 return res;
8818 if(count==0)
8820 if(no_similar_count==0)
8821 return EQUIP_ERR_OK;
8823 if(no_space_count)
8824 *no_space_count = count + no_similar_count;
8825 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8828 else // equipped bag
8830 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8831 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8832 if(res!=EQUIP_ERR_OK)
8833 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8835 if(res!=EQUIP_ERR_OK)
8837 if(no_space_count)
8838 *no_space_count = count + no_similar_count;
8839 return res;
8842 if(count==0)
8844 if(no_similar_count==0)
8845 return EQUIP_ERR_OK;
8847 if(no_space_count)
8848 *no_space_count = count + no_similar_count;
8849 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8854 // search free slot in bag for place to
8855 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8857 // search free slot - keyring case
8858 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8860 uint32 keyringSize = GetMaxKeyringSize();
8861 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8862 if(res!=EQUIP_ERR_OK)
8864 if(no_space_count)
8865 *no_space_count = count + no_similar_count;
8866 return res;
8869 if(count==0)
8871 if(no_similar_count==0)
8872 return EQUIP_ERR_OK;
8874 if(no_space_count)
8875 *no_space_count = count + no_similar_count;
8876 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8879 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8880 if(res!=EQUIP_ERR_OK)
8882 if(no_space_count)
8883 *no_space_count = count + no_similar_count;
8884 return res;
8887 if(count==0)
8889 if(no_similar_count==0)
8890 return EQUIP_ERR_OK;
8892 if(no_space_count)
8893 *no_space_count = count + no_similar_count;
8894 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8897 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8899 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8900 if(res!=EQUIP_ERR_OK)
8902 if(no_space_count)
8903 *no_space_count = count + no_similar_count;
8904 return res;
8907 if(count==0)
8909 if(no_similar_count==0)
8910 return EQUIP_ERR_OK;
8912 if(no_space_count)
8913 *no_space_count = count + no_similar_count;
8914 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8918 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8919 if(res!=EQUIP_ERR_OK)
8921 if(no_space_count)
8922 *no_space_count = count + no_similar_count;
8923 return res;
8926 if(count==0)
8928 if(no_similar_count==0)
8929 return EQUIP_ERR_OK;
8931 if(no_space_count)
8932 *no_space_count = count + no_similar_count;
8933 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8936 else // equipped bag
8938 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8939 if(res!=EQUIP_ERR_OK)
8940 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8942 if(res!=EQUIP_ERR_OK)
8944 if(no_space_count)
8945 *no_space_count = count + no_similar_count;
8946 return res;
8949 if(count==0)
8951 if(no_similar_count==0)
8952 return EQUIP_ERR_OK;
8954 if(no_space_count)
8955 *no_space_count = count + no_similar_count;
8956 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8961 // not specific bag or have space for partly store only in specific bag
8963 // search stack for merge to
8964 if( pProto->Stackable != 1 )
8966 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8967 if(res!=EQUIP_ERR_OK)
8969 if(no_space_count)
8970 *no_space_count = count + no_similar_count;
8971 return res;
8974 if(count==0)
8976 if(no_similar_count==0)
8977 return EQUIP_ERR_OK;
8979 if(no_space_count)
8980 *no_space_count = count + no_similar_count;
8981 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8984 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8985 if(res!=EQUIP_ERR_OK)
8987 if(no_space_count)
8988 *no_space_count = count + no_similar_count;
8989 return res;
8992 if(count==0)
8994 if(no_similar_count==0)
8995 return EQUIP_ERR_OK;
8997 if(no_space_count)
8998 *no_space_count = count + no_similar_count;
8999 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9002 if( pProto->BagFamily )
9004 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9006 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9007 if(res!=EQUIP_ERR_OK)
9008 continue;
9010 if(count==0)
9012 if(no_similar_count==0)
9013 return EQUIP_ERR_OK;
9015 if(no_space_count)
9016 *no_space_count = count + no_similar_count;
9017 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9022 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9024 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9025 if(res!=EQUIP_ERR_OK)
9026 continue;
9028 if(count==0)
9030 if(no_similar_count==0)
9031 return EQUIP_ERR_OK;
9033 if(no_space_count)
9034 *no_space_count = count + no_similar_count;
9035 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9040 // search free slot - special bag case
9041 if( pProto->BagFamily )
9043 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9045 uint32 keyringSize = GetMaxKeyringSize();
9046 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9047 if(res!=EQUIP_ERR_OK)
9049 if(no_space_count)
9050 *no_space_count = count + no_similar_count;
9051 return res;
9054 if(count==0)
9056 if(no_similar_count==0)
9057 return EQUIP_ERR_OK;
9059 if(no_space_count)
9060 *no_space_count = count + no_similar_count;
9061 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9064 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9066 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9067 if(res!=EQUIP_ERR_OK)
9069 if(no_space_count)
9070 *no_space_count = count + no_similar_count;
9071 return res;
9074 if(count==0)
9076 if(no_similar_count==0)
9077 return EQUIP_ERR_OK;
9079 if(no_space_count)
9080 *no_space_count = count + no_similar_count;
9081 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9085 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9087 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9088 if(res!=EQUIP_ERR_OK)
9089 continue;
9091 if(count==0)
9093 if(no_similar_count==0)
9094 return EQUIP_ERR_OK;
9096 if(no_space_count)
9097 *no_space_count = count + no_similar_count;
9098 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9103 // search free slot
9104 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9105 if(res!=EQUIP_ERR_OK)
9107 if(no_space_count)
9108 *no_space_count = count + no_similar_count;
9109 return res;
9112 if(count==0)
9114 if(no_similar_count==0)
9115 return EQUIP_ERR_OK;
9117 if(no_space_count)
9118 *no_space_count = count + no_similar_count;
9119 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9122 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9124 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9125 if(res!=EQUIP_ERR_OK)
9126 continue;
9128 if(count==0)
9130 if(no_similar_count==0)
9131 return EQUIP_ERR_OK;
9133 if(no_space_count)
9134 *no_space_count = count + no_similar_count;
9135 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9139 if(no_space_count)
9140 *no_space_count = count + no_similar_count;
9142 return EQUIP_ERR_INVENTORY_FULL;
9145 //////////////////////////////////////////////////////////////////////////
9146 uint8 Player::CanStoreItems( Item **pItems,int count) const
9148 Item *pItem2;
9150 // fill space table
9151 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9152 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9153 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9154 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9156 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9157 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9158 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9159 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9161 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9163 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9165 if (pItem2 && !pItem2->IsInTrade())
9167 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9171 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9173 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9175 if (pItem2 && !pItem2->IsInTrade())
9177 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9181 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9183 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9185 if (pItem2 && !pItem2->IsInTrade())
9187 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9191 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9193 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9195 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9197 pItem2 = GetItemByPos( i, j );
9198 if (pItem2 && !pItem2->IsInTrade())
9200 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9206 // check free space for all items
9207 for (int k=0;k<count;k++)
9209 Item *pItem = pItems[k];
9211 // no item
9212 if (!pItem) continue;
9214 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9215 ItemPrototype const *pProto = pItem->GetProto();
9217 // strange item
9218 if( !pProto )
9219 return EQUIP_ERR_ITEM_NOT_FOUND;
9221 // item it 'bind'
9222 if(pItem->IsBindedNotWith(GetGUID()))
9223 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9225 Bag *pBag;
9226 ItemPrototype const *pBagProto;
9228 // item is 'one item only'
9229 uint8 res = CanTakeMoreSimilarItems(pItem);
9230 if(res != EQUIP_ERR_OK)
9231 return res;
9233 // search stack for merge to
9234 if( pProto->Stackable != 1 )
9236 bool b_found = false;
9238 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9240 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9241 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9243 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9244 b_found = true;
9245 break;
9248 if (b_found) continue;
9250 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9252 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9253 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9255 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9256 b_found = true;
9257 break;
9260 if (b_found) continue;
9262 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9264 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9265 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9267 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9268 b_found = true;
9269 break;
9272 if (b_found) continue;
9274 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9276 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9277 if( pBag )
9279 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9281 pItem2 = GetItemByPos( t, j );
9282 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9284 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9285 b_found = true;
9286 break;
9291 if (b_found) continue;
9294 // special bag case
9295 if( pProto->BagFamily )
9297 bool b_found = false;
9298 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9300 uint32 keyringSize = GetMaxKeyringSize();
9301 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9303 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9305 inv_keys[t-KEYRING_SLOT_START] = 1;
9306 b_found = true;
9307 break;
9312 if (b_found) continue;
9314 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9316 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9318 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9320 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9321 b_found = true;
9322 break;
9327 if (b_found) continue;
9329 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9331 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9332 if( pBag )
9334 pBagProto = pBag->GetProto();
9336 // not plain container check
9337 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9338 ItemCanGoIntoBag(pProto,pBagProto) )
9340 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9342 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9344 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9345 b_found = true;
9346 break;
9352 if (b_found) continue;
9355 // search free slot
9356 bool b_found = false;
9357 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9359 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9361 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9362 b_found = true;
9363 break;
9366 if (b_found) continue;
9368 // search free slot in bags
9369 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9371 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9372 if( pBag )
9374 pBagProto = pBag->GetProto();
9376 // special bag already checked
9377 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9378 continue;
9380 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9382 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9384 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9385 b_found = true;
9386 break;
9392 // no free slot found?
9393 if (!b_found)
9394 return EQUIP_ERR_INVENTORY_FULL;
9397 return EQUIP_ERR_OK;
9400 //////////////////////////////////////////////////////////////////////////
9401 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9403 dest = 0;
9404 Item *pItem = Item::CreateItem( item, 1, this );
9405 if( pItem )
9407 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9408 delete pItem;
9409 return result;
9412 return EQUIP_ERR_ITEM_NOT_FOUND;
9415 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9417 dest = 0;
9418 if( pItem )
9420 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9421 ItemPrototype const *pProto = pItem->GetProto();
9422 if( pProto )
9424 if(pItem->IsBindedNotWith(GetGUID()))
9425 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9427 // check count of items (skip for auto move for same player from bank)
9428 uint8 res = CanTakeMoreSimilarItems(pItem);
9429 if(res != EQUIP_ERR_OK)
9430 return res;
9432 // check this only in game
9433 if(not_loading)
9435 // May be here should be more stronger checks; STUNNED checked
9436 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9437 if (hasUnitState(UNIT_STAT_STUNNED))
9438 return EQUIP_ERR_YOU_ARE_STUNNED;
9440 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9441 // - combat
9442 // - in-progress arenas
9443 if( !pProto->CanChangeEquipStateInCombat() )
9445 if( isInCombat() )
9446 return EQUIP_ERR_NOT_IN_COMBAT;
9448 if(BattleGround* bg = GetBattleGround())
9449 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9450 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9453 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9454 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9456 if(IsNonMeleeSpellCasted(false))
9457 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9460 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9461 if( eslot == NULL_SLOT )
9462 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9464 uint8 msg = CanUseItem( pItem , not_loading );
9465 if( msg != EQUIP_ERR_OK )
9466 return msg;
9467 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9468 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9470 // if swap ignore item (equipped also)
9471 if(uint8 res = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9472 return res;
9474 // check unique-equipped special item classes
9475 if (pProto->Class == ITEM_CLASS_QUIVER)
9477 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9479 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9481 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9483 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9485 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9486 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9487 else
9488 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9495 uint32 type = pProto->InventoryType;
9497 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9499 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9501 if(!CanDualWield())
9502 return EQUIP_ERR_CANT_DUAL_WIELD;
9504 else if (type == INVTYPE_2HWEAPON)
9506 if(!CanDualWield() || !CanTitanGrip())
9507 return EQUIP_ERR_CANT_DUAL_WIELD;
9510 if(IsTwoHandUsed())
9511 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9514 // equip two-hand weapon case (with possible unequip 2 items)
9515 if( type == INVTYPE_2HWEAPON )
9517 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9519 if (!CanTitanGrip())
9520 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9522 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9523 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9525 if (!CanTitanGrip())
9527 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9528 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9529 ItemPosCountVec off_dest;
9530 if( offItem && (!not_loading ||
9531 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9532 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9533 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9536 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9537 return EQUIP_ERR_OK;
9540 if( !swap )
9541 return EQUIP_ERR_ITEM_NOT_FOUND;
9542 else
9543 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9546 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9548 // Applied only to equipped items and bank bags
9549 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9550 return EQUIP_ERR_OK;
9552 Item* pItem = GetItemByPos(pos);
9554 // Applied only to existed equipped item
9555 if( !pItem )
9556 return EQUIP_ERR_OK;
9558 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9560 ItemPrototype const *pProto = pItem->GetProto();
9561 if( !pProto )
9562 return EQUIP_ERR_ITEM_NOT_FOUND;
9564 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9565 // - combat
9566 // - in-progress arenas
9567 if( !pProto->CanChangeEquipStateInCombat() )
9569 if( isInCombat() )
9570 return EQUIP_ERR_NOT_IN_COMBAT;
9572 if(BattleGround* bg = GetBattleGround())
9573 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9574 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9577 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9578 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9580 return EQUIP_ERR_OK;
9583 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9585 if( !pItem )
9586 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9588 uint32 count = pItem->GetCount();
9590 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9591 ItemPrototype const *pProto = pItem->GetProto();
9592 if( !pProto )
9593 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9595 if( pItem->IsBindedNotWith(GetGUID()) )
9596 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9598 // check count of items (skip for auto move for same player from bank)
9599 uint8 res = CanTakeMoreSimilarItems(pItem);
9600 if(res != EQUIP_ERR_OK)
9601 return res;
9603 // in specific slot
9604 if( bag != NULL_BAG && slot != NULL_SLOT )
9606 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9608 if (!pItem->IsBag())
9609 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9611 Bag *pBag = (Bag*)pItem;
9612 if( !HasBankBagSlot( slot ) )
9613 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9615 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9616 return cantuse;
9619 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9620 if(res!=EQUIP_ERR_OK)
9621 return res;
9623 if(count==0)
9624 return EQUIP_ERR_OK;
9627 // not specific slot or have space for partly store only in specific slot
9629 // in specific bag
9630 if( bag != NULL_BAG )
9632 if( pProto->InventoryType == INVTYPE_BAG )
9634 Bag *pBag = (Bag*)pItem;
9635 if( pBag && !pBag->IsEmpty() )
9636 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9639 // search stack in bag for merge to
9640 if( pProto->Stackable != 1 )
9642 if( bag == INVENTORY_SLOT_BAG_0 )
9644 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9645 if(res!=EQUIP_ERR_OK)
9646 return res;
9648 if(count==0)
9649 return EQUIP_ERR_OK;
9651 else
9653 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9654 if(res!=EQUIP_ERR_OK)
9655 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9657 if(res!=EQUIP_ERR_OK)
9658 return res;
9660 if(count==0)
9661 return EQUIP_ERR_OK;
9665 // search free slot in bag
9666 if( bag == INVENTORY_SLOT_BAG_0 )
9668 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9669 if(res!=EQUIP_ERR_OK)
9670 return res;
9672 if(count==0)
9673 return EQUIP_ERR_OK;
9675 else
9677 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9678 if(res!=EQUIP_ERR_OK)
9679 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9681 if(res!=EQUIP_ERR_OK)
9682 return res;
9684 if(count==0)
9685 return EQUIP_ERR_OK;
9689 // not specific bag or have space for partly store only in specific bag
9691 // search stack for merge to
9692 if( pProto->Stackable != 1 )
9694 // in slots
9695 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9696 if(res!=EQUIP_ERR_OK)
9697 return res;
9699 if(count==0)
9700 return EQUIP_ERR_OK;
9702 // in special bags
9703 if( pProto->BagFamily )
9705 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9707 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9708 if(res!=EQUIP_ERR_OK)
9709 continue;
9711 if(count==0)
9712 return EQUIP_ERR_OK;
9716 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9718 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9719 if(res!=EQUIP_ERR_OK)
9720 continue;
9722 if(count==0)
9723 return EQUIP_ERR_OK;
9727 // search free place in special bag
9728 if( pProto->BagFamily )
9730 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9732 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9733 if(res!=EQUIP_ERR_OK)
9734 continue;
9736 if(count==0)
9737 return EQUIP_ERR_OK;
9741 // search free space
9742 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9743 if(res!=EQUIP_ERR_OK)
9744 return res;
9746 if(count==0)
9747 return EQUIP_ERR_OK;
9749 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9751 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9752 if(res!=EQUIP_ERR_OK)
9753 continue;
9755 if(count==0)
9756 return EQUIP_ERR_OK;
9758 return EQUIP_ERR_BANK_FULL;
9761 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9763 if( pItem )
9765 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9766 if( !isAlive() && not_loading )
9767 return EQUIP_ERR_YOU_ARE_DEAD;
9768 //if( isStunned() )
9769 // return EQUIP_ERR_YOU_ARE_STUNNED;
9770 ItemPrototype const *pProto = pItem->GetProto();
9771 if( pProto )
9773 if( pItem->IsBindedNotWith(GetGUID()) )
9774 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9775 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9776 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9777 if( pItem->GetSkill() != 0 )
9779 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9780 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9782 if( pProto->RequiredSkill != 0 )
9784 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9785 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9786 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9787 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9789 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9790 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9791 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9792 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9793 if( getLevel() < pProto->RequiredLevel )
9794 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9795 return EQUIP_ERR_OK;
9798 return EQUIP_ERR_ITEM_NOT_FOUND;
9801 bool Player::CanUseItem( ItemPrototype const *pProto )
9803 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9805 if( pProto )
9807 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9808 return false;
9809 if( pProto->RequiredSkill != 0 )
9811 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9812 return false;
9813 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9814 return false;
9816 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9817 return false;
9818 if( getLevel() < pProto->RequiredLevel )
9819 return false;
9820 return true;
9822 return false;
9825 uint8 Player::CanUseAmmo( uint32 item ) const
9827 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9828 if( !isAlive() )
9829 return EQUIP_ERR_YOU_ARE_DEAD;
9830 //if( isStunned() )
9831 // return EQUIP_ERR_YOU_ARE_STUNNED;
9832 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9833 if( pProto )
9835 if( pProto->InventoryType!= INVTYPE_AMMO )
9836 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9837 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9838 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9839 if( pProto->RequiredSkill != 0 )
9841 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9842 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9843 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9844 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9846 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9847 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9848 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9849 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9851 if( getLevel() < pProto->RequiredLevel )
9852 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9854 // Requires No Ammo
9855 if(GetDummyAura(46699))
9856 return EQUIP_ERR_BAG_FULL6;
9858 return EQUIP_ERR_OK;
9860 return EQUIP_ERR_ITEM_NOT_FOUND;
9863 void Player::SetAmmo( uint32 item )
9865 if(!item)
9866 return;
9868 // already set
9869 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9870 return;
9872 // check ammo
9873 if(item)
9875 uint8 msg = CanUseAmmo( item );
9876 if( msg != EQUIP_ERR_OK )
9878 SendEquipError( msg, NULL, NULL );
9879 return;
9883 SetUInt32Value(PLAYER_AMMO_ID, item);
9885 _ApplyAmmoBonuses();
9888 void Player::RemoveAmmo()
9890 SetUInt32Value(PLAYER_AMMO_ID, 0);
9892 m_ammoDPS = 0.0f;
9894 if(CanModifyStats())
9895 UpdateDamagePhysical(RANGED_ATTACK);
9898 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9899 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9901 uint32 count = 0;
9902 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9903 count += itr->count;
9905 Item *pItem = Item::CreateItem( item, count, this );
9906 if( pItem )
9908 ItemAddedQuestCheck( item, count );
9909 if(randomPropertyId)
9910 pItem->SetItemRandomProperties(randomPropertyId);
9911 pItem = StoreItem( dest, pItem, update );
9913 return pItem;
9916 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9918 if( !pItem )
9919 return NULL;
9921 Item* lastItem = pItem;
9922 uint32 entry = pItem->GetEntry();
9923 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9925 uint16 pos = itr->pos;
9926 uint32 count = itr->count;
9928 ++itr;
9930 if(itr == dest.end())
9932 lastItem = _StoreItem(pos,pItem,count,false,update);
9933 break;
9936 lastItem = _StoreItem(pos,pItem,count,true,update);
9938 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
9939 return lastItem;
9942 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9943 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9945 if( !pItem )
9946 return NULL;
9948 uint8 bag = pos >> 8;
9949 uint8 slot = pos & 255;
9951 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
9953 Item *pItem2 = GetItemByPos( bag, slot );
9955 if( !pItem2 )
9957 if(clone)
9958 pItem = pItem->CloneItem(count,this);
9959 else
9960 pItem->SetCount(count);
9962 if(!pItem)
9963 return NULL;
9965 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9966 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
9967 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9968 pItem->SetBinding( true );
9970 if( bag == INVENTORY_SLOT_BAG_0 )
9972 m_items[slot] = pItem;
9973 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
9974 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
9975 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
9977 pItem->SetSlot( slot );
9978 pItem->SetContainer( NULL );
9980 // need update known currency
9981 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
9982 UpdateKnownCurrencies(pItem->GetEntry(),true);
9984 if( IsInWorld() && update )
9986 pItem->AddToWorld();
9987 pItem->SendUpdateToPlayer( this );
9990 pItem->SetState(ITEM_CHANGED, this);
9992 else
9994 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9995 if( pBag )
9997 pBag->StoreItem( slot, pItem, update );
9998 if( IsInWorld() && update )
10000 pItem->AddToWorld();
10001 pItem->SendUpdateToPlayer( this );
10003 pItem->SetState(ITEM_CHANGED, this);
10004 pBag->SetState(ITEM_CHANGED, this);
10008 AddEnchantmentDurations(pItem);
10009 AddItemDurations(pItem);
10011 return pItem;
10013 else
10015 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10016 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10017 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10018 pItem2->SetBinding( true );
10020 pItem2->SetCount( pItem2->GetCount() + count );
10021 if( IsInWorld() && update )
10022 pItem2->SendUpdateToPlayer( this );
10024 if(!clone)
10026 // delete item (it not in any slot currently)
10027 if( IsInWorld() && update )
10029 pItem->RemoveFromWorld();
10030 pItem->DestroyForPlayer( this );
10033 RemoveEnchantmentDurations(pItem);
10034 RemoveItemDurations(pItem);
10036 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10037 pItem->SetState(ITEM_REMOVED, this);
10039 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10040 AddEnchantmentDurations(pItem2);
10042 pItem2->SetState(ITEM_CHANGED, this);
10044 return pItem2;
10048 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10050 Item *pItem = Item::CreateItem( item, 1, this );
10051 if( pItem )
10053 ItemAddedQuestCheck( item, 1 );
10054 Item * retItem = EquipItem( pos, pItem, update );
10056 return retItem;
10058 return NULL;
10061 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10063 if( pItem )
10065 AddEnchantmentDurations(pItem);
10066 AddItemDurations(pItem);
10068 uint8 bag = pos >> 8;
10069 uint8 slot = pos & 255;
10071 Item *pItem2 = GetItemByPos( bag, slot );
10073 if( !pItem2 )
10075 VisualizeItem( slot, pItem);
10077 if(isAlive())
10079 ItemPrototype const *pProto = pItem->GetProto();
10081 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10082 if(pProto && pProto->ItemSet)
10083 AddItemsSetItem(this,pItem);
10085 _ApplyItemMods(pItem, slot, true);
10087 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10089 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10091 if (getClass() == CLASS_ROGUE)
10092 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10094 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10096 if (!spellProto)
10097 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10098 else
10100 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10102 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10103 data << uint64(GetGUID());
10104 data << uint8(1);
10105 data << uint32(cooldownSpell);
10106 data << uint32(0);
10107 GetSession()->SendPacket(&data);
10112 if( IsInWorld() && update )
10114 pItem->AddToWorld();
10115 pItem->SendUpdateToPlayer( this );
10118 ApplyEquipCooldown(pItem);
10120 if( slot == EQUIPMENT_SLOT_MAINHAND )
10121 UpdateExpertise(BASE_ATTACK);
10122 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10123 UpdateExpertise(OFF_ATTACK);
10125 else
10127 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10128 if( IsInWorld() && update )
10129 pItem2->SendUpdateToPlayer( this );
10131 // delete item (it not in any slot currently)
10132 //pItem->DeleteFromDB();
10133 if( IsInWorld() && update )
10135 pItem->RemoveFromWorld();
10136 pItem->DestroyForPlayer( this );
10139 RemoveEnchantmentDurations(pItem);
10140 RemoveItemDurations(pItem);
10142 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10143 pItem->SetState(ITEM_REMOVED, this);
10144 pItem2->SetState(ITEM_CHANGED, this);
10146 ApplyEquipCooldown(pItem2);
10148 return pItem2;
10152 // only for full equip instead adding to stack
10153 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10154 return pItem;
10157 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10159 if( pItem )
10161 AddEnchantmentDurations(pItem);
10162 AddItemDurations(pItem);
10164 uint8 slot = pos & 255;
10165 VisualizeItem( slot, pItem);
10167 if( IsInWorld() )
10169 pItem->AddToWorld();
10170 pItem->SendUpdateToPlayer( this );
10175 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10177 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10178 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10179 // entry // Size: 1
10180 // inspected enchantments // Size: 6
10181 // ? // Size: 5
10182 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10183 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10184 // // = 16
10186 if(pItem)
10188 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10190 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10191 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10193 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10194 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10196 // Use SetInt16Value to prevent set high part to FFFF for negative value
10197 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10198 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10200 else
10202 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10204 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10205 SetUInt32Value(VisibleBase + 0, 0);
10207 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10208 SetUInt32Value(VisibleBase + 1 + i, 0);
10210 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10211 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10215 void Player::VisualizeItem( uint8 slot, Item *pItem)
10217 if(!pItem)
10218 return;
10220 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10221 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10222 pItem->SetBinding( true );
10224 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10226 m_items[slot] = pItem;
10227 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10228 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10229 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10230 pItem->SetSlot( slot );
10231 pItem->SetContainer( NULL );
10233 if( slot < EQUIPMENT_SLOT_END )
10234 SetVisibleItemSlot(slot,pItem);
10236 pItem->SetState(ITEM_CHANGED, this);
10239 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10241 // note: removeitem does not actually change the item
10242 // it only takes the item out of storage temporarily
10243 // note2: if removeitem is to be used for delinking
10244 // the item must be removed from the player's updatequeue
10246 Item *pItem = GetItemByPos( bag, slot );
10247 if( pItem )
10249 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10251 RemoveEnchantmentDurations(pItem);
10252 RemoveItemDurations(pItem);
10254 if( bag == INVENTORY_SLOT_BAG_0 )
10256 if ( slot < INVENTORY_SLOT_BAG_END )
10258 ItemPrototype const *pProto = pItem->GetProto();
10259 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10261 if(pProto && pProto->ItemSet)
10262 RemoveItemsSetItem(this,pProto);
10264 _ApplyItemMods(pItem, slot, false);
10266 // remove item dependent auras and casts (only weapon and armor slots)
10267 if(slot < EQUIPMENT_SLOT_END)
10269 RemoveItemDependentAurasAndCasts(pItem);
10271 // remove held enchantments, update expertise
10272 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10274 if (pItem->GetItemSuffixFactor())
10276 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10277 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10279 else
10281 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10282 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10285 UpdateExpertise(BASE_ATTACK);
10287 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10288 UpdateExpertise(OFF_ATTACK);
10291 // need update known currency
10292 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10293 UpdateKnownCurrencies(pItem->GetEntry(),false);
10295 m_items[slot] = NULL;
10296 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10298 if ( slot < EQUIPMENT_SLOT_END )
10299 SetVisibleItemSlot(slot,NULL);
10301 else
10303 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10304 if( pBag )
10305 pBag->RemoveItem(slot, update);
10307 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10308 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10309 pItem->SetSlot( NULL_SLOT );
10310 if( IsInWorld() && update )
10311 pItem->SendUpdateToPlayer( this );
10315 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10316 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10318 if(Item* it = GetItemByPos(bag,slot))
10320 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10321 RemoveItem( bag,slot,update);
10322 it->RemoveFromUpdateQueueOf(this);
10323 if(it->IsInWorld())
10325 it->RemoveFromWorld();
10326 it->DestroyForPlayer( this );
10331 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10332 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10334 // update quest counters
10335 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10337 // store item
10338 Item* pLastItem = StoreItem( dest, pItem, update);
10340 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10341 if(pLastItem==pItem)
10343 // update owner for last item (this can be original item with wrong owner
10344 if(pLastItem->GetOwnerGUID() != GetGUID())
10345 pLastItem->SetOwnerGUID(GetGUID());
10347 // if this original item then it need create record in inventory
10348 // in case trade we already have item in other player inventory
10349 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10353 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10355 Item *pItem = GetItemByPos( bag, slot );
10356 if( pItem )
10358 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10360 // start from destroy contained items (only equipped bag can have its)
10361 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10363 for (int i = 0; i < MAX_BAG_SIZE; i++)
10364 DestroyItem(slot,i,update);
10367 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10368 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10370 RemoveEnchantmentDurations(pItem);
10371 RemoveItemDurations(pItem);
10373 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10375 if( bag == INVENTORY_SLOT_BAG_0 )
10377 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10379 // equipment and equipped bags can have applied bonuses
10380 if ( slot < INVENTORY_SLOT_BAG_END )
10382 ItemPrototype const *pProto = pItem->GetProto();
10384 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10385 if(pProto && pProto->ItemSet)
10386 RemoveItemsSetItem(this,pProto);
10388 _ApplyItemMods(pItem, slot, false);
10391 if ( slot < EQUIPMENT_SLOT_END )
10393 // remove item dependent auras and casts (only weapon and armor slots)
10394 RemoveItemDependentAurasAndCasts(pItem);
10396 // update expertise
10397 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10398 UpdateExpertise(BASE_ATTACK);
10399 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10400 UpdateExpertise(OFF_ATTACK);
10402 // equipment visual show
10403 SetVisibleItemSlot(slot,NULL);
10405 // need update known currency
10406 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10407 UpdateKnownCurrencies(pItem->GetEntry(),false);
10409 m_items[slot] = NULL;
10411 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10412 pBag->RemoveItem(slot, update);
10414 if( IsInWorld() && update )
10416 pItem->RemoveFromWorld();
10417 pItem->DestroyForPlayer(this);
10420 //pItem->SetOwnerGUID(0);
10421 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10422 pItem->SetSlot( NULL_SLOT );
10423 pItem->SetState(ITEM_REMOVED, this);
10427 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10429 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10430 uint32 remcount = 0;
10432 // in inventory
10433 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10435 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10437 if (pItem->GetEntry() == item)
10439 if (pItem->GetCount() + remcount <= count)
10441 // all items in inventory can unequipped
10442 remcount += pItem->GetCount();
10443 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10445 if (remcount >=count)
10446 return;
10448 else
10450 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10451 pItem->SetCount( pItem->GetCount() - count + remcount );
10452 if (IsInWorld() & update)
10453 pItem->SendUpdateToPlayer( this );
10454 pItem->SetState(ITEM_CHANGED, this);
10455 return;
10461 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10463 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10465 if (pItem->GetEntry() == item)
10467 if (pItem->GetCount() + remcount <= count)
10469 // all keys can be unequipped
10470 remcount += pItem->GetCount();
10471 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10473 if (remcount >=count)
10474 return;
10476 else
10478 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10479 pItem->SetCount( pItem->GetCount() - count + remcount );
10480 if (IsInWorld() & update)
10481 pItem->SendUpdateToPlayer( this );
10482 pItem->SetState(ITEM_CHANGED, this);
10483 return;
10489 // in inventory bags
10490 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10492 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10494 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10496 if(Item* pItem = pBag->GetItemByPos(j))
10498 if (pItem->GetEntry() == item)
10500 // all items in bags can be unequipped
10501 if (pItem->GetCount() + remcount <= count)
10503 remcount += pItem->GetCount();
10504 DestroyItem( i, j, update );
10506 if (remcount >=count)
10507 return;
10509 else
10511 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10512 pItem->SetCount( pItem->GetCount() - count + remcount );
10513 if (IsInWorld() && update)
10514 pItem->SendUpdateToPlayer( this );
10515 pItem->SetState(ITEM_CHANGED, this);
10516 return;
10524 // in equipment and bag list
10525 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10527 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10529 if (pItem && pItem->GetEntry() == item)
10531 if (pItem->GetCount() + remcount <= count)
10533 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10535 remcount += pItem->GetCount();
10536 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10538 if (remcount >=count)
10539 return;
10542 else
10544 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10545 pItem->SetCount( pItem->GetCount() - count + remcount );
10546 if (IsInWorld() & update)
10547 pItem->SendUpdateToPlayer( this );
10548 pItem->SetState(ITEM_CHANGED, this);
10549 return;
10556 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10558 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10560 // in inventory
10561 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10562 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10563 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10564 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10566 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10567 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10568 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10569 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10571 // in inventory bags
10572 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10573 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10574 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10575 if (Item* pItem = pBag->GetItemByPos(j))
10576 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10577 DestroyItem( i, j, update);
10579 // in equipment and bag list
10580 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10581 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10582 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone))
10583 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10586 void Player::DestroyConjuredItems( bool update )
10588 // used when entering arena
10589 // destroys all conjured items
10590 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10592 // in inventory
10593 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10594 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10595 if (pItem->IsConjuredConsumable())
10596 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10598 // in inventory bags
10599 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10600 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10601 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10602 if (Item* pItem = pBag->GetItemByPos(j))
10603 if (pItem->IsConjuredConsumable())
10604 DestroyItem( i, j, update);
10606 // in equipment and bag list
10607 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10608 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10609 if (pItem->IsConjuredConsumable())
10610 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10613 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10615 if(!pItem)
10616 return;
10618 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10620 if( pItem->GetCount() <= count )
10622 count-= pItem->GetCount();
10624 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10626 else
10628 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10629 pItem->SetCount( pItem->GetCount() - count );
10630 count = 0;
10631 if( IsInWorld() & update )
10632 pItem->SendUpdateToPlayer( this );
10633 pItem->SetState(ITEM_CHANGED, this);
10637 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10639 uint8 srcbag = src >> 8;
10640 uint8 srcslot = src & 255;
10642 uint8 dstbag = dst >> 8;
10643 uint8 dstslot = dst & 255;
10645 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10646 if( !pSrcItem )
10648 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10649 return;
10652 // not let split all items (can be only at cheating)
10653 if(pSrcItem->GetCount() == count)
10655 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10656 return;
10659 // not let split more existed items (can be only at cheating)
10660 if(pSrcItem->GetCount() < count)
10662 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10663 return;
10666 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10668 //best error message found for attempting to split while looting
10669 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10670 return;
10673 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10674 Item *pNewItem = pSrcItem->CloneItem( count, this );
10675 if( !pNewItem )
10677 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10678 return;
10681 if( IsInventoryPos( dst ) )
10683 // change item amount before check (for unique max count check)
10684 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10686 ItemPosCountVec dest;
10687 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10688 if( msg != EQUIP_ERR_OK )
10690 delete pNewItem;
10691 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10692 SendEquipError( msg, pSrcItem, NULL );
10693 return;
10696 if( IsInWorld() )
10697 pSrcItem->SendUpdateToPlayer( this );
10698 pSrcItem->SetState(ITEM_CHANGED, this);
10699 StoreItem( dest, pNewItem, true);
10701 else if( IsBankPos ( dst ) )
10703 // change item amount before check (for unique max count check)
10704 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10706 ItemPosCountVec dest;
10707 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10708 if( msg != EQUIP_ERR_OK )
10710 delete pNewItem;
10711 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10712 SendEquipError( msg, pSrcItem, NULL );
10713 return;
10716 if( IsInWorld() )
10717 pSrcItem->SendUpdateToPlayer( this );
10718 pSrcItem->SetState(ITEM_CHANGED, this);
10719 BankItem( dest, pNewItem, true);
10721 else if( IsEquipmentPos ( dst ) )
10723 // change item amount before check (for unique max count check), provide space for splitted items
10724 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10726 uint16 dest;
10727 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10728 if( msg != EQUIP_ERR_OK )
10730 delete pNewItem;
10731 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10732 SendEquipError( msg, pSrcItem, NULL );
10733 return;
10736 if( IsInWorld() )
10737 pSrcItem->SendUpdateToPlayer( this );
10738 pSrcItem->SetState(ITEM_CHANGED, this);
10739 EquipItem( dest, pNewItem, true);
10740 AutoUnequipOffhandIfNeed();
10744 void Player::SwapItem( uint16 src, uint16 dst )
10746 uint8 srcbag = src >> 8;
10747 uint8 srcslot = src & 255;
10749 uint8 dstbag = dst >> 8;
10750 uint8 dstslot = dst & 255;
10752 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10753 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10755 if( !pSrcItem )
10756 return;
10758 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10760 if(!isAlive() )
10762 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10763 return;
10766 // SRC checks
10768 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10770 //best error message found for attempting to swap while looting
10771 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10772 return;
10775 // check unequip potability for equipped items and bank bags
10776 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10778 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10779 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10780 if(msg != EQUIP_ERR_OK)
10782 SendEquipError( msg, pSrcItem, pDstItem );
10783 return;
10787 // prevent put equipped/bank bag in self
10788 if( IsBagPos ( src ) && srcslot == dstbag)
10790 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10791 return;
10794 // DST checks
10796 if (pDstItem)
10798 if(pDstItem->m_lootGenerated) // prevent swap looting item
10800 //best error message found for attempting to swap while looting
10801 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10802 return;
10805 // check unequip potability for equipped items and bank bags
10806 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10808 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10809 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10810 if(msg != EQUIP_ERR_OK)
10812 SendEquipError( msg, pSrcItem, pDstItem );
10813 return;
10818 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10819 // or swap empty bag with another empty or not empty bag (with items exchange)
10821 // Move case
10822 if( !pDstItem )
10824 if( IsInventoryPos( dst ) )
10826 ItemPosCountVec dest;
10827 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10828 if( msg != EQUIP_ERR_OK )
10830 SendEquipError( msg, pSrcItem, NULL );
10831 return;
10834 RemoveItem(srcbag, srcslot, true);
10835 StoreItem( dest, pSrcItem, true);
10837 else if( IsBankPos ( dst ) )
10839 ItemPosCountVec dest;
10840 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10841 if( msg != EQUIP_ERR_OK )
10843 SendEquipError( msg, pSrcItem, NULL );
10844 return;
10847 RemoveItem(srcbag, srcslot, true);
10848 BankItem( dest, pSrcItem, true);
10850 else if( IsEquipmentPos ( dst ) )
10852 uint16 dest;
10853 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10854 if( msg != EQUIP_ERR_OK )
10856 SendEquipError( msg, pSrcItem, NULL );
10857 return;
10860 RemoveItem(srcbag, srcslot, true);
10861 EquipItem( dest, pSrcItem, true);
10862 AutoUnequipOffhandIfNeed();
10865 return;
10868 // attempt merge to / fill target item
10869 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10871 uint8 msg;
10872 ItemPosCountVec sDest;
10873 uint16 eDest;
10874 if( IsInventoryPos( dst ) )
10875 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10876 else if( IsBankPos ( dst ) )
10877 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10878 else if( IsEquipmentPos ( dst ) )
10879 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10880 else
10881 return;
10883 // can be merge/fill
10884 if(msg == EQUIP_ERR_OK)
10886 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10888 RemoveItem(srcbag, srcslot, true);
10890 if( IsInventoryPos( dst ) )
10891 StoreItem( sDest, pSrcItem, true);
10892 else if( IsBankPos ( dst ) )
10893 BankItem( sDest, pSrcItem, true);
10894 else if( IsEquipmentPos ( dst ) )
10896 EquipItem( eDest, pSrcItem, true);
10897 AutoUnequipOffhandIfNeed();
10900 else
10902 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10903 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10904 pSrcItem->SetState(ITEM_CHANGED, this);
10905 pDstItem->SetState(ITEM_CHANGED, this);
10906 if( IsInWorld() )
10908 pSrcItem->SendUpdateToPlayer( this );
10909 pDstItem->SendUpdateToPlayer( this );
10912 return;
10916 // impossible merge/fill, do real swap
10917 uint8 msg;
10919 // check src->dest move possibility
10920 ItemPosCountVec sDest;
10921 uint16 eDest;
10922 if( IsInventoryPos( dst ) )
10923 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10924 else if( IsBankPos( dst ) )
10925 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10926 else if( IsEquipmentPos( dst ) )
10928 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10929 if( msg == EQUIP_ERR_OK )
10930 msg = CanUnequipItem( eDest, true );
10933 if( msg != EQUIP_ERR_OK )
10935 SendEquipError( msg, pSrcItem, pDstItem );
10936 return;
10939 // check dest->src move possibility
10940 ItemPosCountVec sDest2;
10941 uint16 eDest2;
10942 if( IsInventoryPos( src ) )
10943 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10944 else if( IsBankPos( src ) )
10945 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10946 else if( IsEquipmentPos( src ) )
10948 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10949 if( msg == EQUIP_ERR_OK )
10950 msg = CanUnequipItem( eDest2, true);
10953 if( msg != EQUIP_ERR_OK )
10955 SendEquipError( msg, pDstItem, pSrcItem );
10956 return;
10959 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
10960 if(pSrcItem->IsBag() && pDstItem->IsBag())
10962 Bag* emptyBag = NULL;
10963 Bag* fullBag = NULL;
10964 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
10966 emptyBag = (Bag*)pSrcItem;
10967 fullBag = (Bag*)pDstItem;
10969 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
10971 emptyBag = (Bag*)pDstItem;
10972 fullBag = (Bag*)pSrcItem;
10975 // bag swap (with items exchange) case
10976 if(emptyBag && fullBag)
10978 ItemPrototype const* emotyProto = emptyBag->GetProto();
10980 uint32 count = 0;
10982 for(int i=0; i < fullBag->GetBagSize(); ++i)
10984 Item *bagItem = fullBag->GetItemByPos(i);
10985 if (!bagItem)
10986 continue;
10988 ItemPrototype const* bagItemProto = bagItem->GetProto();
10989 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
10991 // one from items not go to empry target bag
10992 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10993 return;
10996 ++count;
11000 if (count > emptyBag->GetBagSize())
11002 // too small targeted bag
11003 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11004 return;
11007 // Items swap
11008 count = 0; // will pos in new bag
11009 for(int i=0; i< fullBag->GetBagSize(); ++i)
11011 Item *bagItem = fullBag->GetItemByPos(i);
11012 if (!bagItem)
11013 continue;
11015 fullBag->RemoveItem(i, true);
11016 emptyBag->StoreItem(count, bagItem, true);
11017 bagItem->SetState(ITEM_CHANGED, this);
11019 ++count;
11024 // now do moves, remove...
11025 RemoveItem(dstbag, dstslot, false);
11026 RemoveItem(srcbag, srcslot, false);
11028 // add to dest
11029 if( IsInventoryPos( dst ) )
11030 StoreItem(sDest, pSrcItem, true);
11031 else if( IsBankPos( dst ) )
11032 BankItem(sDest, pSrcItem, true);
11033 else if( IsEquipmentPos( dst ) )
11034 EquipItem(eDest, pSrcItem, true);
11036 // add to src
11037 if( IsInventoryPos( src ) )
11038 StoreItem(sDest2, pDstItem, true);
11039 else if( IsBankPos( src ) )
11040 BankItem(sDest2, pDstItem, true);
11041 else if( IsEquipmentPos( src ) )
11042 EquipItem(eDest2, pDstItem, true);
11044 AutoUnequipOffhandIfNeed();
11047 void Player::AddItemToBuyBackSlot( Item *pItem )
11049 if( pItem )
11051 uint32 slot = m_currentBuybackSlot;
11052 // if current back slot non-empty search oldest or free
11053 if(m_items[slot])
11055 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11056 uint32 oldest_slot = BUYBACK_SLOT_START;
11058 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11060 // found empty
11061 if(!m_items[i])
11063 slot = i;
11064 break;
11067 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11069 if(oldest_time > i_time)
11071 oldest_time = i_time;
11072 oldest_slot = i;
11076 // find oldest
11077 slot = oldest_slot;
11080 RemoveItemFromBuyBackSlot( slot, true );
11081 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11083 m_items[slot] = pItem;
11084 time_t base = time(NULL);
11085 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11086 uint32 eslot = slot - BUYBACK_SLOT_START;
11088 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11089 ItemPrototype const *pProto = pItem->GetProto();
11090 if( pProto )
11091 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11092 else
11093 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11094 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11096 // move to next (for non filled list is move most optimized choice)
11097 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11098 ++m_currentBuybackSlot;
11102 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11104 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11105 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11106 return m_items[slot];
11107 return NULL;
11110 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11112 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11113 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11115 Item *pItem = m_items[slot];
11116 if( pItem )
11118 pItem->RemoveFromWorld();
11119 if(del) pItem->SetState(ITEM_REMOVED, this);
11122 m_items[slot] = NULL;
11124 uint32 eslot = slot - BUYBACK_SLOT_START;
11125 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11126 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11127 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11129 // if current backslot is filled set to now free slot
11130 if(m_items[m_currentBuybackSlot])
11131 m_currentBuybackSlot = slot;
11135 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11137 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11138 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11139 data << uint8(msg);
11141 if(msg)
11143 data << uint64(pItem ? pItem->GetGUID() : 0);
11144 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11145 data << uint8(0); // not 0 there...
11147 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11149 uint32 level = 0;
11151 if(pItem)
11152 if(ItemPrototype const* proto = pItem->GetProto())
11153 level = proto->RequiredLevel;
11155 data << uint32(level); // new 2.4.0
11158 GetSession()->SendPacket(&data);
11161 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11163 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11164 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11165 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11166 data << uint32(item);
11167 if( param > 0 )
11168 data << uint32(param);
11169 data << uint8(msg);
11170 GetSession()->SendPacket(&data);
11173 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11175 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11176 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11177 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11178 data << uint64(guid);
11179 if( param > 0 )
11180 data << uint32(param);
11181 data << uint8(msg);
11182 GetSession()->SendPacket(&data);
11185 void Player::ClearTrade()
11187 tradeGold = 0;
11188 acceptTrade = false;
11189 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11190 tradeItems[i] = NULL_SLOT;
11193 void Player::TradeCancel(bool sendback)
11195 if(pTrader)
11197 // send yellow "Trade canceled" message to both traders
11198 WorldSession* ws;
11199 ws = GetSession();
11200 if(sendback)
11201 ws->SendCancelTrade();
11202 ws = pTrader->GetSession();
11203 if(!ws->PlayerLogout())
11204 ws->SendCancelTrade();
11206 // cleanup
11207 ClearTrade();
11208 pTrader->ClearTrade();
11209 // prevent loss of reference
11210 pTrader->pTrader = NULL;
11211 pTrader = NULL;
11215 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11217 if(m_itemDuration.empty())
11218 return;
11220 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11222 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11224 Item* item = *itr;
11225 ++itr; // current element can be erased in UpdateDuration
11227 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11228 item->UpdateDuration(this,time);
11232 void Player::UpdateEnchantTime(uint32 time)
11234 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11236 assert(itr->item);
11237 next=itr;
11238 if(!itr->item->GetEnchantmentId(itr->slot))
11240 next = m_enchantDuration.erase(itr);
11242 else if(itr->leftduration <= time)
11244 ApplyEnchantment(itr->item,itr->slot,false,false);
11245 itr->item->ClearEnchantment(itr->slot);
11246 next = m_enchantDuration.erase(itr);
11248 else if(itr->leftduration > time)
11250 itr->leftduration -= time;
11251 ++next;
11256 void Player::AddEnchantmentDurations(Item *item)
11258 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11260 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11261 continue;
11263 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11264 if( duration > 0 )
11265 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11269 void Player::RemoveEnchantmentDurations(Item *item)
11271 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11273 if(itr->item == item)
11275 // save duration in item
11276 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11277 itr = m_enchantDuration.erase(itr);
11279 else
11280 ++itr;
11284 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11286 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11287 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11289 next = itr;
11290 if(itr->slot==slot)
11292 if(itr->item && itr->item->GetEnchantmentId(slot))
11294 // remove from stats
11295 ApplyEnchantment(itr->item,slot,false,false);
11296 // remove visual
11297 itr->item->ClearEnchantment(slot);
11299 // remove from update list
11300 next = m_enchantDuration.erase(itr);
11302 else
11303 ++next;
11306 // remove enchants from inventory items
11307 // NOTE: no need to remove these from stats, since these aren't equipped
11308 // in inventory
11309 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11311 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11312 if( pItem && pItem->GetEnchantmentId(slot) )
11313 pItem->ClearEnchantment(slot);
11316 // in inventory bags
11317 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11319 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11320 if( pBag )
11322 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11324 Item* pItem = pBag->GetItemByPos(j);
11325 if( pItem && pItem->GetEnchantmentId(slot) )
11326 pItem->ClearEnchantment(slot);
11332 // duration == 0 will remove item enchant
11333 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11335 if(!item)
11336 return;
11338 if(slot >= MAX_ENCHANTMENT_SLOT)
11339 return;
11341 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11343 if(itr->item == item && itr->slot == slot)
11345 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11346 m_enchantDuration.erase(itr);
11347 break;
11350 if(item && duration > 0 )
11352 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11353 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11357 void Player::ApplyEnchantment(Item *item,bool apply)
11359 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11360 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11363 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11365 if(!item)
11366 return;
11368 if(!item->IsEquipped())
11369 return;
11371 if(slot >= MAX_ENCHANTMENT_SLOT)
11372 return;
11374 uint32 enchant_id = item->GetEnchantmentId(slot);
11375 if(!enchant_id)
11376 return;
11378 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11379 if(!pEnchant)
11380 return;
11382 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11383 return;
11385 for (int s=0; s<3; s++)
11387 uint32 enchant_display_type = pEnchant->type[s];
11388 uint32 enchant_amount = pEnchant->amount[s];
11389 uint32 enchant_spell_id = pEnchant->spellid[s];
11391 switch(enchant_display_type)
11393 case ITEM_ENCHANTMENT_TYPE_NONE:
11394 break;
11395 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11396 // processed in Player::CastItemCombatSpell
11397 break;
11398 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11399 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11400 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11401 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11402 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11403 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11404 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11405 break;
11406 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11407 if(enchant_spell_id)
11409 if(apply)
11411 int32 basepoints = 0;
11412 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11413 if (item->GetItemRandomPropertyId())
11415 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11416 if (item_rand)
11418 // Search enchant_amount
11419 for (int k=0; k<3; k++)
11421 if(item_rand->enchant_id[k] == enchant_id)
11423 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11424 break;
11429 // Cast custom spell vs all equal basepoints getted from enchant_amount
11430 if (basepoints)
11431 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11432 else
11433 CastSpell(this,enchant_spell_id,true,item);
11435 else
11436 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11438 break;
11439 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11440 if (!enchant_amount)
11442 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11443 if(item_rand)
11445 for (int k=0; k<3; k++)
11447 if(item_rand->enchant_id[k] == enchant_id)
11449 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11450 break;
11456 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11457 break;
11458 case ITEM_ENCHANTMENT_TYPE_STAT:
11460 if (!enchant_amount)
11462 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11463 if(item_rand_suffix)
11465 for (int k=0; k<3; k++)
11467 if(item_rand_suffix->enchant_id[k] == enchant_id)
11469 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11470 break;
11476 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11477 switch (enchant_spell_id)
11479 case ITEM_MOD_AGILITY:
11480 sLog.outDebug("+ %u AGILITY",enchant_amount);
11481 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11482 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11483 break;
11484 case ITEM_MOD_STRENGTH:
11485 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11486 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11487 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11488 break;
11489 case ITEM_MOD_INTELLECT:
11490 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11491 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11492 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11493 break;
11494 case ITEM_MOD_SPIRIT:
11495 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11496 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11497 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11498 break;
11499 case ITEM_MOD_STAMINA:
11500 sLog.outDebug("+ %u STAMINA",enchant_amount);
11501 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11502 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11503 break;
11504 case ITEM_MOD_DEFENSE_SKILL_RATING:
11505 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11506 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11507 break;
11508 case ITEM_MOD_DODGE_RATING:
11509 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11510 sLog.outDebug("+ %u DODGE", enchant_amount);
11511 break;
11512 case ITEM_MOD_PARRY_RATING:
11513 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11514 sLog.outDebug("+ %u PARRY", enchant_amount);
11515 break;
11516 case ITEM_MOD_BLOCK_RATING:
11517 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11518 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11519 break;
11520 case ITEM_MOD_HIT_MELEE_RATING:
11521 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11522 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11523 break;
11524 case ITEM_MOD_HIT_RANGED_RATING:
11525 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11526 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11527 break;
11528 case ITEM_MOD_HIT_SPELL_RATING:
11529 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11530 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11531 break;
11532 case ITEM_MOD_CRIT_MELEE_RATING:
11533 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11534 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11535 break;
11536 case ITEM_MOD_CRIT_RANGED_RATING:
11537 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11538 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11539 break;
11540 case ITEM_MOD_CRIT_SPELL_RATING:
11541 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11542 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11543 break;
11544 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11545 // in Enchantments
11546 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11547 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11548 // break;
11549 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11550 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11551 // break;
11552 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11553 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11554 // break;
11555 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11556 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11557 // break;
11558 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11559 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11560 // break;
11561 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11562 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11563 // break;
11564 // case ITEM_MOD_HASTE_MELEE_RATING:
11565 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11566 // break;
11567 // case ITEM_MOD_HASTE_RANGED_RATING:
11568 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11569 // break;
11570 case ITEM_MOD_HASTE_SPELL_RATING:
11571 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11572 break;
11573 case ITEM_MOD_HIT_RATING:
11574 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11575 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11576 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11577 sLog.outDebug("+ %u HIT", enchant_amount);
11578 break;
11579 case ITEM_MOD_CRIT_RATING:
11580 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11581 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11582 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11583 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11584 break;
11585 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11586 // case ITEM_MOD_HIT_TAKEN_RATING:
11587 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11588 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11589 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11590 // break;
11591 // case ITEM_MOD_CRIT_TAKEN_RATING:
11592 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11593 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11594 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11595 // break;
11596 case ITEM_MOD_RESILIENCE_RATING:
11597 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11598 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11599 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11600 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11601 break;
11602 case ITEM_MOD_HASTE_RATING:
11603 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11604 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11605 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11606 sLog.outDebug("+ %u HASTE", enchant_amount);
11607 break;
11608 case ITEM_MOD_EXPERTISE_RATING:
11609 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11610 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11611 break;
11612 case ITEM_MOD_ATTACK_POWER:
11613 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11614 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11615 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11616 break;
11617 case ITEM_MOD_RANGED_ATTACK_POWER:
11618 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11619 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11620 break;
11621 case ITEM_MOD_FERAL_ATTACK_POWER:
11622 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11623 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11624 break;
11625 case ITEM_MOD_SPELL_HEALING_DONE:
11626 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11627 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11628 break;
11629 case ITEM_MOD_SPELL_DAMAGE_DONE:
11630 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11631 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11632 break;
11633 case ITEM_MOD_MANA_REGENERATION:
11634 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11635 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11636 break;
11637 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11638 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11639 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11640 break;
11641 case ITEM_MOD_SPELL_POWER:
11642 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11643 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11644 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11645 break;
11646 default:
11647 break;
11649 break;
11651 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11653 if(getClass() == CLASS_SHAMAN)
11655 float addValue = 0.0f;
11656 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11658 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11659 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11661 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11663 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11664 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11667 break;
11669 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11670 // processed in Player::CastItemUseSpell
11671 break;
11672 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11673 // nothing do..
11674 break;
11675 default:
11676 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11677 break;
11678 } /*switch(enchant_display_type)*/
11679 } /*for*/
11681 // visualize enchantment at player and equipped items
11682 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11684 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11685 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11688 if(apply_dur)
11690 if(apply)
11692 // set duration
11693 uint32 duration = item->GetEnchantmentDuration(slot);
11694 if(duration > 0)
11695 AddEnchantmentDuration(item,slot,duration);
11697 else
11699 // duration == 0 will remove EnchantDuration
11700 AddEnchantmentDuration(item,slot,0);
11705 void Player::SendEnchantmentDurations()
11707 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11709 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11713 void Player::SendItemDurations()
11715 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11717 (*itr)->SendTimeUpdate(this);
11721 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11723 if(!item) // prevent crash
11724 return;
11726 // last check 2.0.10
11727 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11728 data << GetGUID(); // player GUID
11729 data << uint32(received); // 0=looted, 1=from npc
11730 data << uint32(created); // 0=received, 1=created
11731 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11732 data << (uint8)item->GetBagSlot(); // bagslot
11733 // item slot, but when added to stack: 0xFFFFFFFF
11734 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11735 data << uint32(item->GetEntry()); // item id
11736 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11737 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11738 data << uint32(count); // count of items
11739 data << GetItemCount(item->GetEntry()); // count of items in inventory
11741 if (broadcast && GetGroup())
11742 GetGroup()->BroadcastPacket(&data, true);
11743 else
11744 GetSession()->SendPacket(&data);
11747 /*********************************************************/
11748 /*** QUEST SYSTEM ***/
11749 /*********************************************************/
11751 void Player::PrepareQuestMenu( uint64 guid )
11753 Object *pObject;
11754 QuestRelations* pObjectQR;
11755 QuestRelations* pObjectQIR;
11756 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11757 if( pCreature )
11759 pObject = (Object*)pCreature;
11760 pObjectQR = &objmgr.mCreatureQuestRelations;
11761 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11763 else
11765 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11766 if( pGameObject )
11768 pObject = (Object*)pGameObject;
11769 pObjectQR = &objmgr.mGOQuestRelations;
11770 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11772 else
11773 return;
11776 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11777 qm.ClearMenu();
11779 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11781 uint32 quest_id = i->second;
11782 QuestStatus status = GetQuestStatus( quest_id );
11783 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11784 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11785 else if ( status == QUEST_STATUS_INCOMPLETE )
11786 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11787 else if (status == QUEST_STATUS_AVAILABLE )
11788 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11791 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11793 uint32 quest_id = i->second;
11794 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11795 if(!pQuest) continue;
11797 QuestStatus status = GetQuestStatus( quest_id );
11799 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11800 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11801 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11802 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11806 void Player::SendPreparedQuest( uint64 guid )
11808 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11809 if( questMenu.Empty() )
11810 return;
11812 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11814 uint32 status = qmi0.m_qIcon;
11816 // single element case
11817 if ( questMenu.MenuItemCount() == 1 )
11819 // Auto open -- maybe also should verify there is no greeting
11820 uint32 quest_id = qmi0.m_qId;
11821 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11822 if ( pQuest )
11824 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11825 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11826 else if( status == DIALOG_STATUS_INCOMPLETE )
11827 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11828 // Send completable on repeatable quest if player don't have quest
11829 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11830 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11831 else
11832 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11835 // multiply entries
11836 else
11838 QEmote qe;
11839 qe._Delay = 0;
11840 qe._Emote = 0;
11841 std::string title = "";
11842 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11843 if( pCreature )
11845 uint32 textid = pCreature->GetNpcTextId();
11846 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11847 if( !gossiptext )
11849 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11850 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11851 title = "";
11853 else
11855 qe = gossiptext->Options[0].Emotes[0];
11857 if(!gossiptext->Options[0].Text_0.empty())
11859 title = gossiptext->Options[0].Text_0;
11861 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11862 if (loc_idx >= 0)
11864 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11865 if (nl)
11867 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11868 title = nl->Text_0[0][loc_idx];
11872 else
11874 title = gossiptext->Options[0].Text_1;
11876 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11877 if (loc_idx >= 0)
11879 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11880 if (nl)
11882 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11883 title = nl->Text_1[0][loc_idx];
11889 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11893 bool Player::IsActiveQuest( uint32 quest_id ) const
11895 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11897 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11900 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11902 Object *pObject;
11903 QuestRelations* pObjectQR;
11904 QuestRelations* pObjectQIR;
11906 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11907 if( pCreature )
11909 pObject = (Object*)pCreature;
11910 pObjectQR = &objmgr.mCreatureQuestRelations;
11911 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11913 else
11915 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11916 if( pGameObject )
11918 pObject = (Object*)pGameObject;
11919 pObjectQR = &objmgr.mGOQuestRelations;
11920 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11922 else
11923 return NULL;
11926 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11927 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11929 if (itr->second == nextQuestID)
11930 return objmgr.GetQuestTemplate(nextQuestID);
11933 return NULL;
11936 bool Player::CanSeeStartQuest( Quest const *pQuest )
11938 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11939 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11940 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11941 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11943 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11946 return false;
11949 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11951 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11952 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11953 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11954 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11955 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11956 && SatisfyQuestDay( pQuest, msg );
11959 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11961 if( !SatisfyQuestLog( msg ) )
11962 return false;
11964 uint32 srcitem = pQuest->GetSrcItemId();
11965 if( srcitem > 0 )
11967 uint32 count = pQuest->GetSrcItemCount();
11968 ItemPosCountVec dest;
11969 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
11971 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11972 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
11973 return true;
11974 else if( msg != EQUIP_ERR_OK )
11976 SendEquipError( msg, NULL, NULL );
11977 return false;
11980 return true;
11983 bool Player::CanCompleteQuest( uint32 quest_id )
11985 if( quest_id )
11987 QuestStatusData& q_status = mQuestStatus[quest_id];
11988 if( q_status.m_status == QUEST_STATUS_COMPLETE )
11989 return false; // not allow re-complete quest
11991 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
11993 if(!qInfo)
11994 return false;
11996 // auto complete quest
11997 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
11998 return true;
12000 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12003 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12005 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12007 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12008 return false;
12012 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12014 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12016 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12017 continue;
12019 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12020 return false;
12024 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12025 return false;
12027 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12028 return false;
12030 if ( qInfo->GetRewOrReqMoney() < 0 )
12032 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12033 return false;
12036 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12037 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12038 return false;
12040 return true;
12043 return false;
12046 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12048 // Solve problem that player don't have the quest and try complete it.
12049 // if repeatable she must be able to complete event if player don't have it.
12050 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12051 if( !CanTakeQuest(pQuest, false) )
12052 return false;
12054 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12055 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12056 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12057 return false;
12059 if( !CanRewardQuest(pQuest, false) )
12060 return false;
12062 return true;
12065 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12067 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12068 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12069 return false;
12071 // daily quest can't be rewarded (25 daily quest already completed)
12072 if(!SatisfyQuestDay(pQuest,true))
12073 return false;
12075 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12076 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12077 return false;
12079 // prevent receive reward with quest items in bank
12080 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12082 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12084 if( pQuest->ReqItemCount[i]!= 0 &&
12085 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12087 if(msg)
12088 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12089 return false;
12094 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12095 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12096 return false;
12098 return true;
12101 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12103 // prevent receive reward with quest items in bank or for not completed quest
12104 if(!CanRewardQuest(pQuest,msg))
12105 return false;
12107 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12109 if( pQuest->RewChoiceItemId[reward] )
12111 ItemPosCountVec dest;
12112 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12113 if( res != EQUIP_ERR_OK )
12115 SendEquipError( res, NULL, NULL );
12116 return false;
12121 if ( pQuest->GetRewItemsCount() > 0 )
12123 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12125 if( pQuest->RewItemId[i] )
12127 ItemPosCountVec dest;
12128 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12129 if( res != EQUIP_ERR_OK )
12131 SendEquipError( res, NULL, NULL );
12132 return false;
12138 return true;
12141 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12143 uint16 log_slot = FindQuestSlot( 0 );
12144 assert(log_slot < MAX_QUEST_LOG_SIZE);
12146 uint32 quest_id = pQuest->GetQuestId();
12148 // if not exist then created with set uState==NEW and rewarded=false
12149 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12151 // check for repeatable quests status reset
12152 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12153 questStatusData.m_explored = false;
12155 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12157 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12158 questStatusData.m_itemcount[i] = 0;
12161 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12163 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12164 questStatusData.m_creatureOrGOcount[i] = 0;
12167 GiveQuestSourceItem( pQuest );
12168 AdjustQuestReqItemCount( pQuest, questStatusData );
12170 if( pQuest->GetRepObjectiveFaction() )
12171 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12172 GetReputationMgr().SetVisible(factionEntry);
12174 uint32 qtime = 0;
12175 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12177 uint32 limittime = pQuest->GetLimitTime();
12179 // shared timed quest
12180 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12181 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12183 AddTimedQuest( quest_id );
12184 questStatusData.m_timer = limittime * IN_MILISECONDS;
12185 qtime = static_cast<uint32>(time(NULL)) + limittime;
12187 else
12188 questStatusData.m_timer = 0;
12190 SetQuestSlot(log_slot, quest_id, qtime);
12192 if (questStatusData.uState != QUEST_NEW)
12193 questStatusData.uState = QUEST_CHANGED;
12195 //starting initial quest script
12196 if(questGiver && pQuest->GetQuestStartScript()!=0)
12197 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12199 // Some spells applied at quest activation
12200 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12201 if(saBounds.first != saBounds.second)
12203 uint32 zone, area;
12204 GetZoneAndAreaId(zone,area);
12206 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12207 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12208 if( !HasAura(itr->second->spellId,0) )
12209 CastSpell(this,itr->second->spellId,true);
12212 UpdateForQuestsGO();
12215 void Player::CompleteQuest( uint32 quest_id )
12217 if( quest_id )
12219 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12221 uint16 log_slot = FindQuestSlot( quest_id );
12222 if( log_slot < MAX_QUEST_LOG_SIZE)
12223 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12225 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12227 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12228 RewardQuest(qInfo,0,this,false);
12229 else
12230 SendQuestComplete( quest_id );
12235 void Player::IncompleteQuest( uint32 quest_id )
12237 if( quest_id )
12239 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12241 uint16 log_slot = FindQuestSlot( quest_id );
12242 if( log_slot < MAX_QUEST_LOG_SIZE)
12243 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12247 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12249 uint32 quest_id = pQuest->GetQuestId();
12251 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12253 if ( pQuest->ReqItemId[i] )
12254 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12257 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12258 // SetTimedQuest( 0 );
12259 m_timedquests.erase(pQuest->GetQuestId());
12261 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12263 if( pQuest->RewChoiceItemId[reward] )
12265 ItemPosCountVec dest;
12266 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12268 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12269 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12274 if ( pQuest->GetRewItemsCount() > 0 )
12276 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12278 if( pQuest->RewItemId[i] )
12280 ItemPosCountVec dest;
12281 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12283 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12284 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12290 RewardReputation( pQuest );
12292 if( pQuest->GetRewSpellCast() > 0 )
12293 CastSpell( this, pQuest->GetRewSpellCast(), true);
12294 else if( pQuest->GetRewSpell() > 0)
12295 CastSpell( this, pQuest->GetRewSpell(), true);
12297 uint16 log_slot = FindQuestSlot( quest_id );
12298 if( log_slot < MAX_QUEST_LOG_SIZE)
12299 SetQuestSlot(log_slot,0);
12301 QuestStatusData& q_status = mQuestStatus[quest_id];
12303 // Not give XP in case already completed once repeatable quest
12304 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12306 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12307 GiveXP( XP , NULL );
12308 else
12310 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12311 ModifyMoney( money );
12312 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12315 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12316 if(pQuest->GetRewOrReqMoney())
12318 ModifyMoney( pQuest->GetRewOrReqMoney() );
12320 if(pQuest->GetRewOrReqMoney() > 0)
12321 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12324 // honor reward
12325 if(pQuest->GetRewHonorableKills())
12326 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12328 // title reward
12329 if(pQuest->GetCharTitleId())
12331 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12332 SetTitle(titleEntry);
12335 if(pQuest->GetBonusTalents())
12337 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12338 InitTalentForLevel();
12341 // Send reward mail
12342 if(pQuest->GetRewMailTemplateId())
12344 MailMessageType mailType;
12345 uint32 senderGuidOrEntry;
12346 switch(questGiver->GetTypeId())
12348 case TYPEID_UNIT:
12349 mailType = MAIL_CREATURE;
12350 senderGuidOrEntry = questGiver->GetEntry();
12351 break;
12352 case TYPEID_GAMEOBJECT:
12353 mailType = MAIL_GAMEOBJECT;
12354 senderGuidOrEntry = questGiver->GetEntry();
12355 break;
12356 case TYPEID_ITEM:
12357 mailType = MAIL_ITEM;
12358 senderGuidOrEntry = questGiver->GetEntry();
12359 break;
12360 case TYPEID_PLAYER:
12361 mailType = MAIL_NORMAL;
12362 senderGuidOrEntry = questGiver->GetGUIDLow();
12363 break;
12364 default:
12365 mailType = MAIL_NORMAL;
12366 senderGuidOrEntry = GetGUIDLow();
12367 break;
12370 Loot questMailLoot;
12372 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12374 // fill mail
12375 MailItemsInfo mi; // item list preparing
12377 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12378 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12380 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12382 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12384 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12385 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12390 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12393 if(pQuest->IsDaily())
12395 SetDailyQuestStatus(quest_id);
12396 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12399 if ( !pQuest->IsRepeatable() )
12400 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12401 else
12402 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12404 q_status.m_rewarded = true;
12406 if(announce)
12407 SendQuestReward( pQuest, XP, questGiver );
12409 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12410 if (pQuest->GetZoneOrSort() > 0)
12411 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12412 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12413 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12415 uint32 zone = 0;
12416 uint32 area = 0;
12418 // remove auras from spells with quest reward state limitations
12419 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12420 if(saEndBounds.first != saEndBounds.second)
12422 GetZoneAndAreaId(zone,area);
12424 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12425 if(!itr->second->IsFitToRequirements(this,zone,area))
12426 RemoveAurasDueToSpell(itr->second->spellId);
12429 // Some spells applied at quest reward
12430 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12431 if(saBounds.first != saBounds.second)
12433 if(!zone || !area)
12434 GetZoneAndAreaId(zone,area);
12436 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12437 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12438 if( !HasAura(itr->second->spellId,0) )
12439 CastSpell(this,itr->second->spellId,true);
12443 void Player::FailQuest( uint32 quest_id )
12445 if( quest_id )
12447 IncompleteQuest( quest_id );
12449 uint16 log_slot = FindQuestSlot( quest_id );
12450 if( log_slot < MAX_QUEST_LOG_SIZE)
12452 SetQuestSlotTimer(log_slot, 1 );
12453 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12455 SendQuestFailed( quest_id );
12459 void Player::FailTimedQuest( uint32 quest_id )
12461 if( quest_id )
12463 QuestStatusData& q_status = mQuestStatus[quest_id];
12465 q_status.m_timer = 0;
12466 if (q_status.uState != QUEST_NEW)
12467 q_status.uState = QUEST_CHANGED;
12469 IncompleteQuest( quest_id );
12471 uint16 log_slot = FindQuestSlot( quest_id );
12472 if( log_slot < MAX_QUEST_LOG_SIZE)
12474 SetQuestSlotTimer(log_slot, 1 );
12475 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12477 SendQuestTimerFailed( quest_id );
12481 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12483 int32 zoneOrSort = qInfo->GetZoneOrSort();
12484 int32 skillOrClass = qInfo->GetSkillOrClass();
12486 // skip zone zoneOrSort and 0 case skillOrClass
12487 if( zoneOrSort >= 0 && skillOrClass == 0 )
12488 return true;
12490 int32 questSort = -zoneOrSort;
12491 uint8 reqSortClass = ClassByQuestSort(questSort);
12493 // check class sort cases in zoneOrSort
12494 if( reqSortClass != 0 && getClass() != reqSortClass)
12496 if( msg )
12497 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12498 return false;
12501 // check class
12502 if( skillOrClass < 0 )
12504 uint8 reqClass = -int32(skillOrClass);
12505 if(getClass() != reqClass)
12507 if( msg )
12508 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12509 return false;
12512 // check skill
12513 else if( skillOrClass > 0 )
12515 uint32 reqSkill = skillOrClass;
12516 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12518 if( msg )
12519 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12520 return false;
12524 return true;
12527 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12529 if( getLevel() < qInfo->GetMinLevel() )
12531 if( msg )
12532 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12533 return false;
12535 return true;
12538 bool Player::SatisfyQuestLog( bool msg )
12540 // exist free slot
12541 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12542 return true;
12544 if( msg )
12546 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12547 GetSession()->SendPacket( &data );
12548 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12550 return false;
12553 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12555 // No previous quest (might be first quest in a series)
12556 if( qInfo->prevQuests.empty())
12557 return true;
12559 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12561 uint32 prevId = abs(*iter);
12563 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12564 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12566 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12568 // If any of the positive previous quests completed, return true
12569 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12571 // skip one-from-all exclusive group
12572 if(qPrevInfo->GetExclusiveGroup() >= 0)
12573 return true;
12575 // each-from-all exclusive group ( < 0)
12576 // can be start if only all quests in prev quest exclusive group completed and rewarded
12577 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12578 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12580 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12582 for(; iter != end; ++iter)
12584 uint32 exclude_Id = iter->second;
12586 // skip checked quest id, only state of other quests in group is interesting
12587 if(exclude_Id == prevId)
12588 continue;
12590 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12592 // alternative quest from group also must be completed and rewarded(reported)
12593 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12595 if( msg )
12596 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12597 return false;
12600 return true;
12602 // If any of the negative previous quests active, return true
12603 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12604 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12606 // skip one-from-all exclusive group
12607 if(qPrevInfo->GetExclusiveGroup() >= 0)
12608 return true;
12610 // each-from-all exclusive group ( < 0)
12611 // can be start if only all quests in prev quest exclusive group active
12612 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12613 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12615 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12617 for(; iter != end; ++iter)
12619 uint32 exclude_Id = iter->second;
12621 // skip checked quest id, only state of other quests in group is interesting
12622 if(exclude_Id == prevId)
12623 continue;
12625 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12627 // alternative quest from group also must be active
12628 if( i_exstatus == mQuestStatus.end() ||
12629 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12630 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12632 if( msg )
12633 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12634 return false;
12637 return true;
12642 // Has only positive prev. quests in non-rewarded state
12643 // and negative prev. quests in non-active state
12644 if( msg )
12645 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12647 return false;
12650 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12652 uint32 reqraces = qInfo->GetRequiredRaces();
12653 if ( reqraces == 0 )
12654 return true;
12655 if( (reqraces & getRaceMask()) == 0 )
12657 if( msg )
12658 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12659 return false;
12661 return true;
12664 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12666 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12667 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12669 if( msg )
12670 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12671 return false;
12674 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12675 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12677 if( msg )
12678 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12679 return false;
12682 return true;
12685 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12687 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12688 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12690 if( msg )
12691 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12692 return false;
12694 return true;
12697 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12699 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12701 if( msg )
12702 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12703 return false;
12705 return true;
12708 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12710 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12711 if(qInfo->GetExclusiveGroup() <= 0)
12712 return true;
12714 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12715 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12717 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12719 for(; iter != end; ++iter)
12721 uint32 exclude_Id = iter->second;
12723 // skip checked quest id, only state of other quests in group is interesting
12724 if(exclude_Id == qInfo->GetQuestId())
12725 continue;
12727 // not allow have daily quest if daily quest from exclusive group already recently completed
12728 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12729 if( !SatisfyQuestDay(Nquest, false) )
12731 if( msg )
12732 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12733 return false;
12736 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12738 // alternative quest already started or completed
12739 if( i_exstatus != mQuestStatus.end()
12740 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12742 if( msg )
12743 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12744 return false;
12747 return true;
12750 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12752 if(!qInfo->GetNextQuestInChain())
12753 return true;
12755 // next quest in chain already started or completed
12756 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12757 if( itr != mQuestStatus.end()
12758 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12760 if( msg )
12761 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12762 return false;
12765 // check for all quests further up the chain
12766 // only necessary if there are quest chains with more than one quest that can be skipped
12767 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12768 return true;
12771 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12773 // No previous quest in chain
12774 if( qInfo->prevChainQuests.empty())
12775 return true;
12777 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12779 uint32 prevId = *iter;
12781 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12783 if( i_prevstatus != mQuestStatus.end() )
12785 // If any of the previous quests in chain active, return false
12786 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12787 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12789 if( msg )
12790 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12791 return false;
12795 // check for all quests further down the chain
12796 // only necessary if there are quest chains with more than one quest that can be skipped
12797 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12798 // return false;
12801 // No previous quest in chain active
12802 return true;
12805 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12807 if(!qInfo->IsDaily())
12808 return true;
12810 bool have_slot = false;
12811 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12813 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12814 if(qInfo->GetQuestId()==id)
12815 return false;
12817 if(!id)
12818 have_slot = true;
12821 if(!have_slot)
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12825 return false;
12828 return true;
12831 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12833 uint32 srcitem = pQuest->GetSrcItemId();
12834 if( srcitem > 0 )
12836 uint32 count = pQuest->GetSrcItemCount();
12837 if( count <= 0 )
12838 count = 1;
12840 ItemPosCountVec dest;
12841 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12842 if( msg == EQUIP_ERR_OK )
12844 Item * item = StoreNewItem(dest, srcitem, true);
12845 SendNewItem(item, count, true, false);
12846 return true;
12848 // player already have max amount required item, just report success
12849 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12850 return true;
12851 else
12852 SendEquipError( msg, NULL, NULL );
12853 return false;
12856 return true;
12859 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12861 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12862 if( qInfo )
12864 uint32 srcitem = qInfo->GetSrcItemId();
12865 if( srcitem > 0 )
12867 uint32 count = qInfo->GetSrcItemCount();
12868 if( count <= 0 )
12869 count = 1;
12871 // exist one case when destroy source quest item not possible:
12872 // non un-equippable item (equipped non-empty bag, for example)
12873 uint8 res = CanUnequipItems(srcitem,count);
12874 if(res != EQUIP_ERR_OK)
12876 if(msg)
12877 SendEquipError( res, NULL, NULL );
12878 return false;
12881 DestroyItemCount(srcitem, count, true, true);
12884 return true;
12887 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12889 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12890 if( qInfo )
12892 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12893 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12894 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12895 && !qInfo->IsRepeatable() )
12896 return itr->second.m_rewarded;
12898 return false;
12900 return false;
12903 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12905 if( quest_id )
12907 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12908 if( itr != mQuestStatus.end() )
12909 return itr->second.m_status;
12911 return QUEST_STATUS_NONE;
12914 bool Player::CanShareQuest(uint32 quest_id) const
12916 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12917 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12919 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12920 if( itr != mQuestStatus.end() )
12921 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12923 return false;
12926 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12928 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12929 if( qInfo )
12931 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12933 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12934 m_timedquests.erase(qInfo->GetQuestId());
12937 QuestStatusData& q_status = mQuestStatus[quest_id];
12939 q_status.m_status = status;
12940 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12943 UpdateForQuestsGO();
12946 // not used in MaNGOS, but used in scripting code
12947 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12949 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12950 if( !qInfo )
12951 return 0;
12953 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
12954 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12955 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12957 return 0;
12960 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
12962 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12964 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12966 uint32 reqitemcount = pQuest->ReqItemCount[i];
12967 if( reqitemcount != 0 )
12969 uint32 quest_id = pQuest->GetQuestId();
12970 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12972 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12973 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
12979 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12981 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
12982 if ( GetQuestSlotQuestId(i) == quest_id )
12983 return i;
12985 return MAX_QUEST_LOG_SIZE;
12988 void Player::AreaExploredOrEventHappens( uint32 questId )
12990 if( questId )
12992 uint16 log_slot = FindQuestSlot( questId );
12993 if( log_slot < MAX_QUEST_LOG_SIZE)
12995 QuestStatusData& q_status = mQuestStatus[questId];
12997 if(!q_status.m_explored)
12999 q_status.m_explored = true;
13000 if (q_status.uState != QUEST_NEW)
13001 q_status.uState = QUEST_CHANGED;
13004 if( CanCompleteQuest( questId ) )
13005 CompleteQuest( questId );
13009 //not used in mangosd, function for external script library
13010 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13012 if( Group *pGroup = GetGroup() )
13014 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13016 Player *pGroupGuy = itr->getSource();
13018 // for any leave or dead (with not released body) group member at appropriate distance
13019 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13020 pGroupGuy->AreaExploredOrEventHappens(questId);
13023 else
13024 AreaExploredOrEventHappens(questId);
13027 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13029 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13031 uint32 questid = GetQuestSlotQuestId(i);
13032 if ( questid == 0 )
13033 continue;
13035 QuestStatusData& q_status = mQuestStatus[questid];
13037 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13038 continue;
13040 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13041 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13042 continue;
13044 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13046 uint32 reqitem = qInfo->ReqItemId[j];
13047 if ( reqitem == entry )
13049 uint32 reqitemcount = qInfo->ReqItemCount[j];
13050 uint32 curitemcount = q_status.m_itemcount[j];
13051 if ( curitemcount < reqitemcount )
13053 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13054 q_status.m_itemcount[j] += additemcount;
13055 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13057 SendQuestUpdateAddItem( qInfo, j, additemcount );
13059 if ( CanCompleteQuest( questid ) )
13060 CompleteQuest( questid );
13061 return;
13065 UpdateForQuestsGO();
13068 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13070 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13072 uint32 questid = GetQuestSlotQuestId(i);
13073 if(!questid)
13074 continue;
13075 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13076 if ( !qInfo )
13077 continue;
13078 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13079 continue;
13081 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13083 uint32 reqitem = qInfo->ReqItemId[j];
13084 if ( reqitem == entry )
13086 QuestStatusData& q_status = mQuestStatus[questid];
13088 uint32 reqitemcount = qInfo->ReqItemCount[j];
13089 uint32 curitemcount;
13090 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13091 curitemcount = q_status.m_itemcount[j];
13092 else
13093 curitemcount = GetItemCount(entry,true);
13094 if ( curitemcount < reqitemcount + count )
13096 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13097 q_status.m_itemcount[j] = curitemcount - remitemcount;
13098 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13100 IncompleteQuest( questid );
13102 return;
13106 UpdateForQuestsGO();
13109 void Player::KilledMonster( uint32 entry, uint64 guid )
13111 uint32 addkillcount = 1;
13112 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13113 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13115 uint32 questid = GetQuestSlotQuestId(i);
13116 if(!questid)
13117 continue;
13119 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13120 if( !qInfo )
13121 continue;
13122 // just if !ingroup || !noraidgroup || raidgroup
13123 QuestStatusData& q_status = mQuestStatus[questid];
13124 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13126 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13128 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13130 // skip GO activate objective or none
13131 if(qInfo->ReqCreatureOrGOId[j] <=0)
13132 continue;
13134 // skip Cast at creature objective
13135 if(qInfo->ReqSpell[j] !=0 )
13136 continue;
13138 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13140 if ( reqkill == entry )
13142 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13143 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13144 if ( curkillcount < reqkillcount )
13146 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13147 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13149 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13151 if ( CanCompleteQuest( questid ) )
13152 CompleteQuest( questid );
13154 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13155 continue;
13163 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13165 bool isCreature = IS_CREATURE_GUID(guid);
13167 uint32 addCastCount = 1;
13168 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13170 uint32 questid = GetQuestSlotQuestId(i);
13171 if(!questid)
13172 continue;
13174 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13175 if ( !qInfo )
13176 continue;
13178 QuestStatusData& q_status = mQuestStatus[questid];
13180 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13182 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13184 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13186 // skip kill creature objective (0) or wrong spell casts
13187 if(qInfo->ReqSpell[j] != spell_id )
13188 continue;
13190 uint32 reqTarget = 0;
13192 if(isCreature)
13194 // creature activate objectives
13195 if(qInfo->ReqCreatureOrGOId[j] > 0)
13196 // checked at quest_template loading
13197 reqTarget = qInfo->ReqCreatureOrGOId[j];
13199 else
13201 // GO activate objective
13202 if(qInfo->ReqCreatureOrGOId[j] < 0)
13203 // checked at quest_template loading
13204 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13207 // other not this creature/GO related objectives
13208 if( reqTarget != entry )
13209 continue;
13211 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13212 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13213 if ( curCastCount < reqCastCount )
13215 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13216 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13218 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13221 if ( CanCompleteQuest( questid ) )
13222 CompleteQuest( questid );
13224 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13225 break;
13232 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13234 uint32 addTalkCount = 1;
13235 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13237 uint32 questid = GetQuestSlotQuestId(i);
13238 if(!questid)
13239 continue;
13241 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13242 if ( !qInfo )
13243 continue;
13245 QuestStatusData& q_status = mQuestStatus[questid];
13247 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13249 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13251 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13253 // skip spell casts and Gameobject objectives
13254 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13255 continue;
13257 uint32 reqTarget = 0;
13259 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13260 // checked at quest_template loading
13261 reqTarget = qInfo->ReqCreatureOrGOId[j];
13262 else
13263 continue;
13265 if ( reqTarget == entry )
13267 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13268 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13269 if ( curTalkCount < reqTalkCount )
13271 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13272 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13274 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13276 if ( CanCompleteQuest( questid ) )
13277 CompleteQuest( questid );
13279 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13280 continue;
13288 void Player::MoneyChanged( uint32 count )
13290 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13292 uint32 questid = GetQuestSlotQuestId(i);
13293 if (!questid)
13294 continue;
13296 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13297 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13299 QuestStatusData& q_status = mQuestStatus[questid];
13301 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13303 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13305 if ( CanCompleteQuest( questid ) )
13306 CompleteQuest( questid );
13309 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13311 if(int32(count) < -qInfo->GetRewOrReqMoney())
13312 IncompleteQuest( questid );
13318 void Player::ReputationChanged(FactionEntry const* factionEntry )
13320 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13322 if(uint32 questid = GetQuestSlotQuestId(i))
13324 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13326 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13328 QuestStatusData& q_status = mQuestStatus[questid];
13329 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13331 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13332 if ( CanCompleteQuest( questid ) )
13333 CompleteQuest( questid );
13335 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13337 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13338 IncompleteQuest( questid );
13346 bool Player::HasQuestForItem( uint32 itemid ) const
13348 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13350 uint32 questid = GetQuestSlotQuestId(i);
13351 if ( questid == 0 )
13352 continue;
13354 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13355 if(qs_itr == mQuestStatus.end())
13356 continue;
13358 QuestStatusData const& q_status = qs_itr->second;
13360 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13362 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13363 if(!qinfo)
13364 continue;
13366 // hide quest if player is in raid-group and quest is no raid quest
13367 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13368 continue;
13370 // There should be no mixed ReqItem/ReqSource drop
13371 // This part for ReqItem drop
13372 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13374 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13375 return true;
13377 // This part - for ReqSource
13378 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13380 // examined item is a source item
13381 if (qinfo->ReqSourceId[j] == itemid)
13383 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13385 // 'unique' item
13386 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13387 return true;
13389 // allows custom amount drop when not 0
13390 if (qinfo->ReqSourceCount[j])
13392 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13393 return true;
13394 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13395 return true;
13400 return false;
13403 void Player::SendQuestComplete( uint32 quest_id )
13405 if( quest_id )
13407 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13408 data << uint32(quest_id);
13409 GetSession()->SendPacket( &data );
13410 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13414 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13416 uint32 questid = pQuest->GetQuestId();
13417 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13418 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13419 data << uint32(questid);
13421 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13423 data << uint32(XP);
13424 data << uint32(pQuest->GetRewOrReqMoney());
13426 else
13428 data << uint32(0);
13429 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13432 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13433 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13434 GetSession()->SendPacket( &data );
13436 if (pQuest->GetQuestCompleteScript() != 0)
13437 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13440 void Player::SendQuestFailed( uint32 quest_id )
13442 if( quest_id )
13444 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13445 data << quest_id;
13446 data << uint32(0); // failed reason (4 for inventory is full)
13447 GetSession()->SendPacket( &data );
13448 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13452 void Player::SendQuestTimerFailed( uint32 quest_id )
13454 if( quest_id )
13456 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13457 data << quest_id;
13458 GetSession()->SendPacket( &data );
13459 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13463 void Player::SendCanTakeQuestResponse( uint32 msg )
13465 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13466 data << uint32(msg);
13467 GetSession()->SendPacket( &data );
13468 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13471 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13473 if( pPlayer )
13475 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13476 data << uint64(pPlayer->GetGUID());
13477 data << uint8(msg); // valid values: 0-8
13478 GetSession()->SendPacket( &data );
13479 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13483 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13485 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13486 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13487 //data << pQuest->ReqItemId[item_idx];
13488 //data << count;
13489 GetSession()->SendPacket( &data );
13492 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13494 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13496 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13497 if (entry < 0)
13498 // client expected gameobject template id in form (id|0x80000000)
13499 entry = (-entry) | 0x80000000;
13501 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13502 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13503 data << uint32(pQuest->GetQuestId());
13504 data << uint32(entry);
13505 data << uint32(old_count + add_count);
13506 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13507 data << uint64(guid);
13508 GetSession()->SendPacket(&data);
13510 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13511 if( log_slot < MAX_QUEST_LOG_SIZE)
13512 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13515 /*********************************************************/
13516 /*** LOAD SYSTEM ***/
13517 /*********************************************************/
13519 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13521 bool delete_result = true;
13522 if(!result)
13524 // 0 1 2 3 4 5 6 7 8 9
13525 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13526 if(!result) return false;
13528 else delete_result = false;
13530 Field *fields = result->Fetch();
13532 if(!LoadValues( fields[1].GetString()))
13534 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13535 if(delete_result) delete result;
13536 return false;
13539 // overwrite possible wrong/corrupted guid
13540 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13542 m_name = fields[2].GetCppString();
13544 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13545 SetMapId(fields[6].GetUInt32());
13546 // the instance id is not needed at character enum
13548 m_Played_time[0] = fields[7].GetUInt32();
13549 m_Played_time[1] = fields[8].GetUInt32();
13551 m_atLoginFlags = fields[9].GetUInt32();
13553 // I don't see these used anywhere ..
13554 /*_LoadGroup();
13556 _LoadBoundInstances();*/
13558 if (delete_result) delete result;
13560 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13561 m_items[i] = NULL;
13563 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13564 m_deathState = DEAD;
13566 return true;
13569 void Player::_LoadDeclinedNames(QueryResult* result)
13571 if(!result)
13572 return;
13574 if(m_declinedname)
13575 delete m_declinedname;
13577 m_declinedname = new DeclinedName;
13578 Field *fields = result->Fetch();
13579 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13580 m_declinedname->name[i] = fields[i].GetCppString();
13582 delete result;
13585 void Player::_LoadArenaTeamInfo(QueryResult *result)
13587 // arenateamid, played_week, played_season, personal_rating
13588 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13589 if (!result)
13590 return;
13594 Field *fields = result->Fetch();
13596 uint32 arenateamid = fields[0].GetUInt32();
13597 uint32 played_week = fields[1].GetUInt32();
13598 uint32 played_season = fields[2].GetUInt32();
13599 uint32 personal_rating = fields[3].GetUInt32();
13601 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13602 if(!aTeam)
13604 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13605 continue;
13607 uint8 arenaSlot = aTeam->GetSlot();
13609 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13610 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13611 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13612 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13613 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13614 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13616 }while (result->NextRow());
13617 delete result;
13620 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13622 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13623 if(!result)
13624 return false;
13626 Field *fields = result->Fetch();
13628 x = fields[0].GetFloat();
13629 y = fields[1].GetFloat();
13630 z = fields[2].GetFloat();
13631 o = fields[3].GetFloat();
13632 mapid = fields[4].GetUInt32();
13633 in_flight = !fields[5].GetCppString().empty();
13635 delete result;
13636 return true;
13639 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13641 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13642 if( !result )
13643 return false;
13645 Field *fields = result->Fetch();
13647 data = StrSplit(fields[0].GetCppString(), " ");
13649 delete result;
13651 return true;
13654 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13656 if(index >= data.size())
13657 return 0;
13659 return (uint32)atoi(data[index].c_str());
13662 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13664 float result;
13665 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13666 memcpy(&result, &temp, sizeof(result));
13668 return result;
13671 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13673 Tokens data;
13674 if(!LoadValuesArrayFromDB(data,guid))
13675 return 0;
13677 return GetUInt32ValueFromArray(data,index);
13680 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13682 float result;
13683 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13684 memcpy(&result, &temp, sizeof(result));
13686 return result;
13689 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13691 //// 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
13692 //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);
13693 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13695 if(!result)
13697 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13698 return false;
13701 Field *fields = result->Fetch();
13703 uint32 dbAccountId = fields[1].GetUInt32();
13705 // check if the character's account in the db and the logged in account match.
13706 // player should be able to load/delete character only with correct account!
13707 if( dbAccountId != GetSession()->GetAccountId() )
13709 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13710 delete result;
13711 return false;
13714 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13716 m_name = fields[3].GetCppString();
13718 // check name limitations
13719 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13721 delete result;
13722 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13723 return false;
13726 if(!LoadValues( fields[2].GetString()))
13728 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13729 delete result;
13730 return false;
13733 // overwrite possible wrong/corrupted guid
13734 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13736 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13737 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13739 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13740 SetVisibleItemSlot(slot,NULL);
13742 if (m_items[slot])
13744 delete m_items[slot];
13745 m_items[slot] = NULL;
13749 // update money limits
13750 if(GetMoney() > MAX_MONEY_AMOUNT)
13751 SetMoney(MAX_MONEY_AMOUNT);
13753 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13754 outDebugValues();
13756 m_race = fields[4].GetUInt8();
13757 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13758 //Other way is to saves m_team into characters table.
13759 setFactionForRace(m_race);
13760 SetCharm(NULL);
13762 m_class = fields[5].GetUInt8();
13764 // load home bind and check in same time class/race pair, it used later for restore broken positions
13765 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13766 return false;
13768 InitPrimaryProffesions(); // to max set before any spell loaded
13770 // init saved position, and fix it later if problematic
13771 uint32 transGUID = fields[24].GetUInt32();
13772 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13773 SetMapId(fields[9].GetUInt32());
13774 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13776 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13778 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13780 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13781 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13782 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13784 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13786 // check arena teams integrity
13787 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13789 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13790 if(!arena_team_id)
13791 continue;
13793 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13794 if(at->HaveMember(GetGUID()))
13795 continue;
13797 // arena team not exist or not member, cleanup fields
13798 for(int j =0; j < 6; ++j)
13799 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13802 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13804 if(!IsPositionValid())
13806 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());
13807 RelocateToHomebind();
13809 transGUID = 0;
13811 m_movementInfo.t_x = 0.0f;
13812 m_movementInfo.t_y = 0.0f;
13813 m_movementInfo.t_z = 0.0f;
13814 m_movementInfo.t_o = 0.0f;
13817 uint32 bgid = fields[34].GetUInt32();
13818 uint32 bgteam = fields[35].GetUInt32();
13820 if(bgid) //saved in BattleGround
13822 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13824 // check entry point and fix to homebind if need
13825 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13826 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13827 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13829 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13831 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13833 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13834 uint32 queueSlot = AddBattleGroundQueueId(bgQueueTypeId);
13836 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13837 SetBGTeam(bgteam);
13839 //join player to battleground group
13840 currentBg->EventPlayerLoggedIn(this, GetGUID());
13841 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13843 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13845 else
13847 Relocate(GetBattleGroundEntryPoint());
13848 //RemoveArenaAuras(true);
13851 else
13853 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13854 // if server restart after player save in BG or area
13855 // player can have current coordinates in to BG/Arean map, fix this
13856 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13858 // return to BG master
13859 SetMapId(fields[36].GetUInt32());
13860 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13862 // check entry point and fix to homebind if need
13863 mapEntry = sMapStore.LookupEntry(GetMapId());
13864 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13865 RelocateToHomebind();
13869 if (transGUID != 0)
13871 m_movementInfo.t_x = fields[20].GetFloat();
13872 m_movementInfo.t_y = fields[21].GetFloat();
13873 m_movementInfo.t_z = fields[22].GetFloat();
13874 m_movementInfo.t_o = fields[23].GetFloat();
13876 if( !MaNGOS::IsValidMapCoord(
13877 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13878 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13879 // transport size limited
13880 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13882 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13883 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13884 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13886 RelocateToHomebind();
13888 m_movementInfo.t_x = 0.0f;
13889 m_movementInfo.t_y = 0.0f;
13890 m_movementInfo.t_z = 0.0f;
13891 m_movementInfo.t_o = 0.0f;
13893 transGUID = 0;
13897 if (transGUID != 0)
13899 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13901 if( (*iter)->GetGUIDLow() == transGUID)
13903 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13904 // client without expansion support
13905 if(GetSession()->Expansion() < transMapEntry->Expansion())
13907 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13908 break;
13911 m_transport = *iter;
13912 m_transport->AddPassenger(this);
13913 SetMapId(m_transport->GetMapId());
13914 break;
13918 if(!m_transport)
13920 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13921 guid,transGUID);
13923 RelocateToHomebind();
13925 m_movementInfo.t_x = 0.0f;
13926 m_movementInfo.t_y = 0.0f;
13927 m_movementInfo.t_z = 0.0f;
13928 m_movementInfo.t_o = 0.0f;
13930 transGUID = 0;
13933 else // not transport case
13935 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13936 // client without expansion support
13937 if(GetSession()->Expansion() < mapEntry->Expansion())
13939 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
13940 RelocateToHomebind();
13944 // NOW player must have valid map
13945 // load the player's map here if it's not already loaded
13946 Map *map = GetMap();
13948 // since the player may not be bound to the map yet, make sure subsequent
13949 // getmap calls won't create new maps
13950 SetInstanceId(map->GetInstanceId());
13952 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
13953 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
13955 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
13956 if(at)
13957 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
13958 else
13959 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());
13962 SaveRecallPosition();
13964 time_t now = time(NULL);
13965 time_t logoutTime = time_t(fields[16].GetUInt64());
13967 // since last logout (in seconds)
13968 uint64 time_diff = uint64(now - logoutTime);
13970 // set value, including drunk invisibility detection
13971 // calculate sobering. after 15 minutes logged out, the player will be sober again
13972 float soberFactor;
13973 if(time_diff > 15*MINUTE)
13974 soberFactor = 0;
13975 else
13976 soberFactor = 1-time_diff/(15.0f*MINUTE);
13977 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13978 SetDrunkValue(newDrunkenValue);
13980 m_rest_bonus = fields[15].GetFloat();
13981 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13982 float bubble0 = 0.031;
13983 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13984 float bubble1 = 0.125;
13986 if((int32)fields[16].GetUInt32() > 0)
13988 float bubble = fields[17].GetUInt32() > 0
13989 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13990 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13992 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13995 m_cinematic = fields[12].GetUInt32();
13996 m_Played_time[0]= fields[13].GetUInt32();
13997 m_Played_time[1]= fields[14].GetUInt32();
13999 m_resetTalentsCost = fields[18].GetUInt32();
14000 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14002 // reserve some flags
14003 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14005 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14006 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14008 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14010 uint32 extraflags = fields[25].GetUInt32();
14012 m_stableSlots = fields[26].GetUInt32();
14013 if(m_stableSlots > MAX_PET_STABLES)
14015 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14016 m_stableSlots = MAX_PET_STABLES;
14019 m_atLoginFlags = fields[27].GetUInt32();
14021 // Honor system
14022 // Update Honor kills data
14023 m_lastHonorUpdateTime = logoutTime;
14024 UpdateHonorFields();
14026 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14027 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14028 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14030 std::string taxi_nodes = fields[31].GetCppString();
14032 delete result;
14034 // clear channel spell data (if saved at channel spell casting)
14035 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14036 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14038 // clear charm/summon related fields
14039 SetCharm(NULL);
14040 SetPet(NULL);
14041 SetCharmerGUID(0);
14042 SetOwnerGUID(0);
14043 SetCreatorGUID(0);
14045 // reset some aura modifiers before aura apply
14046 SetFarSightGUID(0);
14047 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14048 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14050 _LoadSkills();
14052 // make sure the unit is considered out of combat for proper loading
14053 ClearInCombat();
14055 // make sure the unit is considered not in duel for proper loading
14056 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14057 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14059 // remember loaded power/health values to restore after stats initialization and modifier applying
14060 uint32 savedHealth = GetHealth();
14061 uint32 savedPower[MAX_POWERS];
14062 for(uint32 i = 0; i < MAX_POWERS; ++i)
14063 savedPower[i] = GetPower(Powers(i));
14065 // reset stats before loading any modifiers
14066 InitStatsForLevel();
14067 InitTaxiNodesForLevel();
14068 InitGlyphsForLevel();
14069 InitRunes();
14071 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14073 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14074 //_LoadMail();
14076 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14077 _LoadGlyphAuras();
14079 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14080 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14081 m_deathState = DEAD;
14083 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14085 // after spell load, learn rewarded spell if need also
14086 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14087 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14089 // after spell and quest load
14090 InitTalentForLevel();
14091 learnDefaultSpells();
14093 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14095 // must be before inventory (some items required reputation check)
14096 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14098 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14100 // update items with duration and realtime
14101 UpdateItemDuration(time_diff, true);
14103 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14105 // unread mails and next delivery time, actual mails not loaded
14106 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14108 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14110 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14111 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14112 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14114 if(!HasTitle(curTitle))
14115 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14118 // Not finish taxi flight path
14119 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14121 // problems with taxi path loading
14122 TaxiNodesEntry const* nodeEntry = NULL;
14123 if(uint32 node_id = m_taxi.GetTaxiSource())
14124 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14126 if(!nodeEntry) // don't know taxi start node, to homebind
14128 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14129 RelocateToHomebind();
14130 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14132 else // have start node, to it
14134 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14135 SetMapId(nodeEntry->map_id);
14136 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14137 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14139 m_taxi.ClearTaxiDestinations();
14141 else if(uint32 node_id = m_taxi.GetTaxiSource())
14143 // save source node as recall coord to prevent recall and fall from sky
14144 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14145 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14146 m_recallMap = nodeEntry->map_id;
14147 m_recallX = nodeEntry->x;
14148 m_recallY = nodeEntry->y;
14149 m_recallZ = nodeEntry->z;
14151 // flight will started later
14154 // has to be called after last Relocate() in Player::LoadFromDB
14155 SetFallInformation(0, GetPositionZ());
14157 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14159 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14160 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14161 if(!isAlive())
14162 RemoveAllAurasOnDeath();
14164 //apply all stat bonuses from items and auras
14165 SetCanModifyStats(true);
14166 UpdateAllStats();
14168 // restore remembered power/health values (but not more max values)
14169 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14170 for(uint32 i = 0; i < MAX_POWERS; ++i)
14171 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14173 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14174 outDebugValues();
14176 // GM state
14177 if(GetSession()->GetSecurity() > SEC_PLAYER)
14179 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14181 default:
14182 case 0: break; // disable
14183 case 1: SetGameMaster(true); break; // enable
14184 case 2: // save state
14185 if(extraflags & PLAYER_EXTRA_GM_ON)
14186 SetGameMaster(true);
14187 break;
14190 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14192 default:
14193 case 0: SetGMVisible(false); break; // invisible
14194 case 1: break; // visible
14195 case 2: // save state
14196 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14197 SetGMVisible(false);
14198 break;
14201 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14203 default:
14204 case 0: break; // disable
14205 case 1: SetAcceptTicket(true); break; // enable
14206 case 2: // save state
14207 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14208 SetAcceptTicket(true);
14209 break;
14212 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14214 default:
14215 case 0: break; // disable
14216 case 1: SetGMChat(true); break; // enable
14217 case 2: // save state
14218 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14219 SetGMChat(true);
14220 break;
14223 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14225 default:
14226 case 0: break; // disable
14227 case 1: SetAcceptWhispers(true); break; // enable
14228 case 2: // save state
14229 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14230 SetAcceptWhispers(true);
14231 break;
14235 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14237 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14238 m_achievementMgr.CheckAllAchievementCriteria();
14239 return true;
14242 bool Player::isAllowedToLoot(Creature* creature)
14244 if(Player* recipient = creature->GetLootRecipient())
14246 if (recipient == this)
14247 return true;
14248 if( Group* otherGroup = recipient->GetGroup())
14250 Group* thisGroup = GetGroup();
14251 if(!thisGroup)
14252 return false;
14253 return thisGroup == otherGroup;
14255 return false;
14257 else
14258 // prevent other players from looting if the recipient got disconnected
14259 return !creature->hasLootRecipient();
14262 void Player::_LoadActions(QueryResult *result)
14264 m_actionButtons.clear();
14266 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14268 if(result)
14272 Field *fields = result->Fetch();
14274 uint8 button = fields[0].GetUInt8();
14276 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14277 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14278 else
14280 sLog.outError( " ...at loading, and will deleted in DB also");
14282 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14283 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14286 while( result->NextRow() );
14288 delete result;
14292 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14294 m_Auras.clear();
14295 for (int i = 0; i < TOTAL_AURAS; i++)
14296 m_modAuras[i].clear();
14298 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14300 if(result)
14304 Field *fields = result->Fetch();
14305 uint64 caster_guid = fields[0].GetUInt64();
14306 uint32 spellid = fields[1].GetUInt32();
14307 uint32 effindex = fields[2].GetUInt32();
14308 uint32 stackcount = fields[3].GetUInt32();
14309 int32 damage = (int32)fields[4].GetUInt32();
14310 int32 maxduration = (int32)fields[5].GetUInt32();
14311 int32 remaintime = (int32)fields[6].GetUInt32();
14312 int32 remaincharges = (int32)fields[7].GetUInt32();
14314 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14315 if(!spellproto)
14317 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14318 continue;
14321 if(effindex >= 3)
14323 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14324 continue;
14327 // negative effects should continue counting down after logout
14328 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14330 if(remaintime <= int32(timediff))
14331 continue;
14333 remaintime -= timediff;
14336 // prevent wrong values of remaincharges
14337 if(spellproto->procCharges)
14339 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14340 remaincharges = spellproto->procCharges;
14342 else
14343 remaincharges = 0;
14346 for(uint32 i=0; i<stackcount; i++)
14348 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14349 if(!damage)
14350 damage = aura->GetModifier()->m_amount;
14352 // reset stolen single target auras
14353 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14354 aura->SetIsSingleTarget(false);
14356 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14357 AddAura(aura);
14358 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14361 while( result->NextRow() );
14363 delete result;
14366 if(m_class == CLASS_WARRIOR)
14367 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14370 void Player::_LoadGlyphAuras()
14372 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14374 if (uint32 glyph = GetGlyph(i))
14376 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14378 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14380 if(gp->TypeFlags == gs->TypeFlags)
14382 CastSpell(this, gp->SpellId, true);
14383 continue;
14385 else
14386 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14388 else
14389 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14391 else
14392 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14394 // On any error remove glyph
14395 SetGlyph(i, 0);
14400 void Player::LoadCorpse()
14402 if( isAlive() )
14404 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14406 else
14408 if(Corpse *corpse = GetCorpse())
14410 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14412 else
14414 //Prevent Dead Player login without corpse
14415 ResurrectPlayer(0.5f);
14420 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14422 //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());
14423 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14424 //NOTE: the "order by `bag`" is important because it makes sure
14425 //the bagMap is filled before items in the bags are loaded
14426 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14427 //expected to be equipped before offhand items (TODO: fixme)
14429 uint32 zone = GetZoneId();
14431 if (result)
14433 std::list<Item*> problematicItems;
14435 // prevent items from being added to the queue when stored
14436 m_itemUpdateQueueBlocked = true;
14439 Field *fields = result->Fetch();
14440 uint32 bag_guid = fields[1].GetUInt32();
14441 uint8 slot = fields[2].GetUInt8();
14442 uint32 item_guid = fields[3].GetUInt32();
14443 uint32 item_id = fields[4].GetUInt32();
14445 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14447 if(!proto)
14449 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14450 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14451 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14452 continue;
14455 Item *item = NewItemOrBag(proto);
14457 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14459 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14460 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14461 item->FSetState(ITEM_REMOVED);
14462 item->SaveToDB(); // it also deletes item object !
14463 continue;
14466 // not allow have in alive state item limited to another map/zone
14467 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14469 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14470 item->FSetState(ITEM_REMOVED);
14471 item->SaveToDB(); // it also deletes item object !
14472 continue;
14475 // "Conjured items disappear if you are logged out for more than 15 minutes"
14476 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14478 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14479 item->FSetState(ITEM_REMOVED);
14480 item->SaveToDB(); // it also deletes item object !
14481 continue;
14484 bool success = true;
14486 if (!bag_guid)
14488 // the item is not in a bag
14489 item->SetContainer( NULL );
14490 item->SetSlot(slot);
14492 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14494 ItemPosCountVec dest;
14495 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14496 item = StoreItem(dest, item, true);
14497 else
14498 success = false;
14500 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14502 uint16 dest;
14503 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14504 QuickEquipItem(dest, item);
14505 else
14506 success = false;
14508 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14510 ItemPosCountVec dest;
14511 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14512 item = BankItem(dest, item, true);
14513 else
14514 success = false;
14517 if(success)
14519 // store bags that may contain items in them
14520 if(item->IsBag() && IsBagPos(item->GetPos()))
14521 bagMap[item_guid] = (Bag*)item;
14524 else
14526 item->SetSlot(NULL_SLOT);
14527 // the item is in a bag, find the bag
14528 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14529 if(itr != bagMap.end())
14530 itr->second->StoreItem(slot, item, true );
14531 else
14532 success = false;
14535 // item's state may have changed after stored
14536 if (success)
14537 item->SetState(ITEM_UNCHANGED, this);
14538 else
14540 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);
14541 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14542 problematicItems.push_back(item);
14544 } while (result->NextRow());
14546 delete result;
14547 m_itemUpdateQueueBlocked = false;
14549 // send by mail problematic items
14550 while(!problematicItems.empty())
14552 // fill mail
14553 MailItemsInfo mi; // item list preparing
14555 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14557 Item* item = problematicItems.front();
14558 problematicItems.pop_front();
14560 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14563 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14565 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14568 //if(isAlive())
14569 _ApplyAllItemMods();
14572 // load mailed item which should receive current player
14573 void Player::_LoadMailedItems(Mail *mail)
14575 // data needs to be at first place for Item::LoadFromDB
14576 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);
14577 if(!result)
14578 return;
14582 Field *fields = result->Fetch();
14583 uint32 item_guid_low = fields[1].GetUInt32();
14584 uint32 item_template = fields[2].GetUInt32();
14586 mail->AddItem(item_guid_low, item_template);
14588 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14590 if(!proto)
14592 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);
14593 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14594 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14595 continue;
14598 Item *item = NewItemOrBag(proto);
14600 if(!item->LoadFromDB(item_guid_low, 0, result))
14602 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14603 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14604 item->FSetState(ITEM_REMOVED);
14605 item->SaveToDB(); // it also deletes item object !
14606 continue;
14609 AddMItem(item);
14610 } while (result->NextRow());
14612 delete result;
14615 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14617 //set a count of unread mails
14618 //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);
14619 if (resultUnread)
14621 Field *fieldMail = resultUnread->Fetch();
14622 unReadMails = fieldMail[0].GetUInt8();
14623 delete resultUnread;
14626 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14627 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14628 if (resultDelivery)
14630 Field *fieldMail = resultDelivery->Fetch();
14631 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14632 delete resultDelivery;
14636 void Player::_LoadMail()
14638 m_mail.clear();
14639 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14640 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());
14641 if(result)
14645 Field *fields = result->Fetch();
14646 Mail *m = new Mail;
14647 m->messageID = fields[0].GetUInt32();
14648 m->messageType = fields[1].GetUInt8();
14649 m->sender = fields[2].GetUInt32();
14650 m->receiver = fields[3].GetUInt32();
14651 m->subject = fields[4].GetCppString();
14652 m->itemTextId = fields[5].GetUInt32();
14653 bool has_items = fields[6].GetBool();
14654 m->expire_time = (time_t)fields[7].GetUInt64();
14655 m->deliver_time = (time_t)fields[8].GetUInt64();
14656 m->money = fields[9].GetUInt32();
14657 m->COD = fields[10].GetUInt32();
14658 m->checked = fields[11].GetUInt32();
14659 m->stationery = fields[12].GetUInt8();
14660 m->mailTemplateId = fields[13].GetInt16();
14662 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14664 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14665 m->mailTemplateId = 0;
14668 m->state = MAIL_STATE_UNCHANGED;
14670 if (has_items)
14671 _LoadMailedItems(m);
14673 m_mail.push_back(m);
14674 } while( result->NextRow() );
14675 delete result;
14677 m_mailsLoaded = true;
14680 void Player::LoadPet()
14682 //fixme: the pet should still be loaded if the player is not in world
14683 // just not added to the map
14684 if(IsInWorld())
14686 Pet *pet = new Pet;
14687 if(!pet->LoadPetFromDB(this,0,0,true))
14688 delete pet;
14692 void Player::_LoadQuestStatus(QueryResult *result)
14694 mQuestStatus.clear();
14696 uint32 slot = 0;
14698 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14699 //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());
14701 if(result)
14705 Field *fields = result->Fetch();
14707 uint32 quest_id = fields[0].GetUInt32();
14708 // used to be new, no delete?
14709 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14710 if( pQuest )
14712 // find or create
14713 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14715 uint32 qstatus = fields[1].GetUInt32();
14716 if(qstatus < MAX_QUEST_STATUS)
14717 questStatusData.m_status = QuestStatus(qstatus);
14718 else
14720 questStatusData.m_status = QUEST_STATUS_NONE;
14721 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14724 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14725 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14727 time_t quest_time = time_t(fields[4].GetUInt64());
14729 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14731 AddTimedQuest( quest_id );
14733 if (quest_time <= sWorld.GetGameTime())
14734 questStatusData.m_timer = 1;
14735 else
14736 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14738 else
14739 quest_time = 0;
14741 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14742 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14743 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14744 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14745 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14746 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14747 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14748 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14750 questStatusData.uState = QUEST_UNCHANGED;
14752 // add to quest log
14753 if( slot < MAX_QUEST_LOG_SIZE &&
14754 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14755 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14756 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14758 SetQuestSlot(slot,quest_id,quest_time);
14760 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14761 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14763 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14764 if(questStatusData.m_creatureOrGOcount[idx])
14765 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14767 ++slot;
14770 if(questStatusData.m_rewarded)
14772 // learn rewarded spell if unknown
14773 learnQuestRewardedSpells(pQuest);
14775 // set rewarded title if any
14776 if(pQuest->GetCharTitleId())
14778 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14779 SetTitle(titleEntry);
14782 if(pQuest->GetBonusTalents())
14783 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14786 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14789 while( result->NextRow() );
14791 delete result;
14794 // clear quest log tail
14795 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14796 SetQuestSlot(i,0);
14799 void Player::_LoadDailyQuestStatus(QueryResult *result)
14801 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14802 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14804 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14806 if(result)
14808 uint32 quest_daily_idx = 0;
14812 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14814 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14815 break;
14818 Field *fields = result->Fetch();
14820 uint32 quest_id = fields[0].GetUInt32();
14822 // save _any_ from daily quest times (it must be after last reset anyway)
14823 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14825 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14826 if( !pQuest )
14827 continue;
14829 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14830 ++quest_daily_idx;
14832 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14834 while( result->NextRow() );
14836 delete result;
14839 m_DailyQuestChanged = false;
14842 void Player::_LoadSpells(QueryResult *result)
14844 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14846 if(result)
14850 Field *fields = result->Fetch();
14852 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14854 while( result->NextRow() );
14856 delete result;
14860 void Player::_LoadTutorials(QueryResult *result)
14862 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14864 if(result)
14868 Field *fields = result->Fetch();
14870 for (int iI=0; iI<8; iI++)
14871 m_Tutorials[iI] = fields[iI].GetUInt32();
14873 while( result->NextRow() );
14875 delete result;
14878 m_TutorialsChanged = false;
14881 void Player::_LoadGroup(QueryResult *result)
14883 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14884 if(result)
14886 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14887 delete result;
14888 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14889 if(group)
14891 uint8 subgroup = group->GetMemberGroup(GetGUID());
14892 SetGroup(group, subgroup);
14893 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14895 // the group leader may change the instance difficulty while the player is offline
14896 SetDifficulty(group->GetDifficulty());
14902 void Player::_LoadBoundInstances(QueryResult *result)
14904 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14905 m_boundInstances[i].clear();
14907 Group *group = GetGroup();
14909 //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));
14910 if(result)
14914 Field *fields = result->Fetch();
14915 bool perm = fields[1].GetBool();
14916 uint32 mapId = fields[2].GetUInt32();
14917 uint32 instanceId = fields[0].GetUInt32();
14918 uint8 difficulty = fields[3].GetUInt8();
14919 time_t resetTime = (time_t)fields[4].GetUInt64();
14920 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14921 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14922 // and in that case it is not used
14924 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
14925 if(!mapEntry || !mapEntry->IsDungeon())
14927 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
14928 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14929 continue;
14932 if(!perm && group)
14934 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);
14935 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14936 continue;
14939 // since non permanent binds are always solo bind, they can always be reset
14940 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14941 if(save) BindToInstance(save, perm, true);
14942 } while(result->NextRow());
14943 delete result;
14947 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14949 // some instances only have one difficulty
14950 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14951 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14953 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14954 if(itr != m_boundInstances[difficulty].end())
14955 return &itr->second;
14956 else
14957 return NULL;
14960 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14962 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14963 UnbindInstance(itr, difficulty, unload);
14966 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14968 if(itr != m_boundInstances[difficulty].end())
14970 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14971 itr->second.save->RemovePlayer(this); // save can become invalid
14972 m_boundInstances[difficulty].erase(itr++);
14976 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14978 if(save)
14980 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14981 if(bind.save)
14983 // update the save when the group kills a boss
14984 if(permanent != bind.perm || save != bind.save)
14985 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());
14987 else
14988 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14990 if(bind.save != save)
14992 if(bind.save) bind.save->RemovePlayer(this);
14993 save->AddPlayer(this);
14996 if(permanent) save->SetCanReset(false);
14998 bind.save = save;
14999 bind.perm = permanent;
15000 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());
15001 return &bind;
15003 else
15004 return NULL;
15007 void Player::SendRaidInfo()
15009 uint32 counter = 0;
15011 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15013 size_t p_counter = data.wpos();
15014 data << uint32(counter); // placeholder
15016 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15018 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15020 if(itr->second.perm)
15022 InstanceSave *save = itr->second.save;
15023 data << uint32(save->GetMapId());
15024 data << uint32(save->GetResetTime() - time(NULL));
15025 data << uint32(save->GetInstanceId());
15026 data << uint32(save->GetDifficulty());
15027 ++counter;
15031 data.put<uint32>(p_counter,counter);
15032 GetSession()->SendPacket(&data);
15036 - called on every successful teleportation to a map
15038 void Player::SendSavedInstances()
15040 bool hasBeenSaved = false;
15041 WorldPacket data;
15043 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15045 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15047 if(itr->second.perm) // only permanent binds are sent
15049 hasBeenSaved = true;
15050 break;
15055 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15056 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15057 data << uint32(hasBeenSaved);
15058 GetSession()->SendPacket(&data);
15060 if(!hasBeenSaved)
15061 return;
15063 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15065 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15067 if(itr->second.perm)
15069 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15070 data << uint32(itr->second.save->GetMapId());
15071 GetSession()->SendPacket(&data);
15077 /// convert the player's binds to the group
15078 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15080 bool has_binds = false;
15081 bool has_solo = false;
15083 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15084 assert(player_guid);
15086 // copy all binds to the group, when changing leader it's assumed the character
15087 // will not have any solo binds
15089 if(player)
15091 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15093 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15095 has_binds = true;
15096 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15097 // permanent binds are not removed
15098 if(!itr->second.perm)
15100 player->UnbindInstance(itr, i, true); // increments itr
15101 has_solo = true;
15103 else
15104 ++itr;
15109 // if the player's not online we don't know what binds it has
15110 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));
15111 // the following should not get executed when changing leaders
15112 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15115 bool Player::_LoadHomeBind(QueryResult *result)
15117 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15118 if(!info)
15120 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15121 return false;
15124 bool ok = false;
15125 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15126 if (result)
15128 Field *fields = result->Fetch();
15129 m_homebindMapId = fields[0].GetUInt32();
15130 m_homebindZoneId = fields[1].GetUInt16();
15131 m_homebindX = fields[2].GetFloat();
15132 m_homebindY = fields[3].GetFloat();
15133 m_homebindZ = fields[4].GetFloat();
15134 delete result;
15136 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15138 // accept saved data only for valid position (and non instanceable), and accessable
15139 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15140 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15142 ok = true;
15144 else
15145 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15148 if(!ok)
15150 m_homebindMapId = info->mapId;
15151 m_homebindZoneId = info->zoneId;
15152 m_homebindX = info->positionX;
15153 m_homebindY = info->positionY;
15154 m_homebindZ = info->positionZ;
15156 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);
15159 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15160 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15162 return true;
15165 /*********************************************************/
15166 /*** SAVE SYSTEM ***/
15167 /*********************************************************/
15169 void Player::SaveToDB()
15171 // delay auto save at any saves (manual, in code, or autosave)
15172 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15174 // first save/honor gain after midnight will also update the player's honor fields
15175 UpdateHonorFields();
15177 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15178 //save, far from tavern/city
15179 //save, but in tavern/city
15180 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15181 outDebugValues();
15183 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15184 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15185 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15186 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15187 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15188 uint32 tmp_displayid = GetDisplayId();
15190 // Set player sit state to standing on save, also stealth and shifted form
15191 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15192 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15193 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15194 SetDisplayId(GetNativeDisplayId());
15196 bool inworld = IsInWorld();
15198 CharacterDatabase.BeginTransaction();
15200 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15202 std::string sql_name = m_name;
15203 CharacterDatabase.escape_string(sql_name);
15205 std::ostringstream ss;
15206 ss << "INSERT INTO characters (guid,account,name,race,class,"
15207 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15208 "taximask, online, cinematic, "
15209 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15210 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15211 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15212 << GetGUIDLow() << ", "
15213 << GetSession()->GetAccountId() << ", '"
15214 << sql_name << "', "
15215 << m_race << ", "
15216 << m_class << ", ";
15218 if(!IsBeingTeleported())
15220 ss << GetMapId() << ", "
15221 << (uint32)GetDifficulty() << ", "
15222 << finiteAlways(GetPositionX()) << ", "
15223 << finiteAlways(GetPositionY()) << ", "
15224 << finiteAlways(GetPositionZ()) << ", "
15225 << finiteAlways(GetOrientation()) << ", '";
15227 else
15229 ss << GetTeleportDest().mapid << ", "
15230 << (uint32)GetDifficulty() << ", "
15231 << finiteAlways(GetTeleportDest().x) << ", "
15232 << finiteAlways(GetTeleportDest().y) << ", "
15233 << finiteAlways(GetTeleportDest().z) << ", "
15234 << finiteAlways(GetTeleportDest().o) << ", '";
15237 uint16 i;
15238 for( i = 0; i < m_valuesCount; i++ )
15240 ss << GetUInt32Value(i) << " ";
15243 ss << "', ";
15245 ss << m_taxi; // string with TaxiMaskSize numbers
15247 ss << ", ";
15248 ss << (inworld ? 1 : 0);
15250 ss << ", ";
15251 ss << m_cinematic;
15253 ss << ", ";
15254 ss << m_Played_time[0];
15255 ss << ", ";
15256 ss << m_Played_time[1];
15258 ss << ", ";
15259 ss << finiteAlways(m_rest_bonus);
15260 ss << ", ";
15261 ss << (uint64)time(NULL);
15262 ss << ", ";
15263 ss << is_save_resting;
15264 ss << ", ";
15265 ss << m_resetTalentsCost;
15266 ss << ", ";
15267 ss << (uint64)m_resetTalentsTime;
15269 ss << ", ";
15270 ss << finiteAlways(m_movementInfo.t_x);
15271 ss << ", ";
15272 ss << finiteAlways(m_movementInfo.t_y);
15273 ss << ", ";
15274 ss << finiteAlways(m_movementInfo.t_z);
15275 ss << ", ";
15276 ss << finiteAlways(m_movementInfo.t_o);
15277 ss << ", ";
15278 if (m_transport)
15279 ss << m_transport->GetGUIDLow();
15280 else
15281 ss << "0";
15283 ss << ", ";
15284 ss << m_ExtraFlags;
15286 ss << ", ";
15287 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15289 ss << ", ";
15290 ss << uint32(m_atLoginFlags);
15292 ss << ", ";
15293 ss << GetZoneId();
15295 ss << ", ";
15296 ss << (uint64)m_deathExpireTime;
15298 ss << ", '";
15299 ss << m_taxi.SaveTaxiDestinationsToString();
15300 ss << "', '0', ";
15301 ss << GetBattleGroundId();
15302 ss << ", ";
15303 ss << GetBGTeam();
15304 ss << ", ";
15305 ss << m_bgEntryPoint.mapid << ", "
15306 << finiteAlways(m_bgEntryPoint.x) << ", "
15307 << finiteAlways(m_bgEntryPoint.y) << ", "
15308 << finiteAlways(m_bgEntryPoint.z) << ", "
15309 << finiteAlways(m_bgEntryPoint.o);
15310 ss << ")";
15312 CharacterDatabase.Execute( ss.str().c_str() );
15314 if(m_mailsUpdated) //save mails only when needed
15315 _SaveMail();
15317 _SaveInventory();
15318 _SaveQuestStatus();
15319 _SaveDailyQuestStatus();
15320 _SaveTutorials();
15321 _SaveSpells();
15322 _SaveSpellCooldowns();
15323 _SaveActions();
15324 _SaveAuras();
15325 m_achievementMgr.SaveToDB();
15326 m_reputationMgr.SaveToDB();
15328 CharacterDatabase.CommitTransaction();
15330 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15331 SetDisplayId(tmp_displayid);
15332 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15333 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15334 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15335 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15337 // save pet (hunter pet level and experience and all type pets health/mana).
15338 if(Pet* pet = GetPet())
15339 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15342 // fast save function for item/money cheating preventing - save only inventory and money state
15343 void Player::SaveInventoryAndGoldToDB()
15345 _SaveInventory();
15346 //money is in data field
15347 SaveDataFieldToDB();
15350 void Player::_SaveActions()
15352 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15354 switch (itr->second.uState)
15356 case ACTIONBUTTON_NEW:
15357 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15358 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15359 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15360 ++itr;
15361 break;
15362 case ACTIONBUTTON_CHANGED:
15363 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15364 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15365 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15366 ++itr;
15367 break;
15368 case ACTIONBUTTON_DELETED:
15369 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15370 m_actionButtons.erase(itr++);
15371 break;
15372 default:
15373 ++itr;
15374 break;
15379 void Player::_SaveAuras()
15381 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15383 AuraMap const& auras = GetAuras();
15385 if (auras.empty())
15386 return;
15388 spellEffectPair lastEffectPair = auras.begin()->first;
15389 uint32 stackCounter = 1;
15391 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15393 if(itr == auras.end() || lastEffectPair != itr->first)
15395 AuraMap::const_iterator itr2 = itr;
15396 // save previous spellEffectPair to db
15397 itr2--;
15399 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15401 //skip all auras from spells that are passive or need a shapeshift
15402 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15404 //do not save single target auras (unless they were cast by the player)
15405 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15407 uint8 i;
15408 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15409 for (i = 0; i < 3; i++)
15410 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15411 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15412 break;
15414 if (i == 3)
15416 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15417 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15418 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()));
15423 if(itr == auras.end())
15424 break;
15427 if (lastEffectPair == itr->first)
15428 stackCounter++;
15429 else
15431 lastEffectPair = itr->first;
15432 stackCounter = 1;
15437 void Player::_SaveInventory()
15439 // force items in buyback slots to new state
15440 // and remove those that aren't already
15441 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15443 Item *item = m_items[i];
15444 if (!item || item->GetState() == ITEM_NEW) continue;
15445 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15446 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15447 m_items[i]->FSetState(ITEM_NEW);
15450 // update enchantment durations
15451 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15453 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15456 // if no changes
15457 if (m_itemUpdateQueue.empty()) return;
15459 // do not save if the update queue is corrupt
15460 bool error = false;
15461 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15463 Item *item = m_itemUpdateQueue[i];
15464 if(!item || item->GetState() == ITEM_REMOVED) continue;
15465 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15467 if (test == NULL)
15469 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());
15470 error = true;
15472 else if (test != item)
15474 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());
15475 error = true;
15479 if (error)
15481 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15482 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15483 return;
15486 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15488 Item *item = m_itemUpdateQueue[i];
15489 if(!item) continue;
15491 Bag *container = item->GetContainer();
15492 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15494 switch(item->GetState())
15496 case ITEM_NEW:
15497 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());
15498 break;
15499 case ITEM_CHANGED:
15500 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());
15501 break;
15502 case ITEM_REMOVED:
15503 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15504 break;
15505 case ITEM_UNCHANGED:
15506 break;
15509 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15511 m_itemUpdateQueue.clear();
15514 void Player::_SaveMail()
15516 if (!m_mailsLoaded)
15517 return;
15519 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15521 Mail *m = (*itr);
15522 if (m->state == MAIL_STATE_CHANGED)
15524 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'",
15525 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15526 if(m->removedItems.size())
15528 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15529 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15530 m->removedItems.clear();
15532 m->state = MAIL_STATE_UNCHANGED;
15534 else if (m->state == MAIL_STATE_DELETED)
15536 if (m->HasItems())
15537 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15538 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15539 if (m->itemTextId)
15540 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15541 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15542 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15546 //deallocate deleted mails...
15547 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15549 if ((*itr)->state == MAIL_STATE_DELETED)
15551 Mail* m = *itr;
15552 m_mail.erase(itr);
15553 delete m;
15554 itr = m_mail.begin();
15556 else
15557 ++itr;
15560 m_mailsUpdated = false;
15563 void Player::_SaveQuestStatus()
15565 // we don't need transactions here.
15566 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15568 switch (i->second.uState)
15570 case QUEST_NEW :
15571 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15572 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15573 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]);
15574 break;
15575 case QUEST_CHANGED :
15576 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' ",
15577 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 );
15578 break;
15579 case QUEST_UNCHANGED:
15580 break;
15582 i->second.uState = QUEST_UNCHANGED;
15586 void Player::_SaveDailyQuestStatus()
15588 if(!m_DailyQuestChanged)
15589 return;
15591 m_DailyQuestChanged = false;
15593 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15595 // we don't need transactions here.
15596 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15597 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15598 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15599 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15600 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15603 void Player::_SaveSpells()
15605 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15607 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15608 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15610 // add only changed/new not dependent spells
15611 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15612 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);
15614 if (itr->second->state == PLAYERSPELL_REMOVED)
15616 delete itr->second;
15617 m_spells.erase(itr++);
15619 else
15621 itr->second->state = PLAYERSPELL_UNCHANGED;
15622 ++itr;
15628 void Player::_SaveTutorials()
15630 if(!m_TutorialsChanged)
15631 return;
15633 uint32 Rows=0;
15634 // it's better than rebuilding indexes multiple times
15635 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15636 if(result)
15638 Rows = result->Fetch()[0].GetUInt32();
15639 delete result;
15642 if (Rows)
15644 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'",
15645 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 );
15647 else
15649 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]);
15652 m_TutorialsChanged = false;
15655 void Player::outDebugValues() const
15657 if(!sLog.IsOutDebug()) // optimize disabled debug output
15658 return;
15660 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15661 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15662 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15663 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15664 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15665 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15666 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15667 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15668 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15669 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15670 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15671 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15674 /*********************************************************/
15675 /*** FLOOD FILTER SYSTEM ***/
15676 /*********************************************************/
15678 void Player::UpdateSpeakTime()
15680 // ignore chat spam protection for GMs in any mode
15681 if(GetSession()->GetSecurity() > SEC_PLAYER)
15682 return;
15684 time_t current = time (NULL);
15685 if(m_speakTime > current)
15687 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15688 if(!max_count)
15689 return;
15691 ++m_speakCount;
15692 if(m_speakCount >= max_count)
15694 // prevent overwrite mute time, if message send just before mutes set, for example.
15695 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15696 if(GetSession()->m_muteTime < new_mute)
15697 GetSession()->m_muteTime = new_mute;
15699 m_speakCount = 0;
15702 else
15703 m_speakCount = 0;
15705 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15708 bool Player::CanSpeak() const
15710 return GetSession()->m_muteTime <= time (NULL);
15713 /*********************************************************/
15714 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15715 /*********************************************************/
15717 void Player::SendAttackSwingNotInRange()
15719 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15720 GetSession()->SendPacket( &data );
15723 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15725 std::ostringstream ss;
15726 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15727 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15728 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15729 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15730 sLog.outDebug(ss.str().c_str());
15731 CharacterDatabase.Execute(ss.str().c_str());
15734 void Player::SaveDataFieldToDB()
15736 std::ostringstream ss;
15737 ss<<"UPDATE characters SET data='";
15739 for(uint16 i = 0; i < m_valuesCount; i++ )
15741 ss << GetUInt32Value(i) << " ";
15743 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15745 CharacterDatabase.Execute(ss.str().c_str());
15748 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15750 std::ostringstream ss2;
15751 ss2<<"UPDATE characters SET data='";
15752 int i=0;
15753 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15755 ss2<<tokens[i]<<" ";
15757 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15759 return CharacterDatabase.Execute(ss2.str().c_str());
15762 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15764 char buf[11];
15765 snprintf(buf,11,"%u",value);
15767 if(index >= tokens.size())
15768 return;
15770 tokens[index] = buf;
15773 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15775 Tokens tokens;
15776 if(!LoadValuesArrayFromDB(tokens,guid))
15777 return;
15779 if(index >= tokens.size())
15780 return;
15782 char buf[11];
15783 snprintf(buf,11,"%u",value);
15784 tokens[index] = buf;
15786 SaveValuesArrayInDB(tokens,guid);
15789 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15791 uint32 temp;
15792 memcpy(&temp, &value, sizeof(value));
15793 Player::SetUInt32ValueInDB(index, temp, guid);
15796 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15798 Tokens tokens;
15799 if(!LoadValuesArrayFromDB(tokens, guid))
15800 return;
15802 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15803 uint8 race = unit_bytes0 & 0xFF;
15804 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15806 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15807 if(!info)
15808 return;
15810 unit_bytes0 &= ~(0xFF << 16);
15811 unit_bytes0 |= (gender << 16);
15812 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15814 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15815 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15817 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15819 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15820 player_bytes2 &= ~0xFF;
15821 player_bytes2 |= facialHair;
15822 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15824 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15825 player_bytes3 &= ~0xFF;
15826 player_bytes3 |= gender;
15827 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15829 SaveValuesArrayInDB(tokens, guid);
15832 void Player::SendAttackSwingNotStanding()
15834 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15835 GetSession()->SendPacket( &data );
15838 void Player::SendAttackSwingDeadTarget()
15840 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15841 GetSession()->SendPacket( &data );
15844 void Player::SendAttackSwingCantAttack()
15846 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15847 GetSession()->SendPacket( &data );
15850 void Player::SendAttackSwingCancelAttack()
15852 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15853 GetSession()->SendPacket( &data );
15856 void Player::SendAttackSwingBadFacingAttack()
15858 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15859 GetSession()->SendPacket( &data );
15862 void Player::SendAutoRepeatCancel()
15864 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15865 data.append(GetPackGUID()); // may be it's target guid
15866 GetSession()->SendPacket( &data );
15869 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15871 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15872 data << Area;
15873 data << Experience;
15874 GetSession()->SendPacket(&data);
15877 void Player::SendDungeonDifficulty(bool IsInGroup)
15879 uint8 val = 0x00000001;
15880 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15881 data << (uint32)GetDifficulty();
15882 data << uint32(val);
15883 data << uint32(IsInGroup);
15884 GetSession()->SendPacket(&data);
15887 void Player::SendResetFailedNotify(uint32 mapid)
15889 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15890 data << uint32(mapid);
15891 GetSession()->SendPacket(&data);
15894 /// Reset all solo instances and optionally send a message on success for each
15895 void Player::ResetInstances(uint8 method)
15897 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15899 // we assume that when the difficulty changes, all instances that can be reset will be
15900 uint8 dif = GetDifficulty();
15902 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15904 InstanceSave *p = itr->second.save;
15905 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15906 if(!entry || !p->CanReset())
15908 ++itr;
15909 continue;
15912 if(method == INSTANCE_RESET_ALL)
15914 // the "reset all instances" method can only reset normal maps
15915 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15917 ++itr;
15918 continue;
15922 // if the map is loaded, reset it
15923 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15924 if(map && map->IsDungeon())
15925 ((InstanceMap*)map)->Reset(method);
15927 // since this is a solo instance there should not be any players inside
15928 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15929 SendResetInstanceSuccess(p->GetMapId());
15931 p->DeleteFromDB();
15932 m_boundInstances[dif].erase(itr++);
15934 // the following should remove the instance save from the manager and delete it as well
15935 p->RemovePlayer(this);
15939 void Player::SendResetInstanceSuccess(uint32 MapId)
15941 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15942 data << MapId;
15943 GetSession()->SendPacket(&data);
15946 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15948 // TODO: find what other fail reasons there are besides players in the instance
15949 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15950 data << reason;
15951 data << MapId;
15952 GetSession()->SendPacket(&data);
15955 /*********************************************************/
15956 /*** Update timers ***/
15957 /*********************************************************/
15959 ///checks the 15 afk reports per 5 minutes limit
15960 void Player::UpdateAfkReport(time_t currTime)
15962 if(m_bgAfkReportedTimer <= currTime)
15964 m_bgAfkReportedCount = 0;
15965 m_bgAfkReportedTimer = currTime+5*MINUTE;
15969 void Player::UpdateContestedPvP(uint32 diff)
15971 if(!m_contestedPvPTimer||isInCombat())
15972 return;
15973 if(m_contestedPvPTimer <= diff)
15975 ResetContestedPvP();
15977 else
15978 m_contestedPvPTimer -= diff;
15981 void Player::UpdatePvPFlag(time_t currTime)
15983 if(!IsPvP())
15984 return;
15985 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15986 return;
15988 UpdatePvP(false);
15991 void Player::UpdateDuelFlag(time_t currTime)
15993 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15994 return;
15996 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15997 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15999 duel->startTimer = 0;
16000 duel->startTime = currTime;
16001 duel->opponent->duel->startTimer = 0;
16002 duel->opponent->duel->startTime = currTime;
16005 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16007 if(!pet)
16008 pet = GetPet();
16010 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16012 //returning of reagents only for players, so best done here
16013 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16014 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16016 if(spellInfo)
16018 for(uint32 i = 0; i < 7; ++i)
16020 if(spellInfo->Reagent[i] > 0)
16022 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16023 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16024 if( msg == EQUIP_ERR_OK )
16026 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16027 if(IsInWorld())
16028 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16033 m_temporaryUnsummonedPetNumber = 0;
16036 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16037 return;
16039 // only if current pet in slot
16040 switch(pet->getPetType())
16042 case MINI_PET:
16043 m_miniPet = 0;
16044 break;
16045 case GUARDIAN_PET:
16046 m_guardianPets.erase(pet->GetGUID());
16047 break;
16048 default:
16049 if(GetPetGUID() == pet->GetGUID())
16050 SetPet(NULL);
16051 break;
16054 pet->CombatStop();
16056 if(returnreagent)
16058 switch(pet->GetEntry())
16060 //warlock pets except imp are removed(?) when logging out
16061 case 1860:
16062 case 1863:
16063 case 417:
16064 case 17252:
16065 mode = PET_SAVE_NOT_IN_SLOT;
16066 break;
16070 pet->SavePetToDB(mode);
16072 pet->CleanupsBeforeDelete();
16073 pet->AddObjectToRemoveList();
16074 pet->m_removed = true;
16076 if(pet->isControlled())
16078 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16079 data << uint64(0);
16080 data << uint32(0);
16081 GetSession()->SendPacket(&data);
16083 if(GetGroup())
16084 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16088 void Player::RemoveMiniPet()
16090 if(Pet* pet = GetMiniPet())
16092 pet->Remove(PET_SAVE_AS_DELETED);
16093 m_miniPet = 0;
16097 Pet* Player::GetMiniPet()
16099 if(!m_miniPet)
16100 return NULL;
16101 return ObjectAccessor::GetPet(m_miniPet);
16104 void Player::RemoveGuardians()
16106 while(!m_guardianPets.empty())
16108 uint64 guid = *m_guardianPets.begin();
16109 if(Pet* pet = ObjectAccessor::GetPet(guid))
16110 pet->Remove(PET_SAVE_AS_DELETED);
16112 m_guardianPets.erase(guid);
16116 bool Player::HasGuardianWithEntry(uint32 entry)
16118 // pet guid middle part is entry (and creature also)
16119 // and in guardian list must be guardians with same entry _always_
16120 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16121 if(GUID_ENPART(*itr)==entry)
16122 return true;
16124 return false;
16127 void Player::Uncharm()
16129 Unit* charm = GetCharm();
16130 if(!charm)
16131 return;
16133 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16134 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16137 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16139 *data << (uint8)msgtype;
16140 *data << (uint32)language;
16141 *data << (uint64)GetGUID();
16142 *data << (uint32)language; //language 2.1.0 ?
16143 *data << (uint64)GetGUID();
16144 *data << (uint32)(text.length()+1);
16145 *data << text;
16146 *data << (uint8)chatTag();
16149 void Player::Say(const std::string& text, const uint32 language)
16151 WorldPacket data(SMSG_MESSAGECHAT, 200);
16152 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16153 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16156 void Player::Yell(const std::string& text, const uint32 language)
16158 WorldPacket data(SMSG_MESSAGECHAT, 200);
16159 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16160 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16163 void Player::TextEmote(const std::string& text)
16165 WorldPacket data(SMSG_MESSAGECHAT, 200);
16166 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16167 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16170 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16172 if (language != LANG_ADDON) // if not addon data
16173 language = LANG_UNIVERSAL; // whispers should always be readable
16175 Player *rPlayer = objmgr.GetPlayer(receiver);
16177 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16178 if(!rPlayer->isDND() || isGameMaster())
16180 WorldPacket data(SMSG_MESSAGECHAT, 200);
16181 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16182 rPlayer->GetSession()->SendPacket(&data);
16184 data.Initialize(SMSG_MESSAGECHAT, 200);
16185 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16186 GetSession()->SendPacket(&data);
16188 else
16190 // announce to player that player he is whispering to is dnd and cannot receive his message
16191 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16194 if(!isAcceptWhispers())
16196 SetAcceptWhispers(true);
16197 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16200 // announce to player that player he is whispering to is afk
16201 if(rPlayer->isAFK())
16202 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16204 // if player whisper someone, auto turn of dnd to be able to receive an answer
16205 if(isDND() && !rPlayer->isGameMaster())
16206 ToggleDND();
16209 void Player::PetSpellInitialize()
16211 Pet* pet = GetPet();
16213 if(!pet)
16214 return;
16216 sLog.outDebug("Pet Spells Groups");
16218 CharmInfo *charmInfo = pet->GetCharmInfo();
16220 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16221 data << uint64(pet->GetGUID());
16222 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16223 data << uint32(0);
16224 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16226 // action bar loop
16227 for(uint32 i = 0; i < 10; i++)
16229 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16232 size_t spellsCountPos = data.wpos();
16234 // spells count
16235 uint8 addlist = 0;
16236 data << uint8(addlist); // placeholder
16238 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16240 // spells loop
16241 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16243 if(itr->second->state == PETSPELL_REMOVED)
16244 continue;
16246 data << uint16(itr->first);
16247 data << uint16(itr->second->active); // pet spell active state isn't boolean
16248 ++addlist;
16252 data.put<uint8>(spellsCountPos, addlist);
16254 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16255 data << uint8(cooldownsCount);
16257 time_t curTime = time(NULL);
16259 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16261 time_t cooldown = 0;
16263 if(itr->second > curTime)
16264 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16266 data << uint16(itr->first); // spellid
16267 data << uint16(0); // spell category?
16268 data << uint32(itr->second); // cooldown
16269 data << uint32(0); // category cooldown
16272 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16274 time_t cooldown = 0;
16276 if(itr->second > curTime)
16277 cooldown = (itr->second - curTime) * IN_MILISECONDS;
16279 data << uint16(itr->first); // spellid
16280 data << uint16(0); // spell category?
16281 data << uint32(0); // cooldown
16282 data << uint32(itr->second); // category cooldown
16285 GetSession()->SendPacket(&data);
16288 void Player::PossessSpellInitialize()
16290 Unit* charm = GetCharm();
16292 if(!charm)
16293 return;
16295 CharmInfo *charmInfo = charm->GetCharmInfo();
16297 if(!charmInfo)
16299 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16300 return;
16303 uint8 addlist = 0;
16304 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16306 //16
16307 data << uint64(charm->GetGUID());
16308 data << uint32(0x00000000);
16309 data << uint32(0);
16310 data << uint32(0);
16312 for(uint32 i = 0; i < 10; i++) //40
16314 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16317 data << uint8(addlist); //1
16319 uint8 count = 0;
16320 data << uint8(count); // cooldowns count
16322 GetSession()->SendPacket(&data);
16325 void Player::CharmSpellInitialize()
16327 Unit* charm = GetCharm();
16329 if(!charm)
16330 return;
16332 CharmInfo *charmInfo = charm->GetCharmInfo();
16333 if(!charmInfo)
16335 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16336 return;
16339 uint8 addlist = 0;
16341 if(charm->GetTypeId() != TYPEID_PLAYER)
16343 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16345 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16347 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16349 if(charmInfo->GetCharmSpell(i)->spellId)
16350 ++addlist;
16355 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16357 data << uint64(charm->GetGUID());
16358 data << uint32(0x00000000);
16359 data << uint32(0);
16360 if(charm->GetTypeId() != TYPEID_PLAYER)
16361 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16362 else
16363 data << uint8(0) << uint8(0);
16364 data << uint16(0);
16366 for(uint32 i = 0; i < 10; i++) //40
16368 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16371 data << uint8(addlist); //1
16373 if(addlist)
16375 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16377 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16378 if(cspell->spellId)
16380 data << uint16(cspell->spellId);
16381 data << uint16(cspell->active);
16386 uint8 count = 0;
16387 data << uint8(count); // cooldowns count
16389 GetSession()->SendPacket(&data);
16392 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16394 if (!mod || !spellInfo)
16395 return false;
16397 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16399 // prevent apply to any spell except spell that trigger expire
16400 if(spell)
16402 if(mod->lastAffected != spell)
16403 return false;
16405 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16406 return false;
16409 return spellmgr.IsAffectedByMod(spellInfo, mod);
16412 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16414 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16416 for(int eff=0;eff<96;++eff)
16418 uint64 _mask = 0;
16419 uint64 _mask2= 0;
16420 if (eff<64) _mask = uint64(1) << (eff- 0);
16421 else _mask2= uint64(1) << (eff-64);
16422 if ( mod->mask & _mask || mod->mask2 & _mask2)
16424 int32 val = 0;
16425 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16427 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16428 val += (*itr)->value;
16430 val += apply ? mod->value : -(mod->value);
16431 WorldPacket data(Opcode, (1+1+4));
16432 data << uint8(eff);
16433 data << uint8(mod->op);
16434 data << int32(val);
16435 SendDirectMessage(&data);
16439 if (apply)
16440 m_spellMods[mod->op].push_back(mod);
16441 else
16443 if (mod->charges == -1)
16444 --m_SpellModRemoveCount;
16445 m_spellMods[mod->op].remove(mod);
16446 delete mod;
16450 void Player::RemoveSpellMods(Spell const* spell)
16452 if(!spell || (m_SpellModRemoveCount == 0))
16453 return;
16455 for(int i=0;i<MAX_SPELLMOD;++i)
16457 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16459 SpellModifier *mod = *itr;
16460 ++itr;
16462 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16464 RemoveAurasDueToSpell(mod->spellId);
16465 if (m_spellMods[i].empty())
16466 break;
16467 else
16468 itr = m_spellMods[i].begin();
16474 // send Proficiency
16475 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16477 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16478 data << pr1 << pr2;
16479 GetSession()->SendPacket (&data);
16482 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16484 QueryResult *result = NULL;
16485 if(type==10)
16486 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16487 else
16488 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16489 if(result)
16491 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.
16492 { // and SendPetitionQueryOpcode reads data from the DB
16493 Field *fields = result->Fetch();
16494 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16495 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16497 // send update if charter owner in game
16498 Player* owner = objmgr.GetPlayer(ownerguid);
16499 if(owner)
16500 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16502 } while ( result->NextRow() );
16504 delete result;
16506 if(type==10)
16507 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16508 else
16509 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16512 CharacterDatabase.BeginTransaction();
16513 if(type == 10)
16515 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16516 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16518 else
16520 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16521 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16523 CharacterDatabase.CommitTransaction();
16526 void Player::LeaveAllArenaTeams(uint64 guid)
16528 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));
16529 if(!result)
16530 return;
16534 Field *fields = result->Fetch();
16535 uint32 at_id = fields[0].GetUInt32();
16536 if(at_id != 0)
16538 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16539 if(at)
16540 at->DelMember(guid);
16542 } while (result->NextRow());
16544 delete result;
16547 void Player::SetRestBonus (float rest_bonus_new)
16549 // Prevent resting on max level
16550 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16551 rest_bonus_new = 0;
16553 if(rest_bonus_new < 0)
16554 rest_bonus_new = 0;
16556 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16558 if(rest_bonus_new > rest_bonus_max)
16559 m_rest_bonus = rest_bonus_max;
16560 else
16561 m_rest_bonus = rest_bonus_new;
16563 // update data for client
16564 if(m_rest_bonus>10)
16565 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16566 else if(m_rest_bonus<=1)
16567 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16569 //RestTickUpdate
16570 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16573 void Player::HandleStealthedUnitsDetection()
16575 std::list<Unit*> stealthedUnits;
16577 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16578 Cell cell(p);
16579 cell.data.Part.reserved = ALL_DISTRICT;
16580 cell.SetNoCreate();
16582 MaNGOS::AnyStealthedCheck u_check;
16583 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16585 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16586 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16588 CellLock<GridReadGuard> cell_lock(cell, p);
16589 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16590 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16592 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16594 if((*i)==this)
16596 i = stealthedUnits.erase(i);
16597 continue;
16600 if ((*i)->isVisibleForOrDetect(this,true))
16603 (*i)->SendUpdateToPlayer(this);
16604 m_clientGUIDs.insert((*i)->GetGUID());
16606 #ifdef MANGOS_DEBUG
16607 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16608 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16609 #endif
16611 // target aura duration for caster show only if target exist at caster client
16612 // send data at target visibility change (adding to client)
16613 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16614 SendAurasForTarget(*i);
16616 i = stealthedUnits.erase(i);
16617 continue;
16620 ++i;
16624 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16626 if(nodes.size() < 2)
16627 return false;
16629 // not let cheating with start flight mounted
16630 if(IsMounted())
16632 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16633 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16634 GetSession()->SendPacket(&data);
16635 return false;
16638 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16640 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16641 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16642 GetSession()->SendPacket(&data);
16643 return false;
16646 // 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
16647 if(GetSession()->isLogingOut() ||
16648 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16649 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16650 IsNonMeleeSpellCasted(false) ||
16651 isInCombat())
16653 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16654 data << uint32(ERR_TAXIPLAYERBUSY);
16655 GetSession()->SendPacket(&data);
16656 return false;
16659 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16660 return false;
16662 uint32 sourcenode = nodes[0];
16664 // starting node too far away (cheat?)
16665 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16666 if( !node || node->map_id != GetMapId() ||
16667 (node->x - GetPositionX())*(node->x - GetPositionX())+
16668 (node->y - GetPositionY())*(node->y - GetPositionY())+
16669 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16670 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16672 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16673 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16674 GetSession()->SendPacket(&data);
16675 return false;
16678 // Prepare to flight start now
16680 // stop combat at start taxi flight if any
16681 CombatStop();
16683 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16684 TradeCancel(true);
16686 // clean not finished taxi path if any
16687 m_taxi.ClearTaxiDestinations();
16689 // 0 element current node
16690 m_taxi.AddTaxiDestination(sourcenode);
16692 // fill destinations path tail
16693 uint32 sourcepath = 0;
16694 uint32 totalcost = 0;
16696 uint32 prevnode = sourcenode;
16697 uint32 lastnode = 0;
16699 for(uint32 i = 1; i < nodes.size(); ++i)
16701 uint32 path, cost;
16703 lastnode = nodes[i];
16704 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16706 if(!path)
16708 m_taxi.ClearTaxiDestinations();
16709 return false;
16712 totalcost += cost;
16714 if(prevnode == sourcenode)
16715 sourcepath = path;
16717 m_taxi.AddTaxiDestination(lastnode);
16719 prevnode = lastnode;
16722 if(!mount_id) // if not provide then attempt use default.
16723 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16725 if (mount_id == 0 || sourcepath == 0)
16727 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16728 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16729 GetSession()->SendPacket(&data);
16730 m_taxi.ClearTaxiDestinations();
16731 return false;
16734 uint32 money = GetMoney();
16736 if(npc)
16738 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16741 if(money < totalcost)
16743 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16744 data << uint32(ERR_TAXINOTENOUGHMONEY);
16745 GetSession()->SendPacket(&data);
16746 m_taxi.ClearTaxiDestinations();
16747 return false;
16750 //Checks and preparations done, DO FLIGHT
16751 ModifyMoney(-(int32)totalcost);
16752 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16754 // prevent stealth flight
16755 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16757 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16758 data << uint32(ERR_TAXIOK);
16759 GetSession()->SendPacket(&data);
16761 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16763 GetSession()->SendDoFlight(mount_id, sourcepath);
16765 return true;
16768 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16770 // last check 2.0.10
16771 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16772 data << GetGUID();
16773 data << uint8(0x0); // flags (0x1, 0x2)
16774 time_t curTime = time(NULL);
16775 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16777 if (itr->second->state == PLAYERSPELL_REMOVED)
16778 continue;
16779 uint32 unSpellId = itr->first;
16780 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16781 if (!spellInfo)
16783 ASSERT(spellInfo);
16784 continue;
16787 // Not send cooldown for this spells
16788 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16789 continue;
16791 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16793 data << unSpellId;
16794 data << unTimeMs; // in m.secs
16795 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16798 GetSession()->SendPacket(&data);
16801 void Player::InitDataForForm(bool reapplyMods)
16803 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16804 if(ssEntry && ssEntry->attackSpeed)
16806 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16807 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16808 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16810 else
16811 SetRegularAttackTime();
16813 switch(m_form)
16815 case FORM_CAT:
16817 if(getPowerType()!=POWER_ENERGY)
16818 setPowerType(POWER_ENERGY);
16819 break;
16821 case FORM_BEAR:
16822 case FORM_DIREBEAR:
16824 if(getPowerType()!=POWER_RAGE)
16825 setPowerType(POWER_RAGE);
16826 break;
16828 default: // 0, for example
16830 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16831 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16832 setPowerType(Powers(cEntry->powerType));
16833 break;
16837 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16838 if (!reapplyMods)
16839 UpdateEquipSpellsAtFormChange();
16841 UpdateAttackPowerAndDamage();
16842 UpdateAttackPowerAndDamage(true);
16845 // Return true is the bought item has a max count to force refresh of window by caller
16846 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16848 // cheating attempt
16849 if(count < 1) count = 1;
16851 if(!isAlive())
16852 return false;
16854 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16855 if( !pProto )
16857 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16858 return false;
16861 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16862 if (!pCreature)
16864 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16865 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16866 return false;
16869 VendorItemData const* vItems = pCreature->GetVendorItems();
16870 if(!vItems || vItems->Empty())
16872 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16873 return false;
16876 size_t vendor_slot = vItems->FindItemSlot(item);
16877 if(vendor_slot >= vItems->GetItemCount())
16879 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16880 return false;
16883 VendorItem const* crItem = vItems->m_items[vendor_slot];
16885 // check current item amount if it limited
16886 if( crItem->maxcount != 0 )
16888 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16890 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16891 return false;
16895 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16897 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16898 return false;
16901 if(crItem->ExtendedCost)
16903 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16904 if(!iece)
16906 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16907 return false;
16910 // honor points price
16911 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16913 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16914 return false;
16917 // arena points price
16918 if(GetArenaPoints() < (iece->reqarenapoints * count))
16920 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16921 return false;
16924 // item base price
16925 for (uint8 i = 0; i < 5; ++i)
16927 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16929 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16930 return false;
16934 // check for personal arena rating requirement
16935 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16937 // probably not the proper equip err
16938 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16939 return false;
16943 uint32 price = pProto->BuyPrice * count;
16945 // reputation discount
16946 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16948 if( GetMoney() < price )
16950 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16951 return false;
16954 uint8 bag = 0; // init for case invalid bagGUID
16956 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16958 Bag *pBag;
16959 if( bagguid == GetGUID() )
16961 bag = INVENTORY_SLOT_BAG_0;
16963 else
16965 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16967 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16968 if( pBag )
16970 if( bagguid == pBag->GetGUID() )
16972 bag = i;
16973 break;
16980 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16982 ItemPosCountVec dest;
16983 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16984 if( msg != EQUIP_ERR_OK )
16986 SendEquipError( msg, NULL, NULL );
16987 return false;
16990 ModifyMoney( -(int32)price );
16991 if(crItem->ExtendedCost) // case for new honor system
16993 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16994 if(iece->reqhonorpoints)
16995 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16996 if(iece->reqarenapoints)
16997 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16998 for (uint8 i = 0; i < 5; ++i)
17000 if(iece->reqitem[i])
17001 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17005 if(Item *it = StoreNewItem( dest, item, true ))
17007 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17009 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17010 data << pCreature->GetGUID();
17011 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17012 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17013 data << (uint32)count;
17014 GetSession()->SendPacket(&data);
17016 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17019 else if( IsEquipmentPos( bag, slot ) )
17021 if(pProto->BuyCount * count != 1)
17023 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17024 return false;
17027 uint16 dest;
17028 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17029 if( msg != EQUIP_ERR_OK )
17031 SendEquipError( msg, NULL, NULL );
17032 return false;
17035 ModifyMoney( -(int32)price );
17036 if(crItem->ExtendedCost) // case for new honor system
17038 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17039 if(iece->reqhonorpoints)
17040 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17041 if(iece->reqarenapoints)
17042 ModifyArenaPoints( - int32(iece->reqarenapoints));
17043 for (uint8 i = 0; i < 5; ++i)
17045 if(iece->reqitem[i])
17046 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17050 if(Item *it = EquipNewItem( dest, item, true ))
17052 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17054 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17055 data << pCreature->GetGUID();
17056 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17057 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17058 data << (uint32)count;
17059 GetSession()->SendPacket(&data);
17061 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17063 AutoUnequipOffhandIfNeed();
17066 else
17068 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17069 return false;
17072 return crItem->maxcount!=0;
17075 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17077 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17078 // the personal rating of the arena team must match the required limit as well
17079 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17080 uint32 max_personal_rating = 0;
17081 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17083 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17085 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17086 uint32 t_rating = at->GetRating();
17087 p_rating = p_rating<t_rating? p_rating : t_rating;
17088 if(max_personal_rating < p_rating)
17089 max_personal_rating = p_rating;
17092 return max_personal_rating;
17095 void Player::UpdateHomebindTime(uint32 time)
17097 // GMs never get homebind timer online
17098 if (m_InstanceValid || isGameMaster())
17100 if(m_HomebindTimer) // instance valid, but timer not reset
17102 // hide reminder
17103 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17104 data << uint32(0);
17105 data << uint32(0);
17106 GetSession()->SendPacket(&data);
17108 // instance is valid, reset homebind timer
17109 m_HomebindTimer = 0;
17111 else if (m_HomebindTimer > 0)
17113 if (time >= m_HomebindTimer)
17115 // teleport to homebind location
17116 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17118 else
17119 m_HomebindTimer -= time;
17121 else
17123 // instance is invalid, start homebind timer
17124 m_HomebindTimer = 60000;
17125 // send message to player
17126 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17127 data << m_HomebindTimer;
17128 data << uint32(1);
17129 GetSession()->SendPacket(&data);
17130 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17134 void Player::UpdatePvP(bool state, bool ovrride)
17136 if(!state || ovrride)
17138 SetPvP(state);
17139 if(Pet* pet = GetPet())
17140 pet->SetPvP(state);
17141 if(Unit* charmed = GetCharm())
17142 charmed->SetPvP(state);
17144 pvpInfo.endTimer = 0;
17146 else
17148 if(pvpInfo.endTimer != 0)
17149 pvpInfo.endTimer = time(NULL);
17150 else
17152 SetPvP(state);
17154 if(Pet* pet = GetPet())
17155 pet->SetPvP(state);
17156 if(Unit* charmed = GetCharm())
17157 charmed->SetPvP(state);
17162 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17164 // init cooldown values
17165 uint32 cat = 0;
17166 int32 rec = -1;
17167 int32 catrec = -1;
17169 // some special item spells without correct cooldown in SpellInfo
17170 // cooldown information stored in item prototype
17171 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17173 if(itemId)
17175 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17177 for(int idx = 0; idx < 5; ++idx)
17179 if(proto->Spells[idx].SpellId == spellInfo->Id)
17181 cat = proto->Spells[idx].SpellCategory;
17182 rec = proto->Spells[idx].SpellCooldown;
17183 catrec = proto->Spells[idx].SpellCategoryCooldown;
17184 break;
17190 // if no cooldown found above then base at DBC data
17191 if(rec < 0 && catrec < 0)
17193 cat = spellInfo->Category;
17194 rec = spellInfo->RecoveryTime;
17195 catrec = spellInfo->CategoryRecoveryTime;
17198 time_t curTime = time(NULL);
17200 time_t catrecTime;
17201 time_t recTime;
17203 // overwrite time for selected category
17204 if(infinityCooldown)
17206 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17207 // but not allow ignore until reset or re-login
17208 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17209 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17211 else
17213 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17214 // prevent 0 cooldowns set by another way
17215 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17216 rec = GetAttackTime(RANGED_ATTACK);
17218 // Now we have cooldown data (if found any), time to apply mods
17219 if(rec > 0)
17220 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17222 if(catrec > 0)
17223 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17225 // replace negative cooldowns by 0
17226 if (rec < 0) rec = 0;
17227 if (catrec < 0) catrec = 0;
17229 // no cooldown after applying spell mods
17230 if( rec == 0 && catrec == 0)
17231 return;
17233 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17234 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17237 // self spell cooldown
17238 if(recTime > 0)
17239 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17241 // category spells
17242 if (cat && catrec > 0)
17244 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17245 if(i_scstore != sSpellCategoryStore.end())
17247 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17249 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17250 continue;
17252 AddSpellCooldown(*i_scset, itemId, catrecTime);
17258 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17260 SpellCooldown sc;
17261 sc.end = end_time;
17262 sc.itemid = itemid;
17263 m_spellCooldowns[spellid] = sc;
17266 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17268 // start cooldowns at server side, if any
17269 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17271 // Send activate cooldown timer (possible 0) at client side
17272 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17273 data << spellInfo->Id;
17274 data << GetGUID();
17275 SendDirectMessage(&data);
17278 void Player::UpdatePotionCooldown(Spell* spell)
17280 // no potion used i combat or still in combat
17281 if(!m_lastPotionId || isInCombat())
17282 return;
17284 // Call not from spell cast, send cooldown event for item spells if no in combat
17285 if(!spell)
17287 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17288 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17289 for(int idx = 0; idx < 5; ++idx)
17290 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17291 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17292 SendCooldownEvent(spellInfo,m_lastPotionId);
17294 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17295 else
17296 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17298 m_lastPotionId = 0;
17301 //slot to be excluded while counting
17302 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17304 if(!enchantmentcondition)
17305 return true;
17307 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17309 if(!Condition)
17310 return true;
17312 uint8 curcount[4] = {0, 0, 0, 0};
17314 //counting current equipped gem colors
17315 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17317 if(i == slot)
17318 continue;
17319 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17320 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17322 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17324 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17325 if(!enchant_id)
17326 continue;
17328 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17329 if(!enchantEntry)
17330 continue;
17332 uint32 gemid = enchantEntry->GemID;
17333 if(!gemid)
17334 continue;
17336 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17337 if(!gemProto)
17338 continue;
17340 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17341 if(!gemProperty)
17342 continue;
17344 uint8 GemColor = gemProperty->color;
17346 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17348 if(tmpcolormask & GemColor)
17349 ++curcount[b];
17355 bool activate = true;
17357 for(int i = 0; i < 5; i++)
17359 if(!Condition->Color[i])
17360 continue;
17362 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17364 // if have <CompareColor> use them as count, else use <value> from Condition
17365 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17367 switch(Condition->Comparator[i])
17369 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17370 activate &= (_cur_gem < _cmp_gem) ? true : false;
17371 break;
17372 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17373 activate &= (_cur_gem > _cmp_gem) ? true : false;
17374 break;
17375 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17376 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17377 break;
17381 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");
17383 return activate;
17386 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17388 //cycle all equipped items
17389 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17391 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17392 if(slot == exceptslot)
17393 continue;
17395 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17397 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17398 continue;
17400 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17402 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17403 if(!enchant_id)
17404 continue;
17406 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17407 if(!enchantEntry)
17408 continue;
17410 uint32 condition = enchantEntry->EnchantmentCondition;
17411 if(condition)
17413 //was enchant active with/without item?
17414 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17415 //should it now be?
17416 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17418 // ignore item gem conditions
17419 //if state changed, (dis)apply enchant
17420 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17427 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17428 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17430 //cycle all equipped items
17431 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17433 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17434 if(slot == exceptslot)
17435 continue;
17437 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17439 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17440 continue;
17442 //cycle all (gem)enchants
17443 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17445 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17446 if(!enchant_id) //if no enchant go to next enchant(slot)
17447 continue;
17449 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17450 if(!enchantEntry)
17451 continue;
17453 //only metagems to be (de)activated, so only enchants with condition
17454 uint32 condition = enchantEntry->EnchantmentCondition;
17455 if(condition)
17456 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17461 void Player::LeaveBattleground(bool teleportToEntryPoint)
17463 if(BattleGround *bg = GetBattleGround())
17465 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17467 // call after remove to be sure that player resurrected for correct cast
17468 if( bg->isBattleGround() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17470 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17471 CastSpell(this, 26013, true); // Deserter
17476 bool Player::CanJoinToBattleground() const
17478 // check Deserter debuff
17479 if(GetDummyAura(26013))
17480 return false;
17482 return true;
17485 bool Player::CanReportAfkDueToLimit()
17487 // a player can complain about 15 people per 5 minutes
17488 if(m_bgAfkReportedCount >= 15)
17489 return false;
17490 ++m_bgAfkReportedCount;
17491 return true;
17494 ///This player has been blamed to be inactive in a battleground
17495 void Player::ReportedAfkBy(Player* reporter)
17497 BattleGround *bg = GetBattleGround();
17498 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17499 return;
17501 // check if player has 'Idle' or 'Inactive' debuff
17502 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17504 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17505 // 3 players have to complain to apply debuff
17506 if(m_bgAfkReporter.size() >= 3)
17508 // cast 'Idle' spell
17509 CastSpell(this, 43680, true);
17510 m_bgAfkReporter.clear();
17515 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17517 // gamemaster in GM mode see all, including ghosts
17518 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17519 return true;
17521 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17522 if (InBattleGround())
17524 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17525 return false;
17526 return true;
17529 // Live player see live player or dead player with not realized corpse
17530 if(pl->isAlive() || pl->m_deathTimer > 0)
17532 return isAlive() || m_deathTimer > 0;
17535 // Ghost see other friendly ghosts, that's for sure
17536 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17537 return true;
17539 // Dead player see live players near own corpse
17540 if(isAlive())
17542 Corpse *corpse = pl->GetCorpse();
17543 if(corpse)
17545 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17546 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17547 return true;
17551 // and not see any other
17552 return false;
17555 bool Player::IsVisibleGloballyFor( Player* u ) const
17557 if(!u)
17558 return false;
17560 // Always can see self
17561 if (u==this)
17562 return true;
17564 // Visible units, always are visible for all players
17565 if (GetVisibility() == VISIBILITY_ON)
17566 return true;
17568 // GMs are visible for higher gms (or players are visible for gms)
17569 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17570 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17572 // non faction visibility non-breakable for non-GMs
17573 if (GetVisibility() == VISIBILITY_OFF)
17574 return false;
17576 // non-gm stealth/invisibility not hide from global player lists
17577 return true;
17580 void Player::UpdateVisibilityOf(WorldObject* target)
17582 if(HaveAtClient(target))
17584 if(!target->isVisibleForInState(this,true))
17586 target->DestroyForPlayer(this);
17587 m_clientGUIDs.erase(target->GetGUID());
17589 #ifdef MANGOS_DEBUG
17590 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17591 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17592 #endif
17595 else
17597 if(target->isVisibleForInState(this,false))
17599 target->SendUpdateToPlayer(this);
17600 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17601 m_clientGUIDs.insert(target->GetGUID());
17603 #ifdef MANGOS_DEBUG
17604 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17605 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17606 #endif
17608 // target aura duration for caster show only if target exist at caster client
17609 // send data at target visibility change (adding to client)
17610 if(target!=this && target->isType(TYPEMASK_UNIT))
17611 SendAurasForTarget((Unit*)target);
17613 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17614 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17619 template<class T>
17620 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17622 s64.insert(target->GetGUID());
17625 template<>
17626 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17628 if(!target->IsTransport())
17629 s64.insert(target->GetGUID());
17632 template<class T>
17633 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17635 if(HaveAtClient(target))
17637 if(!target->isVisibleForInState(this,true))
17639 target->BuildOutOfRangeUpdateBlock(&data);
17640 m_clientGUIDs.erase(target->GetGUID());
17642 #ifdef MANGOS_DEBUG
17643 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17644 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));
17645 #endif
17648 else
17650 if(target->isVisibleForInState(this,false))
17652 visibleNow.insert(target);
17653 target->BuildUpdate(data_updates);
17654 target->BuildCreateUpdateBlockForPlayer(&data, this);
17655 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17657 #ifdef MANGOS_DEBUG
17658 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17659 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));
17660 #endif
17665 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17666 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17667 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17668 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17669 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17671 void Player::InitPrimaryProffesions()
17673 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17676 void Player::SendComboPoints()
17678 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17679 if (combotarget)
17681 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17682 data.append(combotarget->GetPackGUID());
17683 data << uint8(m_comboPoints);
17684 GetSession()->SendPacket(&data);
17688 void Player::AddComboPoints(Unit* target, int8 count)
17690 if(!count)
17691 return;
17693 // without combo points lost (duration checked in aura)
17694 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17696 if(target->GetGUID() == m_comboTarget)
17698 m_comboPoints += count;
17700 else
17702 if(m_comboTarget)
17703 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17704 target->RemoveComboPointHolder(GetGUIDLow());
17706 m_comboTarget = target->GetGUID();
17707 m_comboPoints = count;
17709 target->AddComboPointHolder(GetGUIDLow());
17712 if (m_comboPoints > 5) m_comboPoints = 5;
17713 if (m_comboPoints < 0) m_comboPoints = 0;
17715 SendComboPoints();
17718 void Player::ClearComboPoints()
17720 if(!m_comboTarget)
17721 return;
17723 // without combopoints lost (duration checked in aura)
17724 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17726 m_comboPoints = 0;
17728 SendComboPoints();
17730 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17731 target->RemoveComboPointHolder(GetGUIDLow());
17733 m_comboTarget = 0;
17736 void Player::SetGroup(Group *group, int8 subgroup)
17738 if(group == NULL)
17739 m_group.unlink();
17740 else
17742 // never use SetGroup without a subgroup unless you specify NULL for group
17743 assert(subgroup >= 0);
17744 m_group.link(group, this);
17745 m_group.setSubGroup((uint8)subgroup);
17749 void Player::SendInitialPacketsBeforeAddToMap()
17751 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17752 data << uint32(0); // unknown, may be rest state time or experience
17753 GetSession()->SendPacket(&data);
17755 // Homebind
17756 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17757 data << m_homebindX << m_homebindY << m_homebindZ;
17758 data << (uint32) m_homebindMapId;
17759 data << (uint32) m_homebindZoneId;
17760 GetSession()->SendPacket(&data);
17762 // SMSG_SET_PROFICIENCY
17763 // SMSG_UPDATE_AURA_DURATION
17765 // tutorial stuff
17766 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17767 for (int i = 0; i < 8; ++i)
17768 data << uint32( GetTutorialInt(i) );
17769 GetSession()->SendPacket(&data);
17771 SendInitialSpells();
17773 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17774 data << uint32(0); // count, for(count) uint32;
17775 GetSession()->SendPacket(&data);
17777 SendInitialActionButtons();
17778 m_reputationMgr.SendInitialReputations();
17779 m_achievementMgr.SendAllAchievementData();
17781 // update zone
17782 uint32 newzone, newarea;
17783 GetZoneAndAreaId(newzone,newarea);
17784 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17786 // SMSG_SET_AURA_SINGLE
17788 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17789 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17790 data << (float)0.01666667f; // game speed
17791 GetSession()->SendPacket( &data );
17793 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17794 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17795 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17797 m_mover = this;
17800 void Player::SendInitialPacketsAfterAddToMap()
17802 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17803 data << uint32(0x00000000); // on blizz it increments periodically
17804 GetSession()->SendPacket(&data);
17806 CastSpell(this, 836, true); // LOGINEFFECT
17808 // set some aura effects that send packet to player client after add player to map
17809 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17810 // same auras state lost at far teleport, send it one more time in this case also
17811 static const AuraType auratypes[] =
17813 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17814 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17815 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17817 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17819 Unit::AuraList const& auraList = GetAurasByType(*itr);
17820 if(!auraList.empty())
17821 auraList.front()->ApplyModifier(true,true);
17824 if(HasAuraType(SPELL_AURA_MOD_STUN))
17825 SetMovement(MOVE_ROOT);
17827 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17828 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17830 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17831 data.append(GetPackGUID());
17832 data << (uint32)2;
17833 SendMessageToSet(&data,true);
17836 SendAurasForTarget(this);
17837 SendEnchantmentDurations(); // must be after add to map
17838 SendItemDurations(); // must be after add to map
17841 void Player::SendUpdateToOutOfRangeGroupMembers()
17843 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17844 return;
17845 if(Group* group = GetGroup())
17846 group->UpdatePlayerOutOfRange(this);
17848 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17849 m_auraUpdateMask = 0;
17850 if(Pet *pet = GetPet())
17851 pet->ResetAuraUpdateMask();
17854 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17856 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17857 data << uint32(mapid);
17858 data << uint8(reason); // transfer abort reason
17859 switch(reason)
17861 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17862 case TRANSFER_ABORT_DIFFICULTY:
17863 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17864 data << uint8(arg);
17865 break;
17867 GetSession()->SendPacket(&data);
17870 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17872 // type of warning, based on the time remaining until reset
17873 uint32 type;
17874 if(time > 3600)
17875 type = RAID_INSTANCE_WELCOME;
17876 else if(time > 900 && time <= 3600)
17877 type = RAID_INSTANCE_WARNING_HOURS;
17878 else if(time > 300 && time <= 900)
17879 type = RAID_INSTANCE_WARNING_MIN;
17880 else
17881 type = RAID_INSTANCE_WARNING_MIN_SOON;
17882 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17883 data << uint32(type);
17884 data << uint32(mapid);
17885 data << uint32(time);
17886 GetSession()->SendPacket(&data);
17889 void Player::ApplyEquipCooldown( Item * pItem )
17891 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17893 _Spell const& spellData = pItem->GetProto()->Spells[i];
17895 // no spell
17896 if( !spellData.SpellId )
17897 continue;
17899 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17900 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17901 continue;
17903 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17905 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17906 data << pItem->GetGUID();
17907 data << uint32(spellData.SpellId);
17908 GetSession()->SendPacket(&data);
17912 void Player::resetSpells()
17914 // not need after this call
17915 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17917 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17918 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17921 // make full copy of map (spells removed and marked as deleted at another spell remove
17922 // and we can't use original map for safe iterative with visit each spell at loop end
17923 PlayerSpellMap smap = GetSpellMap();
17925 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17926 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17928 learnDefaultSpells();
17929 learnQuestRewardedSpells();
17932 void Player::learnDefaultSpells()
17934 // learn default race/class spells
17935 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17936 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
17938 uint32 tspell = *itr;
17939 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
17940 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
17941 addSpell(tspell,true,true,true,false);
17942 else // but send in normal spell in game learn case
17943 learnSpell(tspell,true);
17947 void Player::learnQuestRewardedSpells(Quest const* quest)
17949 uint32 spell_id = quest->GetRewSpellCast();
17951 // skip quests without rewarded spell
17952 if( !spell_id )
17953 return;
17955 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17956 if(!spellInfo)
17957 return;
17959 // check learned spells state
17960 bool found = false;
17961 for(int i=0; i < 3; ++i)
17963 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17965 found = true;
17966 break;
17970 // skip quests with not teaching spell or already known spell
17971 if(!found)
17972 return;
17974 // prevent learn non first rank unknown profession and second specialization for same profession)
17975 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17976 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17978 // not have first rank learned (unlearned prof?)
17979 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17980 if( !HasSpell(first_spell) )
17981 return;
17983 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17984 if(!learnedInfo)
17985 return;
17987 // specialization
17988 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17990 // search other specialization for same prof
17991 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17993 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17994 continue;
17996 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17997 if(!itrInfo)
17998 return;
18000 // compare only specializations
18001 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18002 continue;
18004 // compare same chain spells
18005 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18006 continue;
18008 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18009 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18010 return;
18015 CastSpell( this, spell_id, true);
18018 void Player::learnQuestRewardedSpells()
18020 // learn spells received from quest completing
18021 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18023 // skip no rewarded quests
18024 if(!itr->second.m_rewarded)
18025 continue;
18027 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18028 if( !quest )
18029 continue;
18031 learnQuestRewardedSpells(quest);
18035 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18037 uint32 raceMask = getRaceMask();
18038 uint32 classMask = getClassMask();
18039 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18041 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18042 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18043 continue;
18044 // Check race if set
18045 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18046 continue;
18047 // Check class if set
18048 if (pAbility->classmask && !(pAbility->classmask & classMask))
18049 continue;
18051 if (sSpellStore.LookupEntry(pAbility->spellId))
18053 // need unlearn spell
18054 if (skill_value < pAbility->req_skill_value)
18055 removeSpell(pAbility->spellId);
18056 // need learn
18057 else if (!IsInWorld())
18058 addSpell(pAbility->spellId,true,true,true,false);
18059 else
18060 learnSpell(pAbility->spellId,true);
18065 void Player::SendAurasForTarget(Unit *target)
18067 if(target->GetVisibleAuras()->empty()) // speedup things
18068 return;
18070 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18071 data.append(target->GetPackGUID());
18073 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18074 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18076 for(uint32 j = 0; j < 3; ++j)
18078 if(Aura *aura = target->GetAura(itr->second, j))
18080 data << uint8(aura->GetAuraSlot());
18081 data << uint32(aura->GetId());
18083 if(aura->GetId())
18085 uint8 auraFlags = aura->GetAuraFlags();
18086 // flags
18087 data << uint8(auraFlags);
18088 // level
18089 data << uint8(aura->GetAuraLevel());
18090 // charges
18091 data << uint8(aura->GetAuraCharges());
18093 if(!(auraFlags & AFLAG_NOT_CASTER))
18095 data << uint8(0); // packed GUID of someone (caster?)
18098 if(auraFlags & AFLAG_DURATION) // include aura duration
18100 data << uint32(aura->GetAuraMaxDuration());
18101 data << uint32(aura->GetAuraDuration());
18104 break;
18109 GetSession()->SendPacket(&data);
18112 void Player::SetDailyQuestStatus( uint32 quest_id )
18114 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18116 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18118 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18119 m_lastDailyQuestTime = time(NULL); // last daily quest time
18120 m_DailyQuestChanged = true;
18121 break;
18126 void Player::ResetDailyQuestStatus()
18128 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18129 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18131 // DB data deleted in caller
18132 m_DailyQuestChanged = false;
18133 m_lastDailyQuestTime = 0;
18136 BattleGround* Player::GetBattleGround() const
18138 if(GetBattleGroundId()==0)
18139 return NULL;
18141 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18144 bool Player::InArena() const
18146 BattleGround *bg = GetBattleGround();
18147 if(!bg || !bg->isArena())
18148 return false;
18150 return true;
18153 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18155 // get a template bg instead of running one
18156 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18157 if(!bg)
18158 return false;
18160 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18161 return false;
18163 return true;
18166 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18168 //returned to hardcoded version of this function, because there is no way to code it dynamic
18169 uint32 level = getLevel();
18170 if( bgTypeId == BATTLEGROUND_AV )
18171 level--;
18173 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18174 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18176 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18177 return QUEUE_ID_MAX_LEVEL_80;
18179 return BGQueueIdBasedOnLevel(queue_id);
18182 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18184 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18185 if(!vendor_faction || !vendor_faction->faction)
18186 return 1.0f;
18188 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18189 if(rank <= REP_NEUTRAL)
18190 return 1.0f;
18192 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18195 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18197 uint32 racemask = getRaceMask();
18198 uint32 classmask = getClassMask();
18200 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18201 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18202 if(lower==upper)
18203 return true;
18205 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18207 // skip wrong race skills
18208 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18209 continue;
18211 // skip wrong class skills
18212 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18213 continue;
18215 return true;
18218 return false;
18221 bool Player::HasQuestForGO(int32 GOId) const
18223 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18225 uint32 questid = GetQuestSlotQuestId(i);
18226 if ( questid == 0 )
18227 continue;
18229 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18230 if(qs_itr == mQuestStatus.end())
18231 continue;
18233 QuestStatusData const& qs = qs_itr->second;
18235 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18237 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18238 if(!qinfo)
18239 continue;
18241 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18242 continue;
18244 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18246 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18247 continue;
18249 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18250 return true;
18254 return false;
18257 void Player::UpdateForQuestsGO()
18259 if(m_clientGUIDs.empty())
18260 return;
18262 UpdateData udata;
18263 WorldPacket packet;
18264 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18266 if(IS_GAMEOBJECT_GUID(*itr))
18268 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18269 if(obj)
18270 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18273 udata.BuildPacket(&packet);
18274 GetSession()->SendPacket(&packet);
18277 void Player::SummonIfPossible(bool agree)
18279 if(!agree)
18281 m_summon_expire = 0;
18282 return;
18285 // expire and auto declined
18286 if(m_summon_expire < time(NULL))
18287 return;
18289 // stop taxi flight at summon
18290 if(isInFlight())
18292 GetMotionMaster()->MovementExpired();
18293 m_taxi.ClearTaxiDestinations();
18296 // drop flag at summon
18297 // 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
18298 if(BattleGround *bg = GetBattleGround())
18299 bg->EventPlayerDroppedFlag(this);
18301 m_summon_expire = 0;
18303 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18306 void Player::RemoveItemDurations( Item *item )
18308 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18310 if(*itr==item)
18312 m_itemDuration.erase(itr);
18313 break;
18318 void Player::AddItemDurations( Item *item )
18320 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18322 m_itemDuration.push_back(item);
18323 item->SendTimeUpdate(this);
18327 void Player::AutoUnequipOffhandIfNeed()
18329 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18330 if(!offItem)
18331 return;
18333 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18334 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18335 return;
18337 ItemPosCountVec off_dest;
18338 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18339 if( off_msg == EQUIP_ERR_OK )
18341 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18342 StoreItem( off_dest, offItem, true );
18344 else
18346 MailItemsInfo mi;
18347 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18348 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18349 CharacterDatabase.BeginTransaction();
18350 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18351 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18352 CharacterDatabase.CommitTransaction();
18354 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18355 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18359 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18361 if(spellInfo->EquippedItemClass < 0)
18362 return true;
18364 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18365 // for optimize check 2 used cases only
18366 switch(spellInfo->EquippedItemClass)
18368 case ITEM_CLASS_WEAPON:
18370 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18371 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18372 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18373 return true;
18374 break;
18376 case ITEM_CLASS_ARMOR:
18378 // tabard not have dependent spells
18379 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18380 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18381 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18382 return true;
18384 // shields can be equipped to offhand slot
18385 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18386 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18387 return true;
18389 // ranged slot can have some armor subclasses
18390 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18391 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18392 return true;
18394 break;
18396 default:
18397 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18398 break;
18401 return false;
18404 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18406 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18407 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18408 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18409 return true;
18411 // Check no reagent use mask
18412 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18413 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18414 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18415 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18416 return true;
18418 return false;
18421 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18423 AuraMap& auras = GetAuras();
18424 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18426 Aura* aura = itr->second;
18428 // skip passive (passive item dependent spells work in another way) and not self applied auras
18429 SpellEntry const* spellInfo = aura->GetSpellProto();
18430 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18432 ++itr;
18433 continue;
18436 // skip if not item dependent or have alternative item
18437 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18439 ++itr;
18440 continue;
18443 // no alt item, remove aura, restart check
18444 RemoveAurasDueToSpell(aura->GetId());
18445 itr = auras.begin();
18448 // currently casted spells can be dependent from item
18449 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18451 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18452 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18453 InterruptSpell(i);
18457 uint32 Player::GetResurrectionSpellId()
18459 // search priceless resurrection possibilities
18460 uint32 prio = 0;
18461 uint32 spell_id = 0;
18462 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18463 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18465 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18466 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18468 switch((*itr)->GetId())
18470 case 20707: spell_id = 3026; break; // rank 1
18471 case 20762: spell_id = 20758; break; // rank 2
18472 case 20763: spell_id = 20759; break; // rank 3
18473 case 20764: spell_id = 20760; break; // rank 4
18474 case 20765: spell_id = 20761; break; // rank 5
18475 case 27239: spell_id = 27240; break; // rank 6
18476 case 47883: spell_id = 47882; break; // rank 7
18477 default:
18478 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18479 continue;
18482 prio = 3;
18484 // Twisting Nether // prio: 2 (max)
18485 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18487 prio = 2;
18488 spell_id = 23700;
18492 // Reincarnation (passive spell) // prio: 1
18493 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18494 spell_id = 21169;
18496 return spell_id;
18499 // Used in triggers for check "Only to targets that grant experience or honor" req
18500 bool Player::isHonorOrXPTarget(Unit* pVictim)
18502 uint32 v_level = pVictim->getLevel();
18503 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18505 // Victim level less gray level
18506 if(v_level<=k_grey)
18507 return false;
18509 if(pVictim->GetTypeId() == TYPEID_UNIT)
18511 if (((Creature*)pVictim)->isTotem() ||
18512 ((Creature*)pVictim)->isPet() ||
18513 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18514 return false;
18516 return true;
18519 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18521 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18523 // prepare data for near group iteration (PvP and !PvP cases)
18524 uint32 xp = 0;
18525 bool honored_kill = false;
18527 if(Group *pGroup = GetGroup())
18529 uint32 count = 0;
18530 uint32 sum_level = 0;
18531 Player* member_with_max_level = NULL;
18532 Player* not_gray_member_with_max_level = NULL;
18534 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18536 if(member_with_max_level)
18538 /// not get Xp in PvP or no not gray players in group
18539 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18541 /// skip in check PvP case (for speed, not used)
18542 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18543 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18544 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18546 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18548 Player* pGroupGuy = itr->getSource();
18549 if(!pGroupGuy)
18550 continue;
18552 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18553 continue; // member (alive or dead) or his corpse at req. distance
18555 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18556 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18557 honored_kill = true;
18559 // xp and reputation only in !PvP case
18560 if(!PvP)
18562 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18564 // if is in dungeon then all receive full reputation at kill
18565 // rewarded any alive/dead/near_corpse group member
18566 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18568 // XP updated only for alive group member
18569 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18570 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18572 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18574 pGroupGuy->GiveXP(itr_xp, pVictim);
18575 if(Pet* pet = pGroupGuy->GetPet())
18576 pet->GivePetXP(itr_xp/2);
18579 // quest objectives updated only for alive group member or dead but with not released body
18580 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18582 // normal creature (not pet/etc) can be only in !PvP case
18583 if(pVictim->GetTypeId()==TYPEID_UNIT)
18584 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18590 else // if (!pGroup)
18592 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18594 // honor can be in PvP and !PvP (racial leader) cases
18595 if(RewardHonor(pVictim,1))
18596 honored_kill = true;
18598 // xp and reputation only in !PvP case
18599 if(!PvP)
18601 RewardReputation(pVictim,1);
18602 GiveXP(xp, pVictim);
18604 if(Pet* pet = GetPet())
18605 pet->GivePetXP(xp);
18607 // normal creature (not pet/etc) can be only in !PvP case
18608 if(pVictim->GetTypeId()==TYPEID_UNIT)
18609 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18612 return xp || honored_kill;
18615 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18617 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18619 // prepare data for near group iteration
18620 if(Group *pGroup = GetGroup())
18622 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18624 Player* pGroupGuy = itr->getSource();
18625 if(!pGroupGuy)
18626 continue;
18628 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18629 continue; // member (alive or dead) or his corpse at req. distance
18631 // quest objectives updated only for alive group member or dead but with not released body
18632 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18633 pGroupGuy->KilledMonster(creature_id, creature_guid);
18636 else // if (!pGroup)
18637 KilledMonster(creature_id, creature_guid);
18640 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18642 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18643 return true;
18645 if(isAlive())
18646 return false;
18648 Corpse* corpse = GetCorpse();
18649 if(!corpse)
18650 return false;
18652 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18655 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18657 Item* item = GetWeaponForAttack(attType,true);
18659 // unarmed only with base attack
18660 if(attType != BASE_ATTACK && !item)
18661 return 0;
18663 // weapon skill or (unarmed for base attack)
18664 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18665 return GetBaseSkillValue(skill);
18668 void Player::ResurectUsingRequestData()
18670 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18671 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18673 ResurrectPlayer(0.0f,false);
18675 if(GetMaxHealth() > m_resurrectHealth)
18676 SetHealth( m_resurrectHealth );
18677 else
18678 SetHealth( GetMaxHealth() );
18680 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18681 SetPower(POWER_MANA, m_resurrectMana );
18682 else
18683 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18685 SetPower(POWER_RAGE, 0 );
18687 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18689 SpawnCorpseBones();
18692 void Player::SetClientControl(Unit* target, uint8 allowMove)
18694 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18695 data.append(target->GetPackGUID());
18696 data << uint8(allowMove);
18697 GetSession()->SendPacket(&data);
18700 void Player::UpdateZoneDependentAuras( uint32 newZone )
18702 // remove new continent flight forms
18703 if( !IsAllowUseFlyMountsHere() )
18705 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18706 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18709 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18710 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18711 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18712 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18713 if( !HasAura(itr->second->spellId,0) )
18714 CastSpell(this,itr->second->spellId,true);
18717 void Player::UpdateAreaDependentAuras( uint32 newArea )
18719 // remove auras from spells with area limitations
18720 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18722 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18723 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18724 RemoveAura(iter);
18725 else
18726 ++iter;
18729 // some auras applied at subzone enter
18730 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18731 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18732 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18733 if( !HasAura(itr->second->spellId,0) )
18734 CastSpell(this,itr->second->spellId,true);
18737 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18739 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18740 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18742 return copseReclaimDelay[0];
18745 time_t now = time(NULL);
18746 // 0..2 full period
18747 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18748 return copseReclaimDelay[count];
18751 void Player::UpdateCorpseReclaimDelay()
18753 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18755 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18756 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18757 return;
18759 time_t now = time(NULL);
18760 if(now < m_deathExpireTime)
18762 // full and partly periods 1..3
18763 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18764 if(count < MAX_DEATH_COUNT)
18765 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18766 else
18767 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18769 else
18770 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18773 void Player::SendCorpseReclaimDelay(bool load)
18775 Corpse* corpse = GetCorpse();
18776 if(!corpse)
18777 return;
18779 uint32 delay;
18780 if(load)
18782 if(corpse->GetGhostTime() > m_deathExpireTime)
18783 return;
18785 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18787 uint32 count;
18788 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18789 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18791 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18792 if(count>=MAX_DEATH_COUNT)
18793 count = MAX_DEATH_COUNT-1;
18795 else
18796 count=0;
18798 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18800 time_t now = time(NULL);
18801 if(now >= expected_time)
18802 return;
18804 delay = expected_time-now;
18806 else
18807 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18809 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18810 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18811 data << uint32(delay*IN_MILISECONDS);
18812 GetSession()->SendPacket( &data );
18815 Player* Player::GetNextRandomRaidMember(float radius)
18817 Group *pGroup = GetGroup();
18818 if(!pGroup)
18819 return NULL;
18821 std::vector<Player*> nearMembers;
18822 nearMembers.reserve(pGroup->GetMembersCount());
18824 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18826 Player* Target = itr->getSource();
18828 // IsHostileTo check duel and controlled by enemy
18829 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18830 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18831 nearMembers.push_back(Target);
18834 if (nearMembers.empty())
18835 return NULL;
18837 uint32 randTarget = urand(0,nearMembers.size()-1);
18838 return nearMembers[randTarget];
18841 PartyResult Player::CanUninviteFromGroup() const
18843 const Group* grp = GetGroup();
18844 if(!grp)
18845 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18847 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18848 return PARTY_RESULT_YOU_NOT_LEADER;
18850 if(InBattleGround())
18851 return PARTY_RESULT_INVITE_RESTRICTED;
18853 return PARTY_RESULT_OK;
18856 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18858 //we must move references from m_group to m_originalGroup
18859 SetOriginalGroup(GetGroup(), GetSubGroup());
18861 m_group.unlink();
18862 m_group.link(group, this);
18863 m_group.setSubGroup((uint8)subgroup);
18866 void Player::RemoveFromBattleGroundRaid()
18868 //remove existing reference
18869 m_group.unlink();
18870 if( Group* group = GetOriginalGroup() )
18872 m_group.link(group, this);
18873 m_group.setSubGroup(GetOriginalSubGroup());
18875 SetOriginalGroup(NULL);
18878 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18880 if( group == NULL )
18881 m_originalGroup.unlink();
18882 else
18884 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18885 assert(subgroup >= 0);
18886 m_originalGroup.link(group, this);
18887 m_originalGroup.setSubGroup((uint8)subgroup);
18891 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18893 LiquidData liquid_status;
18894 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18895 if (!res)
18897 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18898 // Small hack for enable breath in WMO
18899 if (IsInWater())
18900 m_MirrorTimerFlags|=UNDERWATER_INWATER;
18901 return;
18904 // All liquids type - check under water position
18905 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
18907 if ( res & LIQUID_MAP_UNDER_WATER)
18908 m_MirrorTimerFlags |= UNDERWATER_INWATER;
18909 else
18910 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
18913 // Allow travel in dark water on taxi or transport
18914 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
18915 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
18916 else
18917 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
18919 // in lava check, anywhere in lava level
18920 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
18922 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18923 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
18924 else
18925 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
18927 // in slime check, anywhere in slime level
18928 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
18930 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18931 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
18932 else
18933 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
18937 void Player::SetCanParry( bool value )
18939 if(m_canParry==value)
18940 return;
18942 m_canParry = value;
18943 UpdateParryPercentage();
18946 void Player::SetCanBlock( bool value )
18948 if(m_canBlock==value)
18949 return;
18951 m_canBlock = value;
18952 UpdateBlockPercentage();
18955 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18957 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18958 if(itr->pos == pos)
18959 return true;
18961 return false;
18964 bool Player::CanUseBattleGroundObject()
18966 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
18967 // maybe gameobject code should handle that ForceReaction usage
18968 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
18969 return ( //InBattleGround() && // in battleground - not need, check in other cases
18970 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
18971 //player cannot use object when he is invulnerable (immune)
18972 !isTotalImmune() && // not totally immune
18973 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
18974 !HasStealthAura() && // not stealthed
18975 !HasInvisibilityAura() && // not invisible
18976 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18977 isAlive() // live player
18981 bool Player::CanCaptureTowerPoint()
18983 return ( !HasStealthAura() && // not stealthed
18984 !HasInvisibilityAura() && // not invisible
18985 isAlive() // live player
18989 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18991 uint32 level = getLevel();
18993 if(level > GT_MAX_LEVEL)
18994 level = GT_MAX_LEVEL; // max level in this dbc
18996 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18997 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18998 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19000 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19001 return 0;
19003 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19005 if(!bsc) // shouldn't happen
19006 return 0xFFFFFFFF;
19008 float cost = 0;
19010 if(hairstyle != newhairstyle)
19011 cost += bsc->cost; // full price
19013 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19014 cost += bsc->cost * 0.5f; // +1/2 of price
19016 if(facialhair != newfacialhair)
19017 cost += bsc->cost * 0.75f; // +3/4 of price
19019 return uint32(cost);
19022 void Player::InitGlyphsForLevel()
19024 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19025 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19026 if(gs->Order)
19027 SetGlyphSlot(gs->Order - 1, gs->Id);
19029 uint32 level = getLevel();
19030 uint32 value = 0;
19032 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19033 if(level >= 15)
19034 value |= (0x01 | 0x02);
19035 if(level >= 30)
19036 value |= 0x08;
19037 if(level >= 50)
19038 value |= 0x04;
19039 if(level >= 70)
19040 value |= 0x10;
19041 if(level >= 80)
19042 value |= 0x20;
19044 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19047 void Player::EnterVehicle(Vehicle *vehicle)
19049 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19050 if(!ve)
19051 return;
19053 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19054 if(!veSeat)
19055 return;
19057 vehicle->SetCharmerGUID(GetGUID());
19058 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19059 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19060 vehicle->setFaction(getFaction());
19062 SetCharm(vehicle); // charm
19063 SetFarSightGUID(vehicle->GetGUID()); // set view
19065 SetClientControl(vehicle, 1); // redirect controls to vehicle
19067 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19068 GetSession()->SendPacket(&data);
19070 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19071 data.append(GetPackGUID());
19072 data << uint32(0); // counter?
19073 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19074 data << uint16(0); // special flags
19075 data << uint32(getMSTime()); // time
19076 data << vehicle->GetPositionX(); // x
19077 data << vehicle->GetPositionY(); // y
19078 data << vehicle->GetPositionZ(); // z
19079 data << vehicle->GetOrientation(); // o
19080 // transport part, TODO: load/calculate seat offsets
19081 data << uint64(vehicle->GetGUID()); // transport guid
19082 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19083 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19084 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19085 data << float(0); // transport orientation
19086 data << uint32(getMSTime()); // transport time
19087 data << uint8(0); // seat
19088 // end of transport part
19089 data << uint32(0); // fall time
19090 GetSession()->SendPacket(&data);
19092 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19093 data << uint64(vehicle->GetGUID());
19094 data << uint32(0x00000000);
19095 data << uint32(0x00000000);
19096 data << uint32(0x00000101);
19098 for(uint32 i = 0; i < 10; ++i)
19099 data << uint16(0) << uint8(0) << uint8(i+8);
19101 data << uint8(0);
19102 data << uint8(0);
19103 GetSession()->SendPacket(&data);
19106 void Player::ExitVehicle(Vehicle *vehicle)
19108 vehicle->SetCharmerGUID(0);
19109 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19110 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19111 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19113 SetCharm(NULL);
19114 SetFarSightGUID(0);
19116 SetClientControl(vehicle, 0);
19118 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19119 data.append(GetPackGUID());
19120 data << uint32(0); // counter?
19121 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19122 data << uint16(0x40); // special flags
19123 data << uint32(getMSTime()); // time
19124 data << vehicle->GetPositionX(); // x
19125 data << vehicle->GetPositionY(); // y
19126 data << vehicle->GetPositionZ(); // z
19127 data << vehicle->GetOrientation(); // o
19128 data << uint32(0); // fall time
19129 GetSession()->SendPacket(&data);
19131 data.Initialize(SMSG_PET_SPELLS, 8+4);
19132 data << uint64(0);
19133 data << uint32(0);
19134 GetSession()->SendPacket(&data);
19136 // only for flyable vehicles?
19137 CastSpell(this, 45472, true); // Parachute
19140 bool Player::isTotalImmune()
19142 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19144 uint32 immuneMask = 0;
19145 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19147 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19148 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19149 return true;
19151 return false;
19154 bool Player::HasTitle(uint32 bitIndex)
19156 if (bitIndex > 128)
19157 return false;
19159 uint32 fieldIndexOffset = bitIndex/32;
19160 uint32 flag = 1 << (bitIndex%32);
19161 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19164 void Player::SetTitle(CharTitlesEntry const* title)
19166 uint32 fieldIndexOffset = title->bit_index/32;
19167 uint32 flag = 1 << (title->bit_index%32);
19168 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19171 void Player::ConvertRune(uint8 index, uint8 newType)
19173 SetCurrentRune(index, newType);
19175 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19176 data << uint8(index);
19177 data << uint8(newType);
19178 GetSession()->SendPacket(&data);
19181 void Player::ResyncRunes(uint8 count)
19183 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19184 for(uint32 i = 0; i < count; ++i)
19186 data << uint8(GetCurrentRune(i)); // rune type
19187 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19189 GetSession()->SendPacket(&data);
19192 void Player::AddRunePower(uint8 index)
19194 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19195 data << uint32(1 << index); // mask (0x00-0x3F probably)
19196 GetSession()->SendPacket(&data);
19199 void Player::InitRunes()
19201 if(getClass() != CLASS_DEATH_KNIGHT)
19202 return;
19204 m_runes = new Runes;
19206 m_runes->runeState = 0;
19208 for(uint32 i = 0; i < MAX_RUNES; ++i)
19210 SetBaseRune(i, i / 2); // init base types
19211 SetCurrentRune(i, i / 2); // init current types
19212 SetRuneCooldown(i, 0); // reset cooldowns
19213 m_runes->SetRuneState(i);
19216 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19217 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19220 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19222 Loot loot;
19223 loot.FillLoot (loot_id,store,this,true);
19225 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19226 for(uint32 i = 0; i < max_slot; ++i)
19228 LootItem* lootItem = loot.LootItemInSlot(i,this);
19230 ItemPosCountVec dest;
19231 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19232 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19233 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19234 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19235 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19236 if(msg != EQUIP_ERR_OK)
19238 SendEquipError( msg, NULL, NULL );
19239 continue;
19242 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19243 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19247 uint32 Player::CalculateTalentsPoints() const
19249 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19251 if(getClass() != CLASS_DEATH_KNIGHT)
19252 return base_talent;
19254 uint32 talentPointsForLevel =
19255 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19256 + m_questRewardTalentCount;
19258 if(talentPointsForLevel > base_talent)
19259 talentPointsForLevel = base_talent;
19261 return talentPointsForLevel;
19264 bool Player::IsAllowUseFlyMountsHere() const
19266 if (isGameMaster())
19267 return true;
19269 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19270 return v_map == 530 || v_map == 571 && HasSpell(54197);
19273 void Player::learnSpellHighRank(uint32 spellid)
19275 learnSpell(spellid,false);
19277 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19278 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19279 learnSpellHighRank(itr->second);
19282 void Player::_LoadSkills()
19284 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19286 // reset skill modifiers and set correct unlearn flags
19287 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
19289 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19291 // set correct unlearn bit
19292 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19293 if(!id) continue;
19295 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19296 if(!pSkill) continue;
19298 // enable unlearn button for primary professions only
19299 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19300 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19301 else
19302 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19304 // set fixed skill ranges
19305 switch(GetSkillRangeType(pSkill,false))
19307 case SKILL_RANGE_LANGUAGE: // 300..300
19308 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19309 break;
19310 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19311 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19312 break;
19313 default:
19314 break;
19317 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19318 learnSkillRewardedSpells(id, vskill);
19321 // special settings
19322 if(getClass()==CLASS_DEATH_KNIGHT)
19324 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19325 if(base_level < 1)
19326 base_level = 1;
19327 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19328 if(base_skill < 1)
19329 base_skill = 1; // skill mast be known and then > 0 in any case
19331 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19332 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19333 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19334 SetSkill(SKILL_AXES, base_skill,base_skill);
19335 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19336 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19337 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19338 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19339 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19340 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19341 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19342 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19343 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19344 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19345 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19346 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19350 uint32 Player::GetPhaseMaskForSpawn() const
19352 uint32 phase = PHASEMASK_NORMAL;
19353 if(!isGameMaster())
19354 phase = GetPhaseMask();
19355 else
19357 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19358 if(!phases.empty())
19359 phase = phases.front()->GetMiscValue();
19362 // some aura phases include 1 normal map in addition to phase itself
19363 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19364 return n_phase;
19366 return PHASEMASK_NORMAL;
19369 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19371 ItemPrototype const* pProto = pItem->GetProto();
19373 // proto based limitations
19374 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19375 return res;
19377 // check unique-equipped on gems
19378 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19380 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19381 if(!enchant_id)
19382 continue;
19383 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19384 if(!enchantEntry)
19385 continue;
19387 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19388 if(!pGem)
19389 continue;
19391 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19392 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19393 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19395 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19396 return res;
19399 return EQUIP_ERR_OK;
19402 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19404 // check unique-equipped on item
19405 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19407 // there is an equip limit on this item
19408 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19409 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19412 // check unique-equipped limit
19413 if (itemProto->ItemLimitCategory)
19415 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19416 if(!limitEntry)
19417 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19419 if(limit_count > limitEntry->maxCount)
19420 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19422 // there is an equip limit on this item
19423 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19424 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19427 return EQUIP_ERR_OK;
19430 void Player::HandleFall(MovementInfo const& movementInfo)
19432 // calculate total z distance of the fall
19433 float z_diff = m_lastFallZ - movementInfo.z;
19434 sLog.outDebug("zDiff = %f", z_diff);
19436 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19437 // 14.57 can be calculated by resolving damageperc formular below to 0
19438 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19439 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19440 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19442 //Safe fall, fall height reduction
19443 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19445 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19447 if(damageperc >0 )
19449 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19451 float height = movementInfo.z;
19452 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19454 if (damage > 0)
19456 //Prevent fall damage from being more than the player maximum health
19457 if (damage > GetMaxHealth())
19458 damage = GetMaxHealth();
19460 // Gust of Wind
19461 if (GetDummyAura(43621))
19462 damage = GetMaxHealth()/2;
19464 EnvironmentalDamage(DAMAGE_FALL, damage);
19466 // recheck alive, might have died of EnvironmentalDamage
19467 if (isAlive())
19468 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19471 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19472 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);
19477 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19479 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19482 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19484 uint32 CurTalentPoints = GetFreeTalentPoints();
19486 if(CurTalentPoints == 0)
19487 return;
19489 if (talentRank >= MAX_TALENT_RANK)
19490 return;
19492 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19494 if(!talentInfo)
19495 return;
19497 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19499 if(!talentTabInfo)
19500 return;
19502 // prevent learn talent for different class (cheating)
19503 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19504 return;
19506 // find current max talent rank
19507 int32 curtalent_maxrank = 0;
19508 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19510 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19512 curtalent_maxrank = k + 1;
19513 break;
19517 // we already have same or higher talent rank learned
19518 if(curtalent_maxrank >= (talentRank + 1))
19519 return;
19521 // check if we have enough talent points
19522 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19523 return;
19525 // Check if it requires another talent
19526 if (talentInfo->DependsOn > 0)
19528 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19530 bool hasEnoughRank = false;
19531 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; i++)
19533 if (depTalentInfo->RankID[i] != 0)
19534 if (HasSpell(depTalentInfo->RankID[i]))
19535 hasEnoughRank = true;
19537 if (!hasEnoughRank)
19538 return;
19542 // Find out how many points we have in this field
19543 uint32 spentPoints = 0;
19545 uint32 tTab = talentInfo->TalentTab;
19546 if (talentInfo->Row > 0)
19548 unsigned int numRows = sTalentStore.GetNumRows();
19549 for (unsigned int i = 0; i < numRows; i++) // Loop through all talents.
19551 // Someday, someone needs to revamp
19552 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19553 if (tmpTalent) // the way talents are tracked
19555 if (tmpTalent->TalentTab == tTab)
19557 for (int j = 0; j < MAX_TALENT_RANK; j++)
19559 if (tmpTalent->RankID[j] != 0)
19561 if (HasSpell(tmpTalent->RankID[j]))
19563 spentPoints += j + 1;
19572 // not have required min points spent in talent tree
19573 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19574 return;
19576 // spell not set in talent.dbc
19577 uint32 spellid = talentInfo->RankID[talentRank];
19578 if( spellid == 0 )
19580 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19581 return;
19584 // already known
19585 if(HasSpell(spellid))
19586 return;
19588 // learn! (other talent ranks will unlearned at learning)
19589 learnSpell(spellid, false);
19590 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19592 // update free talent points
19593 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19596 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19598 Pet *pet = GetPet();
19600 if(!pet)
19601 return;
19603 if(petGuid != pet->GetGUID())
19604 return;
19606 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19608 if(CurTalentPoints == 0)
19609 return;
19611 if (talentRank >= MAX_PET_TALENT_RANK)
19612 return;
19614 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19616 if(!talentInfo)
19617 return;
19619 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19621 if(!talentTabInfo)
19622 return;
19624 CreatureInfo const *ci = pet->GetCreatureInfo();
19626 if(!ci)
19627 return;
19629 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19631 if(!pet_family)
19632 return;
19634 if(pet_family->petTalentType < 0) // not hunter pet
19635 return;
19637 // prevent learn talent for different family (cheating)
19638 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19639 return;
19641 // find current max talent rank
19642 int32 curtalent_maxrank = 0;
19643 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19645 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19647 curtalent_maxrank = k + 1;
19648 break;
19652 // we already have same or higher talent rank learned
19653 if(curtalent_maxrank >= (talentRank + 1))
19654 return;
19656 // check if we have enough talent points
19657 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19658 return;
19660 // Check if it requires another talent
19661 if (talentInfo->DependsOn > 0)
19663 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19665 bool hasEnoughRank = false;
19666 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; i++)
19668 if (depTalentInfo->RankID[i] != 0)
19669 if (pet->HasSpell(depTalentInfo->RankID[i]))
19670 hasEnoughRank = true;
19672 if (!hasEnoughRank)
19673 return;
19677 // Find out how many points we have in this field
19678 uint32 spentPoints = 0;
19680 uint32 tTab = talentInfo->TalentTab;
19681 if (talentInfo->Row > 0)
19683 unsigned int numRows = sTalentStore.GetNumRows();
19684 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19686 // Someday, someone needs to revamp
19687 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19688 if (tmpTalent) // the way talents are tracked
19690 if (tmpTalent->TalentTab == tTab)
19692 for (int j = 0; j < MAX_TALENT_RANK; j++)
19694 if (tmpTalent->RankID[j] != 0)
19696 if (pet->HasSpell(tmpTalent->RankID[j]))
19698 spentPoints += j + 1;
19707 // not have required min points spent in talent tree
19708 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19709 return;
19711 // spell not set in talent.dbc
19712 uint32 spellid = talentInfo->RankID[talentRank];
19713 if( spellid == 0 )
19715 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19716 return;
19719 // already known
19720 if(pet->HasSpell(spellid))
19721 return;
19723 // learn! (other talent ranks will unlearned at learning)
19724 pet->learnSpell(spellid);
19725 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19727 // update free talent points
19728 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19731 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19733 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19735 if(apply)
19736 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19737 else
19738 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19742 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19744 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19745 SetFallInformation(minfo.fallTime, minfo.z);
19748 void Player::UnsummonPetTemporaryIfAny()
19750 Pet* pet = GetPet();
19751 if(!pet)
19752 return;
19754 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19756 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19757 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19760 RemovePet(pet, PET_SAVE_AS_CURRENT);
19763 void Player::ResummonPetTemporaryUnSummonedIfAny()
19765 if(!m_temporaryUnsummonedPetNumber)
19766 return;
19768 // not resummon in not appropriate state
19769 if(IsPetNeedBeTemporaryUnsummoned())
19770 return;
19772 if(GetPetGUID())
19773 return;
19775 Pet* NewPet = new Pet;
19776 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19777 delete NewPet;
19779 m_temporaryUnsummonedPetNumber = 0;