[8056] Move SMSG_CLEAR_COOLDOWN into function and use it. Other cleanups.
[getmangos.git] / src / game / Player.cpp
blob669ebcd6109c80e6c54f2529fd438b4ccc5aa077
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.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
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 m_DailyQuestChanged = false;
350 m_lastDailyQuestTime = 0;
352 for (int i=0; i<MAX_TIMERS; ++i)
353 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
355 m_MirrorTimerFlags = UNDERWATER_NONE;
356 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
357 m_isInWater = false;
358 m_drunkTimer = 0;
359 m_drunk = 0;
360 m_restTime = 0;
361 m_deathTimer = 0;
362 m_deathExpireTime = 0;
364 m_swingErrorMsg = 0;
366 m_DetectInvTimer = 1*IN_MILISECONDS;
368 m_bgBattleGroundID = 0;
369 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
370 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
372 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
373 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
375 m_bgTeam = 0;
377 m_logintime = time(NULL);
378 m_Last_tick = m_logintime;
379 m_WeaponProficiency = 0;
380 m_ArmorProficiency = 0;
381 m_canParry = false;
382 m_canBlock = false;
383 m_canDualWield = false;
384 m_canTitanGrip = false;
385 m_ammoDPS = 0.0f;
387 m_temporaryUnsummonedPetNumber = 0;
388 //cache for UNIT_CREATED_BY_SPELL to allow
389 //returning reagents for temporarily removed pets
390 //when dying/logging out
391 m_oldpetspell = 0;
393 ////////////////////Rest System/////////////////////
394 time_inn_enter=0;
395 inn_pos_mapid=0;
396 inn_pos_x=0;
397 inn_pos_y=0;
398 inn_pos_z=0;
399 m_rest_bonus=0;
400 rest_type=REST_TYPE_NO;
401 ////////////////////Rest System/////////////////////
403 m_mailsLoaded = false;
404 m_mailsUpdated = false;
405 unReadMails = 0;
406 m_nextMailDelivereTime = 0;
408 m_resetTalentsCost = 0;
409 m_resetTalentsTime = 0;
410 m_itemUpdateQueueBlocked = false;
412 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
413 m_forced_speed_changes[i] = 0;
415 m_stableSlots = 0;
417 /////////////////// Instance System /////////////////////
419 m_HomebindTimer = 0;
420 m_InstanceValid = true;
421 m_dungeonDifficulty = DIFFICULTY_NORMAL;
423 m_lastPotionId = 0;
425 m_activeSpec = 0;
426 m_specsCount = 1;
428 for (int i = 0; i < BASEMOD_END; ++i)
430 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
431 m_auraBaseMod[i][PCT_MOD] = 1.0f;
434 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
435 m_baseRatingValue[i] = 0;
437 m_baseSpellDamage = 0;
438 m_baseSpellHealing = 0;
439 m_baseFeralAP = 0;
440 m_baseManaRegen = 0;
442 // Honor System
443 m_lastHonorUpdateTime = time(NULL);
445 // Player summoning
446 m_summon_expire = 0;
447 m_summon_mapid = 0;
448 m_summon_x = 0.0f;
449 m_summon_y = 0.0f;
450 m_summon_z = 0.0f;
452 //Default movement to run mode
453 m_unit_movement_flags = 0;
455 m_mover = this;
457 m_miniPet = 0;
458 m_bgAfkReportedTimer = 0;
459 m_contestedPvPTimer = 0;
461 m_declinedname = NULL;
462 m_runes = NULL;
464 m_lastFallTime = 0;
465 m_lastFallZ = 0;
468 Player::~Player ()
470 CleanupsBeforeDelete();
472 // it must be unloaded already in PlayerLogout and accessed only for loggined player
473 //m_social = NULL;
475 // Note: buy back item already deleted from DB when player was saved
476 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
478 if(m_items[i])
479 delete m_items[i];
481 CleanupChannels();
483 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
484 delete itr->second;
486 //all mailed items should be deleted, also all mail should be deallocated
487 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
488 delete *itr;
490 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
491 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
493 delete PlayerTalkClass;
495 if (m_transport)
497 m_transport->RemovePassenger(this);
500 for(size_t x = 0; x < ItemSetEff.size(); x++)
501 if(ItemSetEff[x])
502 delete ItemSetEff[x];
504 // clean up player-instance binds, may unload some instance saves
505 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
506 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
507 itr->second.save->RemovePlayer(this);
509 delete m_declinedname;
510 delete m_runes;
513 void Player::CleanupsBeforeDelete()
515 if(m_uint32Values) // only for fully created Object
517 TradeCancel(false);
518 DuelComplete(DUEL_INTERUPTED);
520 Unit::CleanupsBeforeDelete();
523 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 )
525 //FIXME: outfitId not used in player creating
527 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
529 m_name = name;
531 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
532 if(!info)
534 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
535 return false;
538 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
539 m_items[i] = NULL;
541 m_race = race;
542 m_class = class_;
544 SetMapId(info->mapId);
545 Relocate(info->positionX,info->positionY,info->positionZ);
547 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
548 if(!cEntry)
550 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
551 return false;
554 uint8 powertype = cEntry->powerType;
556 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
557 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
559 switch(gender)
561 case GENDER_FEMALE:
562 SetDisplayId(info->displayId_f );
563 SetNativeDisplayId(info->displayId_f );
564 break;
565 case GENDER_MALE:
566 SetDisplayId(info->displayId_m );
567 SetNativeDisplayId(info->displayId_m );
568 break;
569 default:
570 sLog.outError("Invalid gender %u for player",gender);
571 return false;
572 break;
575 setFactionForRace(m_race);
577 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
579 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
580 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
581 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
582 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
583 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
584 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
586 // -1 is default value
587 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
589 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
590 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
591 SetByteValue(PLAYER_BYTES_3, 0, gender);
593 SetUInt32Value( PLAYER_GUILDID, 0 );
594 SetUInt32Value( PLAYER_GUILDRANK, 0 );
595 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
597 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 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 InitPrimaryProfessions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 DealDamageMods(this,damage,&absorb);
851 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
852 data << uint64(GetGUID());
853 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
854 data << uint32(damage);
855 data << uint32(absorb);
856 data << uint32(resist);
857 SendMessageToSet(&data, true);
859 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
861 if(!isAlive())
863 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
865 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
866 DurabilityLossAll(0.10f,false);
867 // durability lost message
868 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
869 GetSession()->SendPacket(&data2);
872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
876 int32 Player::getMaxTimer(MirrorTimerType timer)
878 switch (timer)
880 case FATIGUE_TIMER:
881 return MINUTE*IN_MILISECONDS;
882 case BREATH_TIMER:
884 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
885 return DISABLED_MIRROR_TIMER;
886 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
887 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
888 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
889 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
890 return UnderWaterTime;
892 case FIRE_TIMER:
894 if (!isAlive())
895 return DISABLED_MIRROR_TIMER;
896 return 1*IN_MILISECONDS;
898 default:
899 return 0;
901 return 0;
904 void Player::UpdateMirrorTimers()
906 // Desync flags for update on next HandleDrowning
907 if (m_MirrorTimerFlags)
908 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
911 void Player::HandleDrowning(uint32 time_diff)
913 if (!m_MirrorTimerFlags)
914 return;
916 // In water
917 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
919 // Breath timer not activated - activate it
920 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
922 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
923 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
925 else // If activated - do tick
927 m_MirrorTimer[BREATH_TIMER]-=time_diff;
928 // Timer limit - need deal damage
929 if (m_MirrorTimer[BREATH_TIMER] < 0)
931 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
932 // Calculate and deal damage
933 // TODO: Check this formula
934 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
935 EnvironmentalDamage(DAMAGE_DROWNING, damage);
937 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
938 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
941 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
943 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
944 // Need breath regen
945 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
946 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
947 StopMirrorTimer(BREATH_TIMER);
948 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
949 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
952 // In dark water
953 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
955 // Fatigue timer not activated - activate it
956 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
958 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
959 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
961 else
963 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
964 // Timer limit - need deal damage or teleport ghost to graveyard
965 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
967 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
968 if (isAlive()) // Calculate and deal damage
970 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
971 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
973 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
974 RepopAtGraveyard();
976 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
977 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
980 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
982 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
983 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
984 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
985 StopMirrorTimer(FATIGUE_TIMER);
986 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
987 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
990 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
992 // Breath timer not activated - activate it
993 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
994 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
995 else
997 m_MirrorTimer[FIRE_TIMER]-=time_diff;
998 if (m_MirrorTimer[FIRE_TIMER] < 0)
1000 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1001 // Calculate and deal damage
1002 // TODO: Check this formula
1003 uint32 damage = urand(600, 700);
1004 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1005 EnvironmentalDamage(DAMAGE_LAVA, damage);
1006 else
1007 EnvironmentalDamage(DAMAGE_SLIME, damage);
1011 else
1012 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1014 // Recheck timers flag
1015 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1016 for (int i = 0; i< MAX_TIMERS; ++i)
1017 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1019 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1020 break;
1022 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1025 ///The player sobers by 256 every 10 seconds
1026 void Player::HandleSobering()
1028 m_drunkTimer = 0;
1030 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1031 SetDrunkValue(drunk);
1034 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1036 if(value >= 23000)
1037 return DRUNKEN_SMASHED;
1038 if(value >= 12800)
1039 return DRUNKEN_DRUNK;
1040 if(value & 0xFFFE)
1041 return DRUNKEN_TIPSY;
1042 return DRUNKEN_SOBER;
1045 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1047 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1049 m_drunk = newDrunkenValue;
1050 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1052 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1054 // special drunk invisibility detection
1055 if(newDrunkenState >= DRUNKEN_DRUNK)
1056 m_detectInvisibilityMask |= (1<<6);
1057 else
1058 m_detectInvisibilityMask &= ~(1<<6);
1060 if(newDrunkenState == oldDrunkenState)
1061 return;
1063 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1064 data << uint64(GetGUID());
1065 data << uint32(newDrunkenState);
1066 data << uint32(itemId);
1068 SendMessageToSet(&data, true);
1071 void Player::Update( uint32 p_time )
1073 if(!IsInWorld())
1074 return;
1076 // undelivered mail
1077 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1079 SendNewMail();
1080 ++unReadMails;
1082 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1083 m_nextMailDelivereTime = 0;
1086 Unit::Update( p_time );
1088 // update player only attacks
1089 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1091 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1094 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1096 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1099 time_t now = time (NULL);
1101 UpdatePvPFlag(now);
1103 UpdateContestedPvP(p_time);
1105 UpdateDuelFlag(now);
1107 CheckDuelDistance(now);
1109 UpdateAfkReport(now);
1111 // Update items that have just a limited lifetime
1112 if (now>m_Last_tick)
1113 UpdateItemDuration(uint32(now- m_Last_tick));
1115 if (!m_timedquests.empty())
1117 std::set<uint32>::iterator iter = m_timedquests.begin();
1118 while (iter != m_timedquests.end())
1120 QuestStatusData& q_status = mQuestStatus[*iter];
1121 if( q_status.m_timer <= p_time )
1123 uint32 quest_id = *iter;
1124 ++iter; // current iter will be removed in FailTimedQuest
1125 FailTimedQuest( quest_id );
1127 else
1129 q_status.m_timer -= p_time;
1130 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1131 ++iter;
1136 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1138 Unit *pVictim = getVictim();
1139 if (pVictim && !IsNonMeleeSpellCasted(false))
1141 // default combat reach 10
1142 // TODO add weapon,skill check
1144 float pldistance = ATTACK_DISTANCE;
1146 if (isAttackReady(BASE_ATTACK))
1148 if(!IsWithinDistInMap(pVictim, pldistance))
1150 setAttackTimer(BASE_ATTACK,100);
1151 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1153 SendAttackSwingNotInRange();
1154 m_swingErrorMsg = 1;
1157 //120 degrees of radiant range
1158 else if( !HasInArc( 2*M_PI/3, pVictim ))
1160 setAttackTimer(BASE_ATTACK,100);
1161 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1163 SendAttackSwingBadFacingAttack();
1164 m_swingErrorMsg = 2;
1167 else
1169 m_swingErrorMsg = 0; // reset swing error state
1171 // prevent base and off attack in same time, delay attack at 0.2 sec
1172 if(haveOffhandWeapon())
1174 uint32 off_att = getAttackTimer(OFF_ATTACK);
1175 if(off_att < ATTACK_DISPLAY_DELAY)
1176 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1178 AttackerStateUpdate(pVictim, BASE_ATTACK);
1179 resetAttackTimer(BASE_ATTACK);
1183 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1185 if(!IsWithinDistInMap(pVictim, pldistance))
1187 setAttackTimer(OFF_ATTACK,100);
1189 else if( !HasInArc( 2*M_PI/3, pVictim ))
1191 setAttackTimer(OFF_ATTACK,100);
1193 else
1195 // prevent base and off attack in same time, delay attack at 0.2 sec
1196 uint32 base_att = getAttackTimer(BASE_ATTACK);
1197 if(base_att < ATTACK_DISPLAY_DELAY)
1198 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1199 // do attack
1200 AttackerStateUpdate(pVictim, OFF_ATTACK);
1201 resetAttackTimer(OFF_ATTACK);
1205 Unit *owner = pVictim->GetOwner();
1206 Unit *u = owner ? owner : pVictim;
1207 if(u->IsPvP() && (!duel || duel->opponent != u))
1209 UpdatePvP(true);
1210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1215 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1217 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1219 int time_inn = time(NULL)-GetTimeInnEnter();
1220 if (time_inn >= 10) //freeze update
1222 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1223 //speed collect rest bonus (section/in hour)
1224 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1225 UpdateInnerTime(time(NULL));
1230 if(m_regenTimer > 0)
1232 if(p_time >= m_regenTimer)
1233 m_regenTimer = 0;
1234 else
1235 m_regenTimer -= p_time;
1238 if (m_weaponChangeTimer > 0)
1240 if(p_time >= m_weaponChangeTimer)
1241 m_weaponChangeTimer = 0;
1242 else
1243 m_weaponChangeTimer -= p_time;
1246 if (m_zoneUpdateTimer > 0)
1248 if(p_time >= m_zoneUpdateTimer)
1250 uint32 newzone, newarea;
1251 GetZoneAndAreaId(newzone,newarea);
1253 if( m_zoneUpdateId != newzone )
1254 UpdateZone(newzone,newarea); // also update area
1255 else
1257 // use area updates as well
1258 // needed for free far all arenas for example
1259 if( m_areaUpdateId != newarea )
1260 UpdateArea(newarea);
1262 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1265 else
1266 m_zoneUpdateTimer -= p_time;
1269 if (isAlive())
1271 RegenerateAll();
1274 if (m_deathState == JUST_DIED)
1276 KillPlayer();
1279 if(m_nextSave > 0)
1281 if(p_time >= m_nextSave)
1283 // m_nextSave reseted in SaveToDB call
1284 SaveToDB();
1285 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1287 else
1289 m_nextSave -= p_time;
1293 //Handle Water/drowning
1294 HandleDrowning(p_time);
1296 //Handle detect stealth players
1297 if (m_DetectInvTimer > 0)
1299 if (p_time >= m_DetectInvTimer)
1301 m_DetectInvTimer = 3000;
1302 HandleStealthedUnitsDetection();
1304 else
1305 m_DetectInvTimer -= p_time;
1308 // Played time
1309 if (now > m_Last_tick)
1311 uint32 elapsed = uint32(now - m_Last_tick);
1312 m_Played_time[0] += elapsed; // Total played time
1313 m_Played_time[1] += elapsed; // Level played time
1314 m_Last_tick = now;
1317 if (m_drunk)
1319 m_drunkTimer += p_time;
1321 if (m_drunkTimer > 10*IN_MILISECONDS)
1322 HandleSobering();
1325 // not auto-free ghost from body in instances
1326 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1328 if(p_time >= m_deathTimer)
1330 m_deathTimer = 0;
1331 BuildPlayerRepop();
1332 RepopAtGraveyard();
1334 else
1335 m_deathTimer -= p_time;
1338 UpdateEnchantTime(p_time);
1339 UpdateHomebindTime(p_time);
1341 // group update
1342 SendUpdateToOutOfRangeGroupMembers();
1344 Pet* pet = GetPet();
1345 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1347 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1348 return;
1352 void Player::setDeathState(DeathState s)
1354 uint32 ressSpellId = 0;
1356 bool cur = isAlive();
1358 if(s == JUST_DIED && cur)
1360 // drunken state is cleared on death
1361 SetDrunkValue(0);
1362 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1363 ClearComboPoints();
1365 clearResurrectRequestData();
1367 // remove form before other mods to prevent incorrect stats calculation
1368 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1370 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1371 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1373 // remove uncontrolled pets
1374 RemoveMiniPet();
1376 // save value before aura remove in Unit::setDeathState
1377 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1379 // passive spell
1380 if(!ressSpellId)
1381 ressSpellId = GetResurrectionSpellId();
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1384 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1386 Unit::setDeathState(s);
1388 // restore resurrection spell id for player after aura remove
1389 if(s == JUST_DIED && cur && ressSpellId)
1390 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1392 if(isAlive() && !cur)
1394 //clear aura case after resurrection by another way (spells will be applied before next death)
1395 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1397 // restore default warrior stance
1398 if(getClass()== CLASS_WARRIOR)
1399 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1403 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1405 Field *fields = result->Fetch();
1407 *p_data << uint64(GetGUID());
1408 *p_data << m_name;
1410 *p_data << uint8(getRace());
1411 uint8 pClass = getClass();
1412 *p_data << uint8(pClass);
1413 *p_data << uint8(getGender());
1415 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1416 *p_data << uint8(bytes);
1417 *p_data << uint8(bytes >> 8);
1418 *p_data << uint8(bytes >> 16);
1419 *p_data << uint8(bytes >> 24);
1421 bytes = GetUInt32Value(PLAYER_BYTES_2);
1422 *p_data << uint8(bytes);
1424 *p_data << uint8(getLevel()); // player level
1425 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1426 uint32 zoneId = fields[10].GetUInt32();
1427 sLog.outDebug("Player::BuildEnumData: map:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1428 *p_data << uint32(zoneId);
1429 *p_data << uint32(GetMapId());
1431 *p_data << GetPositionX();
1432 *p_data << GetPositionY();
1433 *p_data << GetPositionZ();
1435 // guild id
1436 *p_data << uint32(fields[14].GetUInt32());
1438 uint32 char_flags = 0;
1439 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1440 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1441 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1442 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1443 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1444 char_flags |= CHARACTER_FLAG_GHOST;
1445 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1446 char_flags |= CHARACTER_FLAG_RENAME;
1447 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1449 if(!fields[15].GetCppString().empty())
1450 char_flags |= CHARACTER_FLAG_DECLINED;
1452 else
1453 char_flags |= CHARACTER_FLAG_DECLINED;
1455 *p_data << uint32(char_flags); // character flags
1456 // character customize (flags?)
1457 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1458 *p_data << uint8(1); // unknown
1460 // Pets info
1462 uint32 petDisplayId = 0;
1463 uint32 petLevel = 0;
1464 uint32 petFamily = 0;
1466 // show pet at selection character in character list only for non-ghost character
1467 if (result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1469 uint32 entry = fields[11].GetUInt32();
1470 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1471 if(cInfo)
1473 petDisplayId = fields[12].GetUInt32();
1474 petLevel = fields[13].GetUInt32();
1475 petFamily = cInfo->family;
1479 *p_data << uint32(petDisplayId);
1480 *p_data << uint32(petLevel);
1481 *p_data << uint32(petFamily);
1484 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1486 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1487 uint32 item_id = GetUInt32Value(visualbase);
1488 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1489 SpellItemEnchantmentEntry const *enchant = NULL;
1491 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1493 uint32 enchantId = GetUInt16Value(visualbase + 1, enchantSlot);
1494 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1495 break;
1498 if (proto != NULL)
1500 *p_data << uint32(proto->DisplayInfoID);
1501 *p_data << uint8(proto->InventoryType);
1502 *p_data << uint32(enchant ? enchant->aura_id : 0);
1504 else
1506 *p_data << uint32(0);
1507 *p_data << uint8(0);
1508 *p_data << uint32(0); // enchant?
1511 *p_data << uint32(0); // first bag display id
1512 *p_data << uint8(0); // first bag inventory type
1513 *p_data << uint32(0); // enchant?
1516 bool Player::ToggleAFK()
1518 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1520 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1522 // afk player not allowed in battleground
1523 if(state && InBattleGround())
1524 LeaveBattleground();
1526 return state;
1529 bool Player::ToggleDND()
1531 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1533 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1536 uint8 Player::chatTag() const
1538 // it's bitmask
1539 // 0x8 - ??
1540 // 0x4 - gm
1541 // 0x2 - dnd
1542 // 0x1 - afk
1543 if(isGMChat())
1544 return 4;
1545 else if(isDND())
1546 return 3;
1547 if(isAFK())
1548 return 1;
1549 else
1550 return 0;
1553 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1555 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1557 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1558 return false;
1561 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1562 Pet* pet = GetPet();
1564 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1566 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1567 // don't let gm level > 1 either
1568 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1569 return false;
1571 // client without expansion support
1572 if(GetSession()->Expansion() < mEntry->Expansion())
1574 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1576 if(GetTransport())
1577 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1579 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1581 return false; // normal client can't teleport to this map...
1583 else
1585 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1588 // if we were on a transport, leave
1589 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1591 m_transport->RemovePassenger(this);
1592 m_transport = NULL;
1593 m_movementInfo.t_x = 0.0f;
1594 m_movementInfo.t_y = 0.0f;
1595 m_movementInfo.t_z = 0.0f;
1596 m_movementInfo.t_o = 0.0f;
1597 m_movementInfo.t_time = 0;
1600 // The player was ported to another map and looses the duel immediately.
1601 // We have to perform this check before the teleport, otherwise the
1602 // ObjectAccessor won't find the flag.
1603 if (duel && GetMapId()!=mapid)
1605 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1606 if (obj)
1607 DuelComplete(DUEL_FLED);
1610 // reset movement flags at teleport, because player will continue move with these flags after teleport
1611 m_movementInfo.flags = 0;
1613 if ((GetMapId() == mapid) && (!m_transport))
1615 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1617 //same map, only remove pet if out of range for new position
1618 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1619 UnsummonPetTemporaryIfAny();
1622 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1623 CombatStop();
1625 // this will be used instead of the current location in SaveToDB
1626 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1627 SetFallInformation(0, z);
1629 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1630 // at client packet MSG_MOVE_TELEPORT_ACK
1631 SetSemaphoreTeleportNear(true);
1632 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1633 if(!GetSession()->PlayerLogout())
1635 WorldPacket data;
1636 BuildTeleportAckMsg(&data, x, y, z, orientation);
1637 GetSession()->SendPacket(&data);
1640 else
1642 // far teleport to another map
1643 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1644 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1646 // Check enter rights before map getting to avoid creating instance copy for player
1647 // this check not dependent from map instance copy and same for all instance copies of selected map
1648 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1649 return false;
1651 // If the map is not created, assume it is possible to enter it.
1652 // It will be created in the WorldPortAck.
1653 Map *map = MapManager::Instance().FindMap(mapid);
1654 if (!map || map->CanEnter(this))
1656 SetSelection(0);
1658 CombatStop();
1660 ResetContestedPvP();
1662 // remove player from battleground on far teleport (when changing maps)
1663 if(BattleGround const* bg = GetBattleGround())
1665 // Note: at battleground join battleground id set before teleport
1666 // and we already will found "current" battleground
1667 // just need check that this is targeted map or leave
1668 if(bg->GetMapId() != mapid)
1669 LeaveBattleground(false); // don't teleport to entry point
1672 // remove pet on map change
1673 if (pet)
1674 UnsummonPetTemporaryIfAny();
1676 // remove all dyn objects
1677 RemoveAllDynObjects();
1679 // stop spellcasting
1680 // not attempt interrupt teleportation spell at caster teleport
1681 if(!(options & TELE_TO_SPELL))
1682 if(IsNonMeleeSpellCasted(true))
1683 InterruptNonMeleeSpells(true);
1685 if(!GetSession()->PlayerLogout())
1687 // send transfer packets
1688 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1689 data << uint32(mapid);
1690 if (m_transport)
1692 data << m_transport->GetEntry() << GetMapId();
1694 GetSession()->SendPacket(&data);
1696 data.Initialize(SMSG_NEW_WORLD, (20));
1697 if (m_transport)
1699 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1701 else
1703 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1705 GetSession()->SendPacket( &data );
1706 SendSavedInstances();
1708 // remove from old map now
1709 if(oldmap) oldmap->Remove(this, false);
1712 // new final coordinates
1713 float final_x = x;
1714 float final_y = y;
1715 float final_z = z;
1716 float final_o = orientation;
1718 if(m_transport)
1720 final_x += m_movementInfo.t_x;
1721 final_y += m_movementInfo.t_y;
1722 final_z += m_movementInfo.t_z;
1723 final_o += m_movementInfo.t_o;
1726 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1727 SetFallInformation(0, final_z);
1728 // if the player is saved before worldportack (at logout for example)
1729 // this will be used instead of the current location in SaveToDB
1731 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1733 // move packet sent by client always after far teleport
1734 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1735 SetSemaphoreTeleportFar(true);
1737 else
1738 return false;
1740 return true;
1743 void Player::AddToWorld()
1745 ///- Do not add/remove the player from the object storage
1746 ///- It will crash when updating the ObjectAccessor
1747 ///- The player should only be added when logging in
1748 Unit::AddToWorld();
1750 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1752 if(m_items[i])
1753 m_items[i]->AddToWorld();
1757 void Player::RemoveFromWorld()
1759 // cleanup
1760 if(IsInWorld())
1762 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1763 Uncharm();
1764 UnsummonAllTotems();
1765 RemoveMiniPet();
1768 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1770 if(m_items[i])
1771 m_items[i]->RemoveFromWorld();
1774 ///- Do not add/remove the player from the object storage
1775 ///- It will crash when updating the ObjectAccessor
1776 ///- The player should only be removed when logging out
1777 Unit::RemoveFromWorld();
1780 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1782 float addRage;
1784 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1786 if(attacker)
1788 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1790 // talent who gave more rage on attack
1791 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1793 else
1795 addRage = damage/rageconversion*2.5;
1797 // Berserker Rage effect
1798 if(HasAura(18499,0))
1799 addRage *= 1.3;
1802 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1804 ModifyPower(POWER_RAGE, uint32(addRage*10));
1807 void Player::RegenerateAll()
1809 if (m_regenTimer != 0)
1810 return;
1811 uint32 regenDelay = 2000;
1813 // Not in combat or they have regeneration
1814 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1815 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1817 RegenerateHealth();
1818 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1820 Regenerate(POWER_RAGE);
1821 if(getClass() == CLASS_DEATH_KNIGHT)
1822 Regenerate(POWER_RUNIC_POWER);
1826 Regenerate( POWER_ENERGY );
1828 Regenerate( POWER_MANA );
1830 if(getClass() == CLASS_DEATH_KNIGHT)
1831 Regenerate( POWER_RUNE );
1833 m_regenTimer = regenDelay;
1836 void Player::Regenerate(Powers power)
1838 uint32 curValue = GetPower(power);
1839 uint32 maxValue = GetMaxPower(power);
1841 float addvalue = 0.0f;
1843 switch (power)
1845 case POWER_MANA:
1847 bool recentCast = IsUnderLastManaUseEffect();
1848 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1849 if (recentCast)
1851 // Mangos Updates Mana in intervals of 2s, which is correct
1852 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1854 else
1856 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1858 } break;
1859 case POWER_RAGE: // Regenerate rage
1861 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1862 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1863 } break;
1864 case POWER_ENERGY: // Regenerate energy (rogue)
1865 addvalue = 20;
1866 break;
1867 case POWER_RUNIC_POWER:
1869 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1870 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1871 } break;
1872 case POWER_RUNE:
1874 for(uint32 i = 0; i < MAX_RUNES; ++i)
1875 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1876 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1877 } break;
1878 case POWER_FOCUS:
1879 case POWER_HAPPINESS:
1880 case POWER_HEALTH:
1881 break;
1884 // Mana regen calculated in Player::UpdateManaRegen()
1885 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1886 if(power != POWER_MANA)
1888 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1889 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1890 if ((*i)->GetModifier()->m_miscvalue == power)
1891 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1894 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1896 curValue += uint32(addvalue);
1897 if (curValue > maxValue)
1898 curValue = maxValue;
1900 else
1902 if(curValue <= uint32(addvalue))
1903 curValue = 0;
1904 else
1905 curValue -= uint32(addvalue);
1907 SetPower(power, curValue);
1910 void Player::RegenerateHealth()
1912 uint32 curValue = GetHealth();
1913 uint32 maxValue = GetMaxHealth();
1915 if (curValue >= maxValue) return;
1917 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1919 float addvalue = 0.0f;
1921 // polymorphed case
1922 if ( IsPolymorphed() )
1923 addvalue = GetMaxHealth()/3;
1924 // normal regen case (maybe partly in combat case)
1925 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1927 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1928 if (!isInCombat())
1930 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1931 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1932 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1934 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1935 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1937 if(!IsStandState())
1938 addvalue *= 1.5;
1941 // always regeneration bonus (including combat)
1942 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1944 if(addvalue < 0)
1945 addvalue = 0;
1947 ModifyHealth(int32(addvalue));
1950 bool Player::CanInteractWithNPCs(bool alive) const
1952 if(alive && !isAlive())
1953 return false;
1954 if(isInFlight())
1955 return false;
1957 return true;
1960 Creature*
1961 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1963 // unit checks
1964 if (!guid)
1965 return NULL;
1967 if(!IsInWorld())
1968 return NULL;
1970 // exist (we need look pets also for some interaction (quest/etc)
1971 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1972 if (!unit)
1973 return NULL;
1975 // player check
1976 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1977 return NULL;
1979 // appropriate npc type
1980 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1981 return NULL;
1983 // alive or spirit healer
1984 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1985 return NULL;
1987 // not allow interaction under control, but allow with own pets
1988 if(unit->GetCharmerGUID())
1989 return NULL;
1991 // not enemy
1992 if( unit->IsHostileTo(this))
1993 return NULL;
1995 // not unfriendly
1996 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1997 if(factionTemplate->faction)
1998 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1999 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2000 return NULL;
2002 // not too far
2003 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2004 return NULL;
2006 return unit;
2009 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2011 if(GameObject *go = GetMap()->GetGameObject(guid))
2013 if(go->GetGoType() == type)
2015 float maxdist;
2016 switch(type)
2018 // TODO: find out how the client calculates the maximal usage distance to spellless working
2019 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2020 case GAMEOBJECT_TYPE_GUILD_BANK:
2021 case GAMEOBJECT_TYPE_MAILBOX:
2022 maxdist = 10.0f;
2023 break;
2024 case GAMEOBJECT_TYPE_FISHINGHOLE:
2025 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2026 break;
2027 default:
2028 maxdist = INTERACTION_DISTANCE;
2029 break;
2032 if (go->IsWithinDistInMap(this, maxdist))
2033 return go;
2035 sLog.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2036 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2039 return NULL;
2042 bool Player::IsUnderWater() const
2044 return IsInWater() &&
2045 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2048 void Player::SetInWater(bool apply)
2050 if(m_isInWater==apply)
2051 return;
2053 //define player in water by opcodes
2054 //move player's guid into HateOfflineList of those mobs
2055 //which can't swim and move guid back into ThreatList when
2056 //on surface.
2057 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2058 m_isInWater = apply;
2060 // remove auras that need water/land
2061 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2063 getHostilRefManager().updateThreatTables();
2066 void Player::SetGameMaster(bool on)
2068 if(on)
2070 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2071 setFaction(35);
2072 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2074 if (Pet* pet = GetPet())
2076 pet->setFaction(35);
2077 pet->getHostilRefManager().setOnlineOfflineState(false);
2080 for (int8 i = 0; i < MAX_TOTEM; ++i)
2081 if(m_TotemSlot[i])
2082 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2083 totem->setFaction(35);
2085 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2086 ResetContestedPvP();
2088 getHostilRefManager().setOnlineOfflineState(false);
2089 CombatStopWithPets();
2091 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2093 else
2095 // restore phase
2096 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2097 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2099 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2100 setFactionForRace(getRace());
2101 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2103 if (Pet* pet = GetPet())
2105 pet->setFaction(getFaction());
2106 pet->getHostilRefManager().setOnlineOfflineState(true);
2109 for (int8 i = 0; i < MAX_TOTEM; ++i)
2110 if(m_TotemSlot[i])
2111 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2112 totem->setFaction(getFaction());
2114 // restore FFA PvP Server state
2115 if(sWorld.IsFFAPvPRealm())
2116 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2118 // restore FFA PvP area state, remove not allowed for GM mounts
2119 UpdateArea(m_areaUpdateId);
2121 getHostilRefManager().setOnlineOfflineState(true);
2124 ObjectAccessor::UpdateVisibilityForPlayer(this);
2127 void Player::SetGMVisible(bool on)
2129 if(on)
2131 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2133 // Reapply stealth/invisibility if active or show if not any
2134 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2135 SetVisibility(VISIBILITY_GROUP_STEALTH);
2136 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2137 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2138 else
2139 SetVisibility(VISIBILITY_ON);
2141 else
2143 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2145 SetAcceptWhispers(false);
2146 SetGameMaster(true);
2148 SetVisibility(VISIBILITY_OFF);
2152 bool Player::IsGroupVisibleFor(Player* p) const
2154 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2156 default: return IsInSameGroupWith(p);
2157 case 1: return IsInSameRaidWith(p);
2158 case 2: return GetTeam()==p->GetTeam();
2162 bool Player::IsInSameGroupWith(Player const* p) const
2164 return p==this || GetGroup() != NULL &&
2165 GetGroup() == p->GetGroup() &&
2166 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2169 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2170 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2171 void Player::UninviteFromGroup()
2173 Group* group = GetGroupInvite();
2174 if(!group)
2175 return;
2177 group->RemoveInvite(this);
2179 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2181 if(group->IsCreated())
2183 group->Disband(true);
2184 objmgr.RemoveGroup(group);
2186 else
2187 group->RemoveAllInvites();
2189 delete group;
2193 void Player::RemoveFromGroup(Group* group, uint64 guid)
2195 if(group)
2197 if (group->RemoveMember(guid, 0) <= 1)
2199 // group->Disband(); already disbanded in RemoveMember
2200 objmgr.RemoveGroup(group);
2201 delete group;
2202 // removemember sets the player's group pointer to NULL
2207 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2209 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2210 data << uint64(victim ? victim->GetGUID() : 0); // guid
2211 data << uint32(GivenXP+RestXP); // given experience
2212 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2213 if(victim)
2215 data << uint32(GivenXP); // experience without rested bonus
2216 data << float(1); // 1 - none 0 - 100% group bonus output
2218 data << uint8(0); // new 2.4.0
2219 GetSession()->SendPacket(&data);
2222 void Player::GiveXP(uint32 xp, Unit* victim)
2224 if ( xp < 1 )
2225 return;
2227 if(!isAlive())
2228 return;
2230 uint32 level = getLevel();
2232 // XP to money conversion processed in Player::RewardQuest
2233 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2234 return;
2236 // handle SPELL_AURA_MOD_XP_PCT auras
2237 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2238 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2239 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2241 // XP resting bonus for kill
2242 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2244 SendLogXPGain(xp,victim,rested_bonus_xp);
2246 uint32 curXP = GetUInt32Value(PLAYER_XP);
2247 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2248 uint32 newXP = curXP + xp + rested_bonus_xp;
2250 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2252 newXP -= nextLvlXP;
2254 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2255 GiveLevel(level + 1);
2257 level = getLevel();
2258 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2261 SetUInt32Value(PLAYER_XP, newXP);
2264 // Update player to next level
2265 // Current player experience not update (must be update by caller)
2266 void Player::GiveLevel(uint32 level)
2268 if ( level == getLevel() )
2269 return;
2271 PlayerLevelInfo info;
2272 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2274 PlayerClassLevelInfo classInfo;
2275 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2277 // send levelup info to client
2278 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2279 data << uint32(level);
2280 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2281 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2282 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2283 data << uint32(0);
2284 data << uint32(0);
2285 data << uint32(0);
2286 data << uint32(0);
2287 data << uint32(0);
2288 data << uint32(0);
2289 // end for
2290 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2291 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2293 GetSession()->SendPacket(&data);
2295 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2297 //update level, max level of skills
2298 if(getLevel()!= level)
2299 m_Played_time[1] = 0; // Level Played Time reset
2300 SetLevel(level);
2301 UpdateSkillsForLevel ();
2303 // save base values (bonuses already included in stored stats
2304 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2305 SetCreateStat(Stats(i), info.stats[i]);
2307 SetCreateHealth(classInfo.basehealth);
2308 SetCreateMana(classInfo.basemana);
2310 InitTalentForLevel();
2311 InitTaxiNodesForLevel();
2312 InitGlyphsForLevel();
2314 UpdateAllStats();
2316 // set current level health and mana/energy to maximum after applying all mods.
2317 SetHealth(GetMaxHealth());
2318 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2319 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2320 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2321 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2322 SetPower(POWER_FOCUS, 0);
2323 SetPower(POWER_HAPPINESS, 0);
2325 // update level to hunter/summon pet
2326 if (Pet* pet = GetPet())
2327 pet->SynchronizeLevelWithOwner();
2329 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2332 void Player::InitTalentForLevel()
2334 uint32 level = getLevel();
2335 // talents base at level diff ( talents = level - 9 but some can be used already)
2336 if(level < 10)
2338 // Remove all talent points
2339 if(m_usedTalentCount > 0) // Free any used talents
2341 resetTalents(true);
2342 SetFreeTalentPoints(0);
2345 else
2347 uint32 talentPointsForLevel = CalculateTalentsPoints();
2349 // if used more that have then reset
2350 if(m_usedTalentCount > talentPointsForLevel)
2352 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2353 resetTalents(true);
2354 else
2355 SetFreeTalentPoints(0);
2357 // else update amount of free points
2358 else
2359 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2362 if(!GetSession()->PlayerLoading())
2363 SendTalentsInfoData(false); // update at client
2366 void Player::InitStatsForLevel(bool reapplyMods)
2368 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2369 _RemoveAllStatBonuses();
2371 PlayerClassLevelInfo classInfo;
2372 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2374 PlayerLevelInfo info;
2375 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2377 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2378 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2380 UpdateSkillsForLevel ();
2382 // set default cast time multiplier
2383 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2385 // reset size before reapply auras
2386 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2388 // save base values (bonuses already included in stored stats
2389 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2390 SetCreateStat(Stats(i), info.stats[i]);
2392 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2393 SetStat(Stats(i), info.stats[i]);
2395 SetCreateHealth(classInfo.basehealth);
2397 //set create powers
2398 SetCreateMana(classInfo.basemana);
2400 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2402 InitStatBuffMods();
2404 //reset rating fields values
2405 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2406 SetUInt32Value(index, 0);
2408 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2409 for (int i = 0; i < 7; ++i)
2411 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2412 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2413 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2416 //reset attack power, damage and attack speed fields
2417 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2418 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2419 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2421 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2422 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2423 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2424 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2425 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2426 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2428 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2429 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2430 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2431 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2432 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2433 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2435 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2436 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2437 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2438 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2440 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2441 for (uint8 i = 0; i < 7; ++i)
2442 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2444 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2445 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2446 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2448 // Dodge percentage
2449 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2451 // set armor (resistance 0) to original value (create_agility*2)
2452 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2453 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2454 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2455 // set other resistance to original value (0)
2456 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2458 SetResistance(SpellSchools(i), 0);
2459 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2460 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2463 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2464 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2465 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2467 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2468 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2470 // Reset no reagent cost field
2471 for(int i = 0; i < 3; ++i)
2472 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2473 // Init data for form but skip reapply item mods for form
2474 InitDataForForm(reapplyMods);
2476 // save new stats
2477 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2478 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2480 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2482 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2483 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2485 // cleanup unit flags (will be re-applied if need at aura load).
2486 RemoveFlag( UNIT_FIELD_FLAGS,
2487 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2488 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2489 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2490 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2491 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2492 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2494 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2496 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2497 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2499 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2500 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2502 // restore if need some important flags
2503 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2505 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2506 _ApplyAllStatBonuses();
2508 // set current level health and mana/energy to maximum after applying all mods.
2509 SetHealth(GetMaxHealth());
2510 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2511 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2512 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2513 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2514 SetPower(POWER_FOCUS, 0);
2515 SetPower(POWER_HAPPINESS, 0);
2516 SetPower(POWER_RUNIC_POWER, 0);
2518 // update level to hunter/summon pet
2519 if (Pet* pet = GetPet())
2520 pet->SynchronizeLevelWithOwner();
2523 void Player::SendInitialSpells()
2525 time_t curTime = time(NULL);
2526 time_t infTime = curTime + MONTH/2;
2528 uint16 spellCount = 0;
2530 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2531 data << uint8(0);
2533 size_t countPos = data.wpos();
2534 data << uint16(spellCount); // spell count placeholder
2536 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2538 if(itr->second->state == PLAYERSPELL_REMOVED)
2539 continue;
2541 if(!itr->second->active || itr->second->disabled)
2542 continue;
2544 data << uint32(itr->first);
2545 data << uint16(0); // it's not slot id
2547 spellCount +=1;
2550 data.put<uint16>(countPos,spellCount); // write real count value
2552 uint16 spellCooldowns = m_spellCooldowns.size();
2553 data << uint16(spellCooldowns);
2554 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2556 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2557 if(!sEntry)
2558 continue;
2560 // not send infinity cooldown
2561 if(itr->second.end > infTime)
2562 continue;
2564 data << uint32(itr->first);
2566 time_t cooldown = 0;
2567 if(itr->second.end > curTime)
2568 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2570 data << uint16(itr->second.itemid); // cast item id
2571 data << uint16(sEntry->Category); // spell category
2572 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2574 data << uint32(0); // cooldown
2575 data << uint32(cooldown); // category cooldown
2577 else
2579 data << uint32(cooldown); // cooldown
2580 data << uint32(0); // category cooldown
2584 GetSession()->SendPacket(&data);
2586 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2589 void Player::RemoveMail(uint32 id)
2591 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2593 if ((*itr)->messageID == id)
2595 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2596 m_mail.erase(itr);
2597 return;
2602 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2604 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2605 data << (uint32) mailId;
2606 data << (uint32) mailAction;
2607 data << (uint32) mailError;
2608 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2609 data << (uint32) equipError;
2610 else if( mailAction == MAIL_ITEM_TAKEN )
2612 data << (uint32) item_guid; // item guid low?
2613 data << (uint32) item_count; // item count?
2615 GetSession()->SendPacket(&data);
2618 void Player::SendNewMail()
2620 // deliver undelivered mail
2621 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2622 data << (uint32) 0;
2623 GetSession()->SendPacket(&data);
2626 void Player::UpdateNextMailTimeAndUnreads()
2628 // calculate next delivery time (min. from non-delivered mails
2629 // and recalculate unReadMail
2630 time_t cTime = time(NULL);
2631 m_nextMailDelivereTime = 0;
2632 unReadMails = 0;
2633 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2635 if((*itr)->deliver_time > cTime)
2637 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2638 m_nextMailDelivereTime = (*itr)->deliver_time;
2640 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2641 ++unReadMails;
2645 void Player::AddNewMailDeliverTime(time_t deliver_time)
2647 if(deliver_time <= time(NULL)) // ready now
2649 ++unReadMails;
2650 SendNewMail();
2652 else // not ready and no have ready mails
2654 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2655 m_nextMailDelivereTime = deliver_time;
2659 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2661 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2662 if (!spellInfo)
2664 // do character spell book cleanup (all characters)
2665 if(!IsInWorld() && !learning) // spell load case
2667 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2668 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2670 else
2671 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2673 return false;
2676 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2678 // do character spell book cleanup (all characters)
2679 if(!IsInWorld() && !learning) // spell load case
2681 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2682 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2684 else
2685 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2687 return false;
2690 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2692 bool dependent_set = false;
2693 bool disabled_case = false;
2694 bool superceded_old = false;
2696 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2697 if (itr != m_spells.end())
2699 uint32 next_active_spell_id = 0;
2700 // fix activate state for non-stackable low rank (and find next spell for !active case)
2701 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2703 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2704 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2706 if(HasSpell(next_itr->second))
2708 // high rank already known so this must !active
2709 active = false;
2710 next_active_spell_id = next_itr->second;
2711 break;
2716 // not do anything if already known in expected state
2717 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2718 itr->second->dependent == dependent && itr->second->disabled == disabled)
2720 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2721 itr->second->state = PLAYERSPELL_UNCHANGED;
2723 return false;
2726 // dependent spell known as not dependent, overwrite state
2727 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2729 itr->second->dependent = dependent;
2730 if (itr->second->state != PLAYERSPELL_NEW)
2731 itr->second->state = PLAYERSPELL_CHANGED;
2732 dependent_set = true;
2735 // update active state for known spell
2736 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2738 itr->second->active = active;
2740 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2741 itr->second->state = PLAYERSPELL_UNCHANGED;
2742 else if(itr->second->state != PLAYERSPELL_NEW)
2743 itr->second->state = PLAYERSPELL_CHANGED;
2745 if(active)
2747 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2748 CastSpell (this,spell_id,true);
2750 else if(IsInWorld())
2752 if(next_active_spell_id)
2754 // update spell ranks in spellbook and action bar
2755 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2756 data << uint32(spell_id);
2757 data << uint32(next_active_spell_id);
2758 GetSession()->SendPacket( &data );
2760 else
2762 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2763 data << uint32(spell_id);
2764 GetSession()->SendPacket(&data);
2768 return active; // learn (show in spell book if active now)
2771 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2773 if(itr->second->state != PLAYERSPELL_NEW)
2774 itr->second->state = PLAYERSPELL_CHANGED;
2775 itr->second->disabled = disabled;
2777 if(disabled)
2778 return false;
2780 disabled_case = true;
2782 else switch(itr->second->state)
2784 case PLAYERSPELL_UNCHANGED: // known saved spell
2785 return false;
2786 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2788 delete itr->second;
2789 m_spells.erase(itr);
2790 state = PLAYERSPELL_CHANGED;
2791 break; // need re-add
2793 default: // known not saved yet spell (new or modified)
2795 // can be in case spell loading but learned at some previous spell loading
2796 if(!IsInWorld() && !learning && !dependent_set)
2797 itr->second->state = PLAYERSPELL_UNCHANGED;
2799 return false;
2804 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2806 // talent: unlearn all other talent ranks (high and low)
2807 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2809 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2811 for(int i=0; i < MAX_TALENT_RANK; ++i)
2813 // skip learning spell and no rank spell case
2814 uint32 rankSpellId = talentInfo->RankID[i];
2815 if(!rankSpellId || rankSpellId==spell_id)
2816 continue;
2818 removeSpell(rankSpellId);
2822 // non talent spell: learn low ranks (recursive call)
2823 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2825 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2826 addSpell(prev_spell,active,true,true,disabled);
2827 else // at normal learning
2828 learnSpell(prev_spell,true);
2831 PlayerSpell *newspell = new PlayerSpell;
2832 newspell->state = state;
2833 newspell->active = active;
2834 newspell->dependent = dependent;
2835 newspell->disabled = disabled;
2837 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2838 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2840 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2842 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2843 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2844 if(!i_spellInfo) continue;
2846 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2848 if(itr2->second->active)
2850 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2852 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2854 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2855 data << uint32(itr2->first);
2856 data << uint32(spell_id);
2857 GetSession()->SendPacket( &data );
2860 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2861 itr2->second->active = false;
2862 if(itr2->second->state != PLAYERSPELL_NEW)
2863 itr2->second->state = PLAYERSPELL_CHANGED;
2864 superceded_old = true; // new spell replace old in action bars and spell book.
2866 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2868 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2870 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2871 data << uint32(spell_id);
2872 data << uint32(itr2->first);
2873 GetSession()->SendPacket( &data );
2876 // mark new spell as disable (not learned yet for client and will not learned)
2877 newspell->active = false;
2878 if(newspell->state != PLAYERSPELL_NEW)
2879 newspell->state = PLAYERSPELL_CHANGED;
2886 m_spells[spell_id] = newspell;
2888 // return false if spell disabled
2889 if (newspell->disabled)
2890 return false;
2893 uint32 talentCost = GetTalentSpellCost(spell_id);
2895 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2896 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2897 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2899 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2900 CastSpell(this, spell_id, true);
2902 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2903 else if (IsPassiveSpell(spell_id))
2905 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2906 CastSpell(this, spell_id, true);
2908 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2910 CastSpell(this, spell_id, true);
2911 return false;
2914 // update used talent points count
2915 m_usedTalentCount += talentCost;
2917 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2918 if(uint32 freeProfs = GetFreePrimaryProfessionPoints())
2920 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2921 SetFreePrimaryProfessions(freeProfs-1);
2924 // add dependent skills
2925 uint16 maxskill = GetMaxSkillValueForLevel();
2927 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2929 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2930 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2932 if(spellLearnSkill)
2934 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2935 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2937 if(skill_value < spellLearnSkill->value)
2938 skill_value = spellLearnSkill->value;
2940 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2942 if(skill_max_value < new_skill_max_value)
2943 skill_max_value = new_skill_max_value;
2945 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2947 else
2949 // not ranked skills
2950 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2952 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2953 if(!pSkill)
2954 continue;
2956 if(HasSkill(pSkill->id))
2957 continue;
2959 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2960 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2961 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2963 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2965 case SKILL_RANGE_LANGUAGE:
2966 SetSkill(pSkill->id, 300, 300 );
2967 break;
2968 case SKILL_RANGE_LEVEL:
2969 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2970 break;
2971 case SKILL_RANGE_MONO:
2972 SetSkill(pSkill->id, 1, 1 );
2973 break;
2974 default:
2975 break;
2981 // learn dependent spells
2982 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2983 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2985 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2987 if(!itr2->second.autoLearned)
2989 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2990 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2991 else // at normal learning
2992 learnSpell(itr2->second.spell,true);
2996 if(!GetSession()->PlayerLoading())
2998 // not ranked skills
2999 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3002 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3005 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3008 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3009 return active && !disabled && !superceded_old;
3012 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3014 bool need_cast = false;
3016 switch(spellInfo->Id)
3018 // some spells not have stance data expected cast at form change or present
3019 case 5420: need_cast = (m_form == FORM_TREE); break;
3020 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
3021 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
3022 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
3023 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
3024 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
3025 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
3026 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
3027 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3028 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3029 // another spells have proper stance data
3030 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
3033 //Check CasterAuraStates
3034 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3037 void Player::learnSpell(uint32 spell_id, bool dependent)
3039 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3041 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3042 bool active = disabled ? itr->second->active : true;
3044 bool learning = addSpell(spell_id,active,true,dependent,false);
3046 // learn all disabled higher ranks (recursive)
3047 if(disabled)
3049 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3050 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3052 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3053 if (iter != m_spells.end() && iter->second->disabled)
3054 learnSpell(i->second,false);
3058 // prevent duplicated entires in spell book, also not send if not in world (loading)
3059 if(!learning || !IsInWorld ())
3060 return;
3062 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3063 data << uint32(spell_id);
3064 GetSession()->SendPacket(&data);
3067 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3069 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3070 if (itr == m_spells.end())
3071 return;
3073 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3074 return;
3076 // unlearn non talent higher ranks (recursive)
3077 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3078 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3079 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3080 removeSpell(itr2->second,disabled);
3082 // re-search, it can be corrupted in prev loop
3083 itr = m_spells.find(spell_id);
3084 if (itr == m_spells.end())
3085 return; // already unleared
3087 bool cur_active = itr->second->active;
3088 bool cur_dependent = itr->second->dependent;
3090 if (disabled)
3092 itr->second->disabled = disabled;
3093 if(itr->second->state != PLAYERSPELL_NEW)
3094 itr->second->state = PLAYERSPELL_CHANGED;
3096 else
3098 if(itr->second->state == PLAYERSPELL_NEW)
3100 delete itr->second;
3101 m_spells.erase(itr);
3103 else
3104 itr->second->state = PLAYERSPELL_REMOVED;
3107 RemoveAurasDueToSpell(spell_id);
3109 // remove pet auras
3110 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3111 RemovePetAura(petSpell);
3113 // free talent points
3114 uint32 talentCosts = GetTalentSpellCost(spell_id);
3115 if(talentCosts > 0)
3117 if(talentCosts < m_usedTalentCount)
3118 m_usedTalentCount -= talentCosts;
3119 else
3120 m_usedTalentCount = 0;
3123 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3124 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3126 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3127 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3128 SetFreePrimaryProfessions(freeProfs);
3131 // remove dependent skill
3132 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3133 if(spellLearnSkill)
3135 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3136 if(!prev_spell) // first rank, remove skill
3137 SetSkill(spellLearnSkill->skill,0,0);
3138 else
3140 // search prev. skill setting by spell ranks chain
3141 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3142 while(!prevSkill && prev_spell)
3144 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3145 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3148 if(!prevSkill) // not found prev skill setting, remove skill
3149 SetSkill(spellLearnSkill->skill,0,0);
3150 else // set to prev. skill setting values
3152 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3153 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3155 if(skill_value > prevSkill->value)
3156 skill_value = prevSkill->value;
3158 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3160 if(skill_max_value > new_skill_max_value)
3161 skill_max_value = new_skill_max_value;
3163 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3168 else
3170 // not ranked skills
3171 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3172 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3174 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3176 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3177 if(!pSkill)
3178 continue;
3180 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3181 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3182 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3184 // not reset skills for professions and racial abilities
3185 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3186 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3187 continue;
3189 SetSkill(pSkill->id, 0, 0 );
3194 // remove dependent spells
3195 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3196 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3198 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3199 removeSpell(itr2->second.spell, disabled);
3201 // activate lesser rank in spellbook/action bar, and cast it if need
3202 bool prev_activate = false;
3204 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3206 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3208 // if talent then lesser rank also talent and need learn
3209 if(talentCosts)
3210 learnSpell (prev_id,false);
3211 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3212 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3214 // need manually update dependence state (learn spell ignore like attempts)
3215 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3216 if (prev_itr != m_spells.end())
3218 if(prev_itr->second->dependent != cur_dependent)
3220 prev_itr->second->dependent = cur_dependent;
3221 if(prev_itr->second->state != PLAYERSPELL_NEW)
3222 prev_itr->second->state = PLAYERSPELL_CHANGED;
3225 // now re-learn if need re-activate
3226 if(cur_active && !prev_itr->second->active)
3228 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3230 if(update_action_bar_for_low_rank)
3232 // downgrade spell ranks in spellbook and action bar
3233 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3234 data << uint32(spell_id);
3235 data << uint32(prev_id);
3236 GetSession()->SendPacket( &data );
3237 prev_activate = true;
3245 // remove from spell book if not replaced by lesser rank
3246 if(!prev_activate)
3248 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3249 data << uint32(spell_id);
3250 GetSession()->SendPacket(&data);
3254 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3256 m_spellCooldowns.erase(spell_id);
3258 if(update)
3259 SendClearCooldown(spell_id, this);
3262 void Player::RemoveArenaSpellCooldowns()
3264 // remove cooldowns on spells that has < 15 min CD
3265 SpellCooldowns::iterator itr, next;
3266 // iterate spell cooldowns
3267 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3269 next = itr;
3270 ++next;
3271 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3272 // check if spellentry is present and if the cooldown is less than 15 mins
3273 if( entry &&
3274 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3275 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3277 // remove & notify
3278 RemoveSpellCooldown(itr->first, true);
3283 void Player::RemoveAllSpellCooldown()
3285 if(!m_spellCooldowns.empty())
3287 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3288 SendClearCooldown(itr->first, this);
3290 m_spellCooldowns.clear();
3294 void Player::_LoadSpellCooldowns(QueryResult *result)
3296 // some cooldowns can be already set at aura loading...
3298 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3300 if(result)
3302 time_t curTime = time(NULL);
3306 Field *fields = result->Fetch();
3308 uint32 spell_id = fields[0].GetUInt32();
3309 uint32 item_id = fields[1].GetUInt32();
3310 time_t db_time = (time_t)fields[2].GetUInt64();
3312 if(!sSpellStore.LookupEntry(spell_id))
3314 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3315 continue;
3318 // skip outdated cooldown
3319 if(db_time <= curTime)
3320 continue;
3322 AddSpellCooldown(spell_id, item_id, db_time);
3324 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3326 while( result->NextRow() );
3328 delete result;
3332 void Player::_SaveSpellCooldowns()
3334 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3336 time_t curTime = time(NULL);
3337 time_t infTime = curTime + MONTH/2;
3339 // remove outdated and save active
3340 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3342 if(itr->second.end <= curTime)
3343 m_spellCooldowns.erase(itr++);
3344 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3346 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" UI64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3347 ++itr;
3349 else
3350 ++itr;
3354 uint32 Player::resetTalentsCost() const
3356 // The first time reset costs 1 gold
3357 if(m_resetTalentsCost < 1*GOLD)
3358 return 1*GOLD;
3359 // then 5 gold
3360 else if(m_resetTalentsCost < 5*GOLD)
3361 return 5*GOLD;
3362 // After that it increases in increments of 5 gold
3363 else if(m_resetTalentsCost < 10*GOLD)
3364 return 10*GOLD;
3365 else
3367 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3368 if(months > 0)
3370 // This cost will be reduced by a rate of 5 gold per month
3371 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3372 // to a minimum of 10 gold.
3373 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3375 else
3377 // After that it increases in increments of 5 gold
3378 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3379 // until it hits a cap of 50 gold.
3380 if(new_cost > 50*GOLD)
3381 new_cost = 50*GOLD;
3382 return new_cost;
3387 bool Player::resetTalents(bool no_cost)
3389 // not need after this call
3390 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3391 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3393 uint32 talentPointsForLevel = CalculateTalentsPoints();
3395 if (m_usedTalentCount == 0)
3397 SetFreeTalentPoints(talentPointsForLevel);
3398 return false;
3401 uint32 cost = 0;
3403 if(!no_cost)
3405 cost = resetTalentsCost();
3407 if (GetMoney() < cost)
3409 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3410 return false;
3414 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3416 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3418 if (!talentInfo) continue;
3420 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3422 if(!talentTabInfo)
3423 continue;
3425 // unlearn only talents for character class
3426 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3427 // to prevent unexpected lost normal learned spell skip another class talents
3428 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3429 continue;
3431 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3433 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3435 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3437 ++itr;
3438 continue;
3441 // remove learned spells (all ranks)
3442 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3444 // unlearn if first rank is talent or learned by talent
3445 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3447 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3448 itr = GetSpellMap().begin();
3449 continue;
3451 else
3452 ++itr;
3457 SetFreeTalentPoints(talentPointsForLevel);
3459 if(!no_cost)
3461 ModifyMoney(-(int32)cost);
3462 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3463 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3465 m_resetTalentsCost = cost;
3466 m_resetTalentsTime = time(NULL);
3469 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3470 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3471 /* when prev line will dropped use next line
3472 if(Pet* pet = GetPet())
3474 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3475 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3480 if(m_canTitanGrip)
3482 m_canTitanGrip = false;
3483 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3484 AutoUnequipOffhandIfNeed();
3487 return true;
3490 Mail* Player::GetMail(uint32 id)
3492 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3494 if ((*itr)->messageID == id)
3496 return (*itr);
3499 return NULL;
3502 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3504 if(target == this)
3506 Object::_SetCreateBits(updateMask, target);
3508 else
3510 for(uint16 index = 0; index < m_valuesCount; index++)
3512 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3513 updateMask->SetBit(index);
3518 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3520 if(target == this)
3522 Object::_SetUpdateBits(updateMask, target);
3524 else
3526 Object::_SetUpdateBits(updateMask, target);
3527 *updateMask &= updateVisualBits;
3531 void Player::InitVisibleBits()
3533 updateVisualBits.SetCount(PLAYER_END);
3535 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3536 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3537 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3538 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3539 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3540 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3541 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3542 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3543 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3544 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3545 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3546 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3547 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3548 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3549 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3550 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3551 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3552 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3553 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3554 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3555 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3556 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3557 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3558 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3559 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3560 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3561 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3562 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3563 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3564 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3565 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3566 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3567 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3568 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3569 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3570 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3571 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3572 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3573 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3574 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3575 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3576 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3577 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3578 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3579 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3580 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3581 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3582 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3583 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3584 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3585 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3586 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3587 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3588 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3589 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3591 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3592 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3593 updateVisualBits.SetBit(PLAYER_FLAGS);
3594 updateVisualBits.SetBit(PLAYER_GUILDID);
3595 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3596 updateVisualBits.SetBit(PLAYER_BYTES);
3597 updateVisualBits.SetBit(PLAYER_BYTES_2);
3598 updateVisualBits.SetBit(PLAYER_BYTES_3);
3599 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3600 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3602 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3603 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3604 updateVisualBits.SetBit(i);
3606 // Players visible items are not inventory stuff
3607 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3609 uint32 offset = i * 2;
3611 // item entry
3612 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3613 // enchant
3614 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3617 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3620 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3622 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3624 if(m_items[i] == NULL)
3625 continue;
3627 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3630 if(target == this)
3632 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3634 if(m_items[i] == NULL)
3635 continue;
3637 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3639 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3641 if(m_items[i] == NULL)
3642 continue;
3644 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3648 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3651 void Player::DestroyForPlayer( Player *target ) const
3653 Unit::DestroyForPlayer( target );
3655 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3657 if(m_items[i] == NULL)
3658 continue;
3660 m_items[i]->DestroyForPlayer( target );
3663 if(target == this)
3665 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3667 if(m_items[i] == NULL)
3668 continue;
3670 m_items[i]->DestroyForPlayer( target );
3672 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3674 if(m_items[i] == NULL)
3675 continue;
3677 m_items[i]->DestroyForPlayer( target );
3682 bool Player::HasSpell(uint32 spell) const
3684 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3685 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3686 !itr->second->disabled);
3689 bool Player::HasActiveSpell(uint32 spell) const
3691 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3692 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3693 itr->second->active && !itr->second->disabled);
3696 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3698 if (!trainer_spell)
3699 return TRAINER_SPELL_RED;
3701 if (!trainer_spell->learnedSpell)
3702 return TRAINER_SPELL_RED;
3704 // known spell
3705 if(HasSpell(trainer_spell->learnedSpell))
3706 return TRAINER_SPELL_GRAY;
3708 // check race/class requirement
3709 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3710 return TRAINER_SPELL_RED;
3712 // check level requirement
3713 if(getLevel() < trainer_spell->reqLevel)
3714 return TRAINER_SPELL_RED;
3716 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3718 // check prev.rank requirement
3719 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3720 return TRAINER_SPELL_RED;
3722 // check additional spell requirement
3723 if(spell_chain->req && !HasSpell(spell_chain->req))
3724 return TRAINER_SPELL_RED;
3727 // check skill requirement
3728 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3729 return TRAINER_SPELL_RED;
3731 // exist, already checked at loading
3732 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3734 // secondary prof. or not prof. spell
3735 uint32 skill = spell->EffectMiscValue[1];
3737 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3738 return TRAINER_SPELL_GREEN;
3740 // check primary prof. limit
3741 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3742 return TRAINER_SPELL_GREEN_DISABLED;
3744 return TRAINER_SPELL_GREEN;
3747 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3749 uint32 guid = GUID_LOPART(playerguid);
3751 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3752 // bones will be deleted by corpse/bones deleting thread shortly
3753 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3755 // remove from guild
3756 uint32 guildId = GetGuildIdFromDB(playerguid);
3757 if(guildId != 0)
3759 Guild* guild = objmgr.GetGuildById(guildId);
3760 if(guild)
3761 guild->DelMember(guid);
3764 // remove from arena teams
3765 LeaveAllArenaTeams(playerguid);
3767 // the player was uninvited already on logout so just remove from group
3768 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3769 if(resultGroup)
3771 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3772 delete resultGroup;
3773 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3774 if(group)
3776 RemoveFromGroup(group, playerguid);
3780 // remove signs from petitions (also remove petitions if owner);
3781 RemovePetitionsAndSigns(playerguid, 10);
3783 // return back all mails with COD and Item 0 1 2 3 4 5 6
3784 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);
3785 if(resultMail)
3789 Field *fields = resultMail->Fetch();
3791 uint32 mail_id = fields[0].GetUInt32();
3792 uint16 mailTemplateId= fields[1].GetUInt16();
3793 uint32 sender = fields[2].GetUInt32();
3794 std::string subject = fields[3].GetCppString();
3795 uint32 itemTextId = fields[4].GetUInt32();
3796 uint32 money = fields[5].GetUInt32();
3797 bool has_items = fields[6].GetBool();
3799 //we can return mail now
3800 //so firstly delete the old one
3801 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3803 MailItemsInfo mi;
3804 if(has_items)
3806 // data needs to be at first place for Item::LoadFromDB
3807 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);
3808 if(resultItems)
3812 Field *fields2 = resultItems->Fetch();
3814 uint32 item_guidlow = fields2[1].GetUInt32();
3815 uint32 item_template = fields2[2].GetUInt32();
3817 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3818 if(!itemProto)
3820 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3821 continue;
3824 Item *pItem = NewItemOrBag(itemProto);
3825 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3827 pItem->FSetState(ITEM_REMOVED);
3828 pItem->SaveToDB(); // it also deletes item object !
3829 continue;
3832 mi.AddItem(item_guidlow, item_template, pItem);
3834 while (resultItems->NextRow());
3836 delete resultItems;
3840 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3842 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3844 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3846 while (resultMail->NextRow());
3848 delete resultMail;
3851 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3852 // Get guids of character's pets, will deleted in transaction
3853 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3855 // NOW we can finally clear other DB data related to character
3856 CharacterDatabase.BeginTransaction();
3857 if (resultPets)
3861 Field *fields3 = resultPets->Fetch();
3862 uint32 petguidlow = fields3[0].GetUInt32();
3863 Pet::DeleteFromDB(petguidlow);
3864 } while (resultPets->NextRow());
3865 delete resultPets;
3868 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3869 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3870 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3871 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3872 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3873 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3874 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3875 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3876 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3877 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3878 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3879 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3880 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3881 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3882 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3883 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3884 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3885 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3886 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3887 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3888 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3889 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3890 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3891 CharacterDatabase.CommitTransaction();
3893 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3894 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3897 void Player::SetMovement(PlayerMovementType pType)
3899 WorldPacket data;
3900 switch(pType)
3902 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3903 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3904 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3905 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3906 default:
3907 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3908 return;
3910 data.append(GetPackGUID());
3911 data << uint32(0);
3912 GetSession()->SendPacket( &data );
3915 /* Preconditions:
3916 - a resurrectable corpse must not be loaded for the player (only bones)
3917 - the player must be in world
3919 void Player::BuildPlayerRepop()
3921 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3922 data.append(GetPackGUID());
3923 GetSession()->SendPacket(&data);
3925 if(getRace() == RACE_NIGHTELF)
3926 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)
3927 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3929 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3930 // there must be SMSG.STOP_MIRROR_TIMER
3931 // there we must send 888 opcode
3933 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3934 if(GetCorpse())
3936 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3937 assert(false);
3940 // create a corpse and place it at the player's location
3941 CreateCorpse();
3942 Corpse *corpse = GetCorpse();
3943 if(!corpse)
3945 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3946 return;
3948 GetMap()->Add(corpse);
3950 // convert player body to ghost
3951 SetHealth( 1 );
3953 SetMovement(MOVE_WATER_WALK);
3954 if(!GetSession()->isLogingOut())
3955 SetMovement(MOVE_UNROOT);
3957 // BG - remove insignia related
3958 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3960 SendCorpseReclaimDelay();
3962 // to prevent cheating
3963 corpse->ResetGhostTime();
3965 StopMirrorTimers(); //disable timers(bars)
3967 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3969 // set and clear other
3970 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3973 void Player::SendDelayResponse(const uint32 ml_seconds)
3975 //FIXME: is this delay time arg really need? 50msec by default in code
3976 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3977 data << (uint32)time(NULL);
3978 data << (uint32)0;
3979 GetSession()->SendPacket( &data );
3982 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3984 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3985 data << uint32(-1);
3986 data << float(0);
3987 data << float(0);
3988 data << float(0);
3989 GetSession()->SendPacket(&data);
3991 // speed change, land walk
3993 // remove death flag + set aura
3994 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3995 if(getRace() == RACE_NIGHTELF)
3996 RemoveAurasDueToSpell(20584); // speed bonuses
3997 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3999 setDeathState(ALIVE);
4001 SetMovement(MOVE_LAND_WALK);
4002 SetMovement(MOVE_UNROOT);
4004 m_deathTimer = 0;
4006 // set health/powers (0- will be set in caller)
4007 if(restore_percent>0.0f)
4009 SetHealth(uint32(GetMaxHealth()*restore_percent));
4010 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4011 SetPower(POWER_RAGE, 0);
4012 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4015 // trigger update zone for alive state zone updates
4016 uint32 newzone, newarea;
4017 GetZoneAndAreaId(newzone,newarea);
4018 UpdateZone(newzone,newarea);
4020 // update visibility
4021 ObjectAccessor::UpdateVisibilityForPlayer(this);
4023 if(!applySickness)
4024 return;
4026 //Characters from level 1-10 are not affected by resurrection sickness.
4027 //Characters from level 11-19 will suffer from one minute of sickness
4028 //for each level they are above 10.
4029 //Characters level 20 and up suffer from ten minutes of sickness.
4030 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4032 if(int32(getLevel()) >= startLevel)
4034 // set resurrection sickness
4035 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4037 // not full duration
4038 if(int32(getLevel()) < startLevel+9)
4040 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4042 for(int i =0; i < 3; ++i)
4044 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4046 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4047 Aur->SendAuraUpdate(false);
4054 void Player::KillPlayer()
4056 SetMovement(MOVE_ROOT);
4058 StopMirrorTimers(); //disable timers(bars)
4060 setDeathState(CORPSE);
4061 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4063 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4064 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4066 // 6 minutes until repop at graveyard
4067 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4069 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4071 // don't create corpse at this moment, player might be falling
4073 // update visibility
4074 ObjectAccessor::UpdateObjectVisibility(this);
4077 void Player::CreateCorpse()
4079 // prevent existence 2 corpse for player
4080 SpawnCorpseBones();
4082 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4084 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4085 SetPvPDeath(false);
4087 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4089 delete corpse;
4090 return;
4093 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4094 _pb = GetUInt32Value(PLAYER_BYTES);
4095 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4097 uint8 race = (uint8)(_uf);
4098 uint8 skin = (uint8)(_pb);
4099 uint8 face = (uint8)(_pb >> 8);
4100 uint8 hairstyle = (uint8)(_pb >> 16);
4101 uint8 haircolor = (uint8)(_pb >> 24);
4102 uint8 facialhair = (uint8)(_pb2);
4104 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4105 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4107 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4108 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4110 uint32 flags = CORPSE_FLAG_UNK2;
4111 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4112 flags |= CORPSE_FLAG_HIDE_HELM;
4113 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4114 flags |= CORPSE_FLAG_HIDE_CLOAK;
4115 if(InBattleGround() && !InArena())
4116 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4117 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4119 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4121 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4123 uint32 iDisplayID;
4124 uint16 iIventoryType;
4125 uint32 _cfi;
4126 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4128 if(m_items[i])
4130 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4131 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4133 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4134 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4138 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4139 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4140 assert(entry);
4141 if(entry->map_type != MAP_BATTLEGROUND)
4142 corpse->SaveToDB();
4144 // register for player, but not show
4145 ObjectAccessor::Instance().AddCorpse(corpse);
4148 void Player::SpawnCorpseBones()
4150 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4151 SaveToDB(); // prevent loading as ghost without corpse
4154 Corpse* Player::GetCorpse() const
4156 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4159 void Player::DurabilityLossAll(double percent, bool inventory)
4161 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4162 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4163 DurabilityLoss(pItem,percent);
4165 if(inventory)
4167 // bags not have durability
4168 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4170 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4171 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4172 DurabilityLoss(pItem,percent);
4174 // keys not have durability
4175 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4177 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4178 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4179 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4180 if(Item* pItem = GetItemByPos( i, j ))
4181 DurabilityLoss(pItem,percent);
4185 void Player::DurabilityLoss(Item* item, double percent)
4187 if(!item )
4188 return;
4190 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4192 if(!pMaxDurability)
4193 return;
4195 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4197 if(pDurabilityLoss < 1 )
4198 pDurabilityLoss = 1;
4200 DurabilityPointsLoss(item,pDurabilityLoss);
4203 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4205 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4206 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4207 DurabilityPointsLoss(pItem,points);
4209 if(inventory)
4211 // bags not have durability
4212 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4214 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4215 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4216 DurabilityPointsLoss(pItem,points);
4218 // keys not have durability
4219 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4221 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4222 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4223 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4224 if(Item* pItem = GetItemByPos( i, j ))
4225 DurabilityPointsLoss(pItem,points);
4229 void Player::DurabilityPointsLoss(Item* item, int32 points)
4231 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4232 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4233 int32 pNewDurability = pOldDurability - points;
4235 if (pNewDurability < 0)
4236 pNewDurability = 0;
4237 else if (pNewDurability > pMaxDurability)
4238 pNewDurability = pMaxDurability;
4240 if (pOldDurability != pNewDurability)
4242 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4243 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4244 _ApplyItemMods(item,item->GetSlot(), false);
4246 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4248 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4249 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4250 _ApplyItemMods(item,item->GetSlot(), true);
4252 item->SetState(ITEM_CHANGED, this);
4256 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4258 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4259 DurabilityPointsLoss(pItem,1);
4262 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4264 uint32 TotalCost = 0;
4265 // equipped, backpack, bags itself
4266 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4267 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4269 // bank, buyback and keys not repaired
4271 // items in inventory bags
4272 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4273 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4274 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4275 return TotalCost;
4278 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4280 Item* item = GetItemByPos(pos);
4282 uint32 TotalCost = 0;
4283 if(!item)
4284 return TotalCost;
4286 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4287 if(!maxDurability)
4288 return TotalCost;
4290 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4292 if(cost)
4294 uint32 LostDurability = maxDurability - curDurability;
4295 if(LostDurability>0)
4297 ItemPrototype const *ditemProto = item->GetProto();
4299 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4300 if(!dcost)
4302 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4303 return TotalCost;
4306 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4307 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4308 if(!dQualitymodEntry)
4310 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4311 return TotalCost;
4314 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4315 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4317 costs = uint32(costs * discountMod);
4319 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4320 costs = 1;
4322 if (guildBank)
4324 if (GetGuildId()==0)
4326 DEBUG_LOG("You are not member of a guild");
4327 return TotalCost;
4330 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4331 if (!pGuild)
4332 return TotalCost;
4334 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4336 DEBUG_LOG("You do not have rights to withdraw for repairs");
4337 return TotalCost;
4340 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4342 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4343 return TotalCost;
4346 if (pGuild->GetGuildBankMoney() < costs)
4348 DEBUG_LOG("There is not enough money in bank");
4349 return TotalCost;
4352 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4353 TotalCost = costs;
4355 else if (GetMoney() < costs)
4357 DEBUG_LOG("You do not have enough money");
4358 return TotalCost;
4360 else
4361 ModifyMoney( -int32(costs) );
4365 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4366 item->SetState(ITEM_CHANGED, this);
4368 // reapply mods for total broken and repaired item if equipped
4369 if(IsEquipmentPos(pos) && !curDurability)
4370 _ApplyItemMods(item,pos & 255, true);
4371 return TotalCost;
4374 void Player::RepopAtGraveyard()
4376 // note: this can be called also when the player is alive
4377 // for example from WorldSession::HandleMovementOpcodes
4379 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4381 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4382 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4384 ResurrectPlayer(0.5f);
4385 SpawnCorpseBones();
4388 WorldSafeLocsEntry const *ClosestGrave = NULL;
4390 // Special handle for battleground maps
4391 if( BattleGround *bg = GetBattleGround() )
4392 ClosestGrave = bg->GetClosestGraveYard(this);
4393 else
4394 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4396 // stop countdown until repop
4397 m_deathTimer = 0;
4399 // if no grave found, stay at the current location
4400 // and don't show spirit healer location
4401 if(ClosestGrave)
4403 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4404 if(isDead()) // not send if alive, because it used in TeleportTo()
4406 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4407 data << ClosestGrave->map_id;
4408 data << ClosestGrave->x;
4409 data << ClosestGrave->y;
4410 data << ClosestGrave->z;
4411 GetSession()->SendPacket(&data);
4416 void Player::JoinedChannel(Channel *c)
4418 m_channels.push_back(c);
4421 void Player::LeftChannel(Channel *c)
4423 m_channels.remove(c);
4426 void Player::CleanupChannels()
4428 while(!m_channels.empty())
4430 Channel* ch = *m_channels.begin();
4431 m_channels.erase(m_channels.begin()); // remove from player's channel list
4432 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4433 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4434 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4437 sLog.outDebug("Player: channels cleaned up!");
4440 void Player::UpdateLocalChannels(uint32 newZone )
4442 if(m_channels.empty())
4443 return;
4445 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4446 if(!current_zone)
4447 return;
4449 ChannelMgr* cMgr = channelMgr(GetTeam());
4450 if(!cMgr)
4451 return;
4453 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4455 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4457 next = i; ++next;
4459 // skip non built-in channels
4460 if(!(*i)->IsConstant())
4461 continue;
4463 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4464 if(!ch)
4465 continue;
4467 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4468 continue;
4470 // new channel
4471 char new_channel_name_buf[100];
4472 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4473 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4475 if((*i)!=new_channel)
4477 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4479 // leave old channel
4480 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4481 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4482 LeftChannel(*i); // remove from player's channel list
4483 cMgr->LeftChannel(name); // delete if empty
4486 sLog.outDebug("Player: channels cleaned up!");
4489 void Player::LeaveLFGChannel()
4491 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4493 if((*i)->IsLFG())
4495 (*i)->Leave(GetGUID());
4496 break;
4501 void Player::UpdateDefense()
4503 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4505 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4507 // update dependent from defense skill part
4508 UpdateDefenseBonusesMod();
4512 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4514 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4516 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4517 return;
4520 float val = 1.0f;
4522 switch(modType)
4524 case FLAT_MOD:
4525 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4526 break;
4527 case PCT_MOD:
4528 if(amount <= -100.0f)
4529 amount = -200.0f;
4531 val = (100.0f + amount) / 100.0f;
4532 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4533 break;
4536 if(!CanModifyStats())
4537 return;
4539 switch(modGroup)
4541 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4542 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4543 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4544 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4545 default: break;
4549 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4551 if(modGroup >= BASEMOD_END || modType > MOD_END)
4553 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4554 return 0.0f;
4557 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4558 return 0.0f;
4560 return m_auraBaseMod[modGroup][modType];
4563 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4565 if(modGroup >= BASEMOD_END)
4567 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4568 return 0.0f;
4571 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4572 return 0.0f;
4574 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4577 uint32 Player::GetShieldBlockValue() const
4579 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4581 value = (value < 0) ? 0 : value;
4583 return uint32(value);
4586 float Player::GetMeleeCritFromAgility()
4588 uint32 level = getLevel();
4589 uint32 pclass = getClass();
4591 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4593 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4594 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4595 if (critBase==NULL || critRatio==NULL)
4596 return 0.0f;
4598 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4599 return crit*100.0f;
4602 float Player::GetDodgeFromAgility()
4604 // Table for base dodge values
4605 float dodge_base[MAX_CLASSES] = {
4606 0.0075f, // Warrior
4607 0.00652f, // Paladin
4608 -0.0545f, // Hunter
4609 -0.0059f, // Rogue
4610 0.03183f, // Priest
4611 0.0114f, // DK
4612 0.0167f, // Shaman
4613 0.034575f, // Mage
4614 0.02011f, // Warlock
4615 0.0f, // ??
4616 -0.0187f // Druid
4618 // Crit/agility to dodge/agility coefficient multipliers
4619 float crit_to_dodge[MAX_CLASSES] = {
4620 1.1f, // Warrior
4621 1.0f, // Paladin
4622 1.6f, // Hunter
4623 2.0f, // Rogue
4624 1.0f, // Priest
4625 1.0f, // DK?
4626 1.0f, // Shaman
4627 1.0f, // Mage
4628 1.0f, // Warlock
4629 0.0f, // ??
4630 1.7f // Druid
4633 uint32 level = getLevel();
4634 uint32 pclass = getClass();
4636 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4638 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4639 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4640 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4641 return 0.0f;
4643 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4644 return dodge*100.0f;
4647 float Player::GetSpellCritFromIntellect()
4649 uint32 level = getLevel();
4650 uint32 pclass = getClass();
4652 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4654 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4655 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4656 if (critBase==NULL || critRatio==NULL)
4657 return 0.0f;
4659 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4660 return crit*100.0f;
4663 float Player::GetRatingCoefficient(CombatRating cr) const
4665 uint32 level = getLevel();
4667 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4669 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4670 if (Rating == NULL)
4671 return 1.0f; // By default use minimum coefficient (not must be called)
4673 return Rating->ratio;
4676 float Player::GetRatingBonusValue(CombatRating cr) const
4678 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4681 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4683 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4684 if (melee>33.0f) melee = 33.0f;
4685 return uint32 (melee * damage /100.0f);
4688 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4690 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4691 if (ranged>33.0f) ranged=33.0f;
4692 return uint32 (ranged * damage /100.0f);
4695 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4697 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4698 // In wow script resilience limited to 33%
4699 if (spell>33.0f)
4700 spell = 33.0f;
4701 return uint32 (spell * damage / 100.0f);
4704 uint32 Player::GetDotDamageReduction(uint32 damage) const
4706 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4707 // Dot resilience not limited (limit it by 100%)
4708 if (spellDot > 100.0f)
4709 spellDot = 100.0f;
4710 return uint32 (spellDot * damage / 100.0f);
4713 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4715 switch (attType)
4717 case BASE_ATTACK:
4718 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4719 case OFF_ATTACK:
4720 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4721 default:
4722 break;
4724 return 0.0f;
4727 float Player::OCTRegenHPPerSpirit()
4729 uint32 level = getLevel();
4730 uint32 pclass = getClass();
4732 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4734 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4735 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4736 if (baseRatio==NULL || moreRatio==NULL)
4737 return 0.0f;
4739 // Formula from PaperDollFrame script
4740 float spirit = GetStat(STAT_SPIRIT);
4741 float baseSpirit = spirit;
4742 if (baseSpirit>50) baseSpirit = 50;
4743 float moreSpirit = spirit - baseSpirit;
4744 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4745 return regen;
4748 float Player::OCTRegenMPPerSpirit()
4750 uint32 level = getLevel();
4751 uint32 pclass = getClass();
4753 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4755 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4756 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4757 if (moreRatio==NULL)
4758 return 0.0f;
4760 // Formula get from PaperDollFrame script
4761 float spirit = GetStat(STAT_SPIRIT);
4762 float regen = spirit * moreRatio->ratio;
4763 return regen;
4766 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4768 m_baseRatingValue[cr]+=(apply ? value : -value);
4770 int32 amount = uint32(m_baseRatingValue[cr]);
4771 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4772 // stat used stored in miscValueB for this aura
4773 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4774 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4775 if ((*i)->GetMiscValue() & (1<<cr))
4776 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4777 if (amount < 0)
4778 amount = 0;
4779 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4781 float RatingCoeffecient = GetRatingCoefficient(cr);
4782 float RatingChange = 0.0f;
4784 bool affectStats = CanModifyStats();
4786 switch (cr)
4788 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4789 case CR_DEFENSE_SKILL:
4790 UpdateDefenseBonusesMod();
4791 break;
4792 case CR_DODGE:
4793 UpdateDodgePercentage();
4794 break;
4795 case CR_PARRY:
4796 UpdateParryPercentage();
4797 break;
4798 case CR_BLOCK:
4799 UpdateBlockPercentage();
4800 break;
4801 case CR_HIT_MELEE:
4802 UpdateMeleeHitChances();
4803 break;
4804 case CR_HIT_RANGED:
4805 UpdateRangedHitChances();
4806 break;
4807 case CR_HIT_SPELL:
4808 UpdateSpellHitChances();
4809 break;
4810 case CR_CRIT_MELEE:
4811 if(affectStats)
4813 UpdateCritPercentage(BASE_ATTACK);
4814 UpdateCritPercentage(OFF_ATTACK);
4816 break;
4817 case CR_CRIT_RANGED:
4818 if(affectStats)
4819 UpdateCritPercentage(RANGED_ATTACK);
4820 break;
4821 case CR_CRIT_SPELL:
4822 if(affectStats)
4823 UpdateAllSpellCritChances();
4824 break;
4825 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4826 case CR_HIT_TAKEN_RANGED:
4827 break;
4828 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4829 break;
4830 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4831 case CR_CRIT_TAKEN_RANGED:
4832 break;
4833 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4834 break;
4835 case CR_HASTE_MELEE:
4836 RatingChange = value / RatingCoeffecient;
4837 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4838 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4839 break;
4840 case CR_HASTE_RANGED:
4841 RatingChange = value / RatingCoeffecient;
4842 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4843 break;
4844 case CR_HASTE_SPELL:
4845 RatingChange = value / RatingCoeffecient;
4846 ApplyCastTimePercentMod(RatingChange,apply);
4847 break;
4848 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4849 case CR_WEAPON_SKILL_OFFHAND:
4850 case CR_WEAPON_SKILL_RANGED:
4851 break;
4852 case CR_EXPERTISE:
4853 if(affectStats)
4855 UpdateExpertise(BASE_ATTACK);
4856 UpdateExpertise(OFF_ATTACK);
4858 break;
4859 case CR_ARMOR_PENETRATION:
4860 break;
4864 void Player::SetRegularAttackTime()
4866 for(int i = 0; i < MAX_ATTACK; ++i)
4868 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4869 if(tmpitem && !tmpitem->IsBroken())
4871 ItemPrototype const *proto = tmpitem->GetProto();
4872 if(proto->Delay)
4873 SetAttackTime(WeaponAttackType(i), proto->Delay);
4874 else
4875 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4880 //skill+step, checking for max value
4881 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4883 if(!skill_id)
4884 return false;
4886 uint16 i=0;
4887 for (; i < PLAYER_MAX_SKILLS; ++i)
4888 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4889 break;
4891 if(i>=PLAYER_MAX_SKILLS)
4892 return false;
4894 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4895 uint32 value = SKILL_VALUE(data);
4896 uint32 max = SKILL_MAX(data);
4898 if ((!max) || (!value) || (value >= max))
4899 return false;
4901 if (value*512 < max*urand(0,512))
4903 uint32 new_value = value+step;
4904 if(new_value > max)
4905 new_value = max;
4907 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4908 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4909 return true;
4912 return false;
4915 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4917 if ( SkillValue >= GrayLevel )
4918 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4919 if ( SkillValue >= GreenLevel )
4920 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4921 if ( SkillValue >= YellowLevel )
4922 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4923 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4926 bool Player::UpdateCraftSkill(uint32 spellid)
4928 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4930 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4931 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4933 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4935 if(_spell_idx->second->skillId)
4937 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4939 // Alchemy Discoveries here
4940 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4941 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4943 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4944 learnSpell(discoveredSpell,false);
4947 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4949 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4950 _spell_idx->second->max_value,
4951 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4952 _spell_idx->second->min_value),
4953 craft_skill_gain);
4956 return false;
4959 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4961 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4963 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4965 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4966 switch (SkillId)
4968 case SKILL_HERBALISM:
4969 case SKILL_LOCKPICKING:
4970 case SKILL_JEWELCRAFTING:
4971 case SKILL_INSCRIPTION:
4972 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4973 case SKILL_SKINNING:
4974 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4975 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4976 else
4977 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4978 case SKILL_MINING:
4979 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4980 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4981 else
4982 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4984 return false;
4987 bool Player::UpdateFishingSkill()
4989 sLog.outDebug("UpdateFishingSkill");
4991 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4993 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4995 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4997 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5000 // levels sync. with spell requirement for skill levels to learn
5001 // bonus abilities in sSkillLineAbilityStore
5002 // Used only to avoid scan DBC at each skill grow
5003 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5005 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5007 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5008 if ( !SkillId )
5009 return false;
5011 if(Chance <= 0) // speedup in 0 chance case
5013 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5014 return false;
5017 uint16 i=0;
5018 for (; i < PLAYER_MAX_SKILLS; ++i)
5019 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5020 if ( i >= PLAYER_MAX_SKILLS )
5021 return false;
5023 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5024 uint16 SkillValue = SKILL_VALUE(data);
5025 uint16 MaxValue = SKILL_MAX(data);
5027 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5028 return false;
5030 int32 Roll = irand(1,1000);
5032 if ( Roll <= Chance )
5034 uint32 new_value = SkillValue+step;
5035 if(new_value > MaxValue)
5036 new_value = MaxValue;
5038 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5039 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5041 if((SkillValue < *bsl && new_value >= *bsl))
5043 learnSkillRewardedSpells( SkillId, new_value);
5044 break;
5047 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5048 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5049 return true;
5052 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5053 return false;
5056 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5058 // no skill gain in pvp
5059 Unit *pVictim = getVictim();
5060 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5061 return;
5063 if(IsInFeralForm())
5064 return; // always maximized SKILL_FERAL_COMBAT in fact
5066 if(m_form == FORM_TREE)
5067 return; // use weapon but not skill up
5069 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5071 switch(attType)
5073 case BASE_ATTACK:
5075 Item *tmpitem = GetWeaponForAttack(attType,true);
5077 if (!tmpitem)
5078 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5079 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5080 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5081 break;
5083 case OFF_ATTACK:
5084 case RANGED_ATTACK:
5086 Item *tmpitem = GetWeaponForAttack(attType,true);
5087 if (tmpitem)
5088 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5089 break;
5092 UpdateAllCritPercentages();
5095 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5097 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5098 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5099 uint32 moblevel = pVictim->getLevelForTarget(this);
5100 if(moblevel < greylevel)
5101 return;
5103 if (moblevel > plevel + 5)
5104 moblevel = plevel + 5;
5106 uint32 lvldif = moblevel - greylevel;
5107 if(lvldif < 3)
5108 lvldif = 3;
5110 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5111 if(skilldif <= 0)
5112 return;
5114 float chance = float(3 * lvldif * skilldif) / plevel;
5115 if(!defence)
5117 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5118 chance *= 0.1f * GetStat(STAT_INTELLECT);
5121 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5123 if(roll_chance_f(chance))
5125 if(defence)
5126 UpdateDefense();
5127 else
5128 UpdateWeaponSkill(attType);
5130 else
5131 return;
5134 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5136 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5137 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5139 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5140 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5141 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5143 if(talent) // permanent bonus stored in high part
5144 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5145 else // temporary/item bonus stored in low part
5146 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5147 return;
5151 void Player::UpdateSkillsForLevel()
5153 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5154 uint32 maxSkill = GetMaxSkillValueForLevel();
5156 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5158 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5159 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5161 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5163 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5164 if(!pSkill)
5165 continue;
5167 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5168 continue;
5170 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5171 uint32 max = SKILL_MAX(data);
5172 uint32 val = SKILL_VALUE(data);
5174 /// update only level dependent max skill values
5175 if(max!=1)
5177 /// miximize skill always
5178 if(alwaysMaxSkill)
5179 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5180 /// update max skill value if current max skill not maximized
5181 else if(max != maxconfskill)
5182 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5187 void Player::UpdateSkillsToMaxSkillsForLevel()
5189 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5190 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5192 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5193 if( IsProfessionOrRidingSkill(pskill))
5194 continue;
5195 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5197 uint32 max = SKILL_MAX(data);
5199 if(max > 1)
5200 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5202 if(pskill == SKILL_DEFENSE)
5203 UpdateDefenseBonusesMod();
5207 // This functions sets a skill line value (and adds if doesn't exist yet)
5208 // To "remove" a skill line, set it's values to zero
5209 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5211 if(!id)
5212 return;
5214 uint16 i=0;
5215 for (; i < PLAYER_MAX_SKILLS; ++i)
5216 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5218 if(i<PLAYER_MAX_SKILLS) //has skill
5220 if(currVal)
5222 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5223 learnSkillRewardedSpells(id, currVal);
5224 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5225 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5227 else //remove
5229 // clear skill fields
5230 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5231 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5232 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5234 // remove all spells that related to this skill
5235 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5236 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5237 if (pAbility->skillId==id)
5238 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5241 else if(currVal) //add
5243 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5244 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5246 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5247 if(!pSkill)
5249 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5250 return;
5252 // enable unlearn button for primary professions only
5253 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5254 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5255 else
5256 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5257 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5258 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5259 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5261 // apply skill bonuses
5262 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5264 // temporary bonuses
5265 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5266 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5267 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5268 (*j)->ApplyModifier(true);
5270 // permanent bonuses
5271 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5272 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5273 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5274 (*j)->ApplyModifier(true);
5276 // Learn all spells for skill
5277 learnSkillRewardedSpells(id, currVal);
5278 return;
5283 bool Player::HasSkill(uint32 skill) const
5285 if(!skill)return false;
5286 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5288 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5290 return true;
5293 return false;
5296 uint16 Player::GetSkillValue(uint32 skill) const
5298 if(!skill)
5299 return 0;
5301 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5303 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5305 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5307 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5308 result += SKILL_TEMP_BONUS(bonus);
5309 result += SKILL_PERM_BONUS(bonus);
5310 return result < 0 ? 0 : result;
5313 return 0;
5316 uint16 Player::GetMaxSkillValue(uint32 skill) const
5318 if(!skill)return 0;
5319 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5321 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5323 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5325 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5326 result += SKILL_TEMP_BONUS(bonus);
5327 result += SKILL_PERM_BONUS(bonus);
5328 return result < 0 ? 0 : result;
5331 return 0;
5334 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5336 if(!skill)return 0;
5337 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5339 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5341 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5344 return 0;
5347 uint16 Player::GetBaseSkillValue(uint32 skill) const
5349 if(!skill)return 0;
5350 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5352 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5354 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5355 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5356 return result < 0 ? 0 : result;
5359 return 0;
5362 uint16 Player::GetPureSkillValue(uint32 skill) const
5364 if(!skill)return 0;
5365 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5367 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5369 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5372 return 0;
5375 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5377 if(!skill)
5378 return 0;
5380 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5382 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5384 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5388 return 0;
5391 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5393 if(!skill)
5394 return 0;
5396 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5398 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5400 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5404 return 0;
5407 void Player::SendInitialActionButtons() const
5409 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5411 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5412 data << uint8(0); // can be 0, 1, 2
5413 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5415 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5416 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5418 data << uint16(itr->second.action);
5419 data << uint8(itr->second.misc);
5420 data << uint8(itr->second.type);
5422 else
5424 data << uint32(0);
5428 GetSession()->SendPacket( &data );
5429 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5432 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5434 if(button >= MAX_ACTION_BUTTONS)
5436 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5437 return false;
5440 // check cheating with adding non-known spells to action bar
5441 if(type==ACTION_BUTTON_SPELL)
5443 if(!sSpellStore.LookupEntry(action))
5445 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5446 return false;
5449 if(!HasSpell(action))
5451 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5452 return false;
5456 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5458 if (buttonItr==m_actionButtons.end())
5459 { // just add new button
5460 m_actionButtons[button] = ActionButton(action,type,misc);
5462 else
5463 { // change state of current button
5464 ActionButtonUpdateState uState = buttonItr->second.uState;
5465 buttonItr->second = ActionButton(action,type,misc);
5466 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5469 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5470 return true;
5473 void Player::removeActionButton(uint8 button)
5475 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5476 if (buttonItr==m_actionButtons.end())
5477 return;
5479 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5480 m_actionButtons.erase(buttonItr); // new and not saved
5481 else
5482 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5484 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5487 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5489 // prevent crash when a bad coord is sent by the client
5490 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5492 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5493 return false;
5496 Map *m = GetMap();
5498 const float old_x = GetPositionX();
5499 const float old_y = GetPositionY();
5500 const float old_z = GetPositionZ();
5501 const float old_r = GetOrientation();
5503 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5505 if (teleport || old_x != x || old_y != y || old_z != z)
5506 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5507 else
5508 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5510 // move and update visible state if need
5511 m->PlayerRelocation(this, x, y, z, orientation);
5513 // reread after Map::Relocation
5514 m = GetMap();
5515 x = GetPositionX();
5516 y = GetPositionY();
5517 z = GetPositionZ();
5519 // group update
5520 if(GetGroup() && (old_x != x || old_y != y))
5521 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5524 // code block for underwater state update
5525 UpdateUnderwaterState(m, x, y, z);
5527 CheckExploreSystem();
5529 return true;
5532 void Player::SaveRecallPosition()
5534 m_recallMap = GetMapId();
5535 m_recallX = GetPositionX();
5536 m_recallY = GetPositionY();
5537 m_recallZ = GetPositionZ();
5538 m_recallO = GetOrientation();
5541 void Player::SendMessageToSet(WorldPacket *data, bool self)
5543 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5544 if(_map)
5546 _map->MessageBroadcast(this, data, self);
5547 return;
5550 //if player is not in world and map in not created/already destroyed
5551 //no need to create one, just send packet for itself!
5552 if(self)
5553 GetSession()->SendPacket(data);
5556 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5558 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5559 if(_map)
5561 _map->MessageDistBroadcast(this, data, dist, self);
5562 return;
5565 if(self)
5566 GetSession()->SendPacket(data);
5569 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5571 Map * _map = IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5572 if(_map)
5574 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5575 return;
5578 if(self)
5579 GetSession()->SendPacket(data);
5582 void Player::SendDirectMessage(WorldPacket *data)
5584 GetSession()->SendPacket(data);
5587 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5589 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5590 data << uint32(CinematicSequenceId);
5591 SendDirectMessage(&data);
5594 void Player::SendMovieStart(uint32 MovieId)
5596 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5597 data << uint32(MovieId);
5598 SendDirectMessage(&data);
5601 void Player::CheckExploreSystem()
5603 if (!isAlive())
5604 return;
5606 if (isInFlight())
5607 return;
5609 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5610 if(areaFlag==0xffff)
5611 return;
5612 int offset = areaFlag / 32;
5614 if(offset >= 128)
5616 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);
5617 return;
5620 uint32 val = (uint32)(1 << (areaFlag % 32));
5621 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5623 if( !(currFields & val) )
5625 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5627 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5629 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5630 if(!p)
5632 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5634 else if(p->area_level > 0)
5636 uint32 area = p->ID;
5637 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5639 SendExplorationExperience(area,0);
5641 else
5643 int32 diff = int32(getLevel()) - p->area_level;
5644 uint32 XP = 0;
5645 if (diff < -5)
5647 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5649 else if (diff > 5)
5651 int32 exploration_percent = (100-((diff-5)*5));
5652 if (exploration_percent > 100)
5653 exploration_percent = 100;
5654 else if (exploration_percent < 0)
5655 exploration_percent = 0;
5657 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5659 else
5661 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5664 GiveXP( XP, NULL );
5665 SendExplorationExperience(area,XP);
5667 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5672 uint32 Player::TeamForRace(uint8 race)
5674 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5675 if(!rEntry)
5677 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5678 return ALLIANCE;
5681 switch(rEntry->TeamID)
5683 case 7: return ALLIANCE;
5684 case 1: return HORDE;
5687 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5688 return ALLIANCE;
5691 uint32 Player::getFactionForRace(uint8 race)
5693 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5694 if(!rEntry)
5696 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5697 return 0;
5700 return rEntry->FactionID;
5703 void Player::setFactionForRace(uint8 race)
5705 m_team = TeamForRace(race);
5706 setFaction( getFactionForRace(race) );
5709 ReputationRank Player::GetReputationRank(uint32 faction) const
5711 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5712 return GetReputationMgr().GetRank(factionEntry);
5715 //Calculate total reputation percent player gain with quest/creature level
5716 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5718 float percent = 100.0f;
5720 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5722 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5723 percent *= rate;
5725 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5727 if (!for_quest)
5728 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5730 percent += rep > 0 ? repMod : -repMod;
5732 if (percent <= 0.0f)
5733 return 0;
5735 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5738 //Calculates how many reputation points player gains in victim's enemy factions
5739 void Player::RewardReputation(Unit *pVictim, float rate)
5741 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5742 return;
5744 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5746 if(!Rep)
5747 return;
5749 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5751 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5752 donerep1 = int32(donerep1*rate);
5753 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5754 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5755 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5756 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5758 // Wiki: Team factions value divided by 2
5759 if (factionEntry1 && Rep->is_teamaward1)
5761 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5762 if(team1_factionEntry)
5763 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5767 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5769 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5770 donerep2 = int32(donerep2*rate);
5771 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5772 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5773 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5774 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5776 // Wiki: Team factions value divided by 2
5777 if (factionEntry2 && Rep->is_teamaward2)
5779 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5780 if(team2_factionEntry)
5781 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5786 //Calculate how many reputation points player gain with the quest
5787 void Player::RewardReputation(Quest const *pQuest)
5789 // quest reputation reward/loss
5790 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5792 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5794 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5795 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5796 if(factionEntry)
5797 GetReputationMgr().ModifyReputation(factionEntry, rep);
5801 // TODO: implement reputation spillover
5804 void Player::UpdateArenaFields(void)
5806 /* arena calcs go here */
5809 void Player::UpdateHonorFields()
5811 /// called when rewarding honor and at each save
5812 uint64 now = time(NULL);
5813 uint64 today = uint64(time(NULL) / DAY) * DAY;
5815 if(m_lastHonorUpdateTime < today)
5817 uint64 yesterday = today - DAY;
5819 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5821 // update yesterday's contribution
5822 if(m_lastHonorUpdateTime >= yesterday )
5824 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5826 // this is the first update today, reset today's contribution
5827 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5828 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5830 else
5832 // no honor/kills yesterday or today, reset
5833 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5834 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5838 m_lastHonorUpdateTime = now;
5841 ///Calculate the amount of honor gained based on the victim
5842 ///and the size of the group for which the honor is divided
5843 ///An exact honor value can also be given (overriding the calcs)
5844 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5846 // do not reward honor in arenas, but enable onkill spellproc
5847 if(InArena())
5849 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5850 return false;
5852 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5853 return false;
5855 return true;
5858 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5859 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5860 return false;
5862 uint64 victim_guid = 0;
5863 uint32 victim_rank = 0;
5865 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5866 UpdateHonorFields();
5868 if(honor <= 0)
5870 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5871 return false;
5873 victim_guid = uVictim->GetGUID();
5875 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5877 Player *pVictim = (Player *)uVictim;
5879 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5880 return false;
5882 float f = 1; //need for total kills (?? need more info)
5883 uint32 k_grey = 0;
5884 uint32 k_level = getLevel();
5885 uint32 v_level = pVictim->getLevel();
5888 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5889 // [0] Just name
5890 // [1..14] Alliance honor titles and player name
5891 // [15..28] Horde honor titles and player name
5892 // [29..38] Other title and player name
5893 // [39+] Nothing
5894 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5895 // Get Killer titles, CharTitlesEntry::bit_index
5896 // Ranks:
5897 // title[1..14] -> rank[5..18]
5898 // title[15..28] -> rank[5..18]
5899 // title[other] -> 0
5900 if (victim_title == 0)
5901 victim_guid = 0; // Don't show HK: <rank> message, only log.
5902 else if (victim_title < 15)
5903 victim_rank = victim_title + 4;
5904 else if (victim_title < 29)
5905 victim_rank = victim_title - 14 + 4;
5906 else
5907 victim_guid = 0; // Don't show HK: <rank> message, only log.
5910 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5912 if(v_level<=k_grey)
5913 return false;
5915 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5917 int32 v_rank =1; //need more info
5919 honor = ((f * diff_level * (190 + v_rank*10))/6);
5920 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5922 // count the number of playerkills in one day
5923 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5924 // and those in a lifetime
5925 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5926 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5927 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5928 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5930 else
5932 Creature *cVictim = (Creature *)uVictim;
5934 if (!cVictim->isRacialLeader())
5935 return false;
5937 honor = 100; // ??? need more info
5938 victim_rank = 19; // HK: Leader
5942 if (uVictim != NULL)
5944 honor *= sWorld.getRate(RATE_HONOR);
5946 if(groupsize > 1)
5947 honor /= groupsize;
5949 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5952 // honor - for show honor points in log
5953 // victim_guid - for show victim name in log
5954 // victim_rank [1..4] HK: <dishonored rank>
5955 // victim_rank [5..19] HK: <alliance\horde rank>
5956 // victim_rank [0,20+] HK: <>
5957 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5958 data << (uint32) honor;
5959 data << (uint64) victim_guid;
5960 data << (uint32) victim_rank;
5962 GetSession()->SendPacket(&data);
5964 // add honor points
5965 ModifyHonorPoints(int32(honor));
5967 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5968 return true;
5971 void Player::ModifyHonorPoints( int32 value )
5973 if(value < 0)
5975 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5976 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5977 else
5978 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5980 else
5981 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5984 void Player::ModifyArenaPoints( int32 value )
5986 if(value < 0)
5988 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5989 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5990 else
5991 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5993 else
5994 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5997 uint32 Player::GetGuildIdFromDB(uint64 guid)
5999 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6000 if(!result)
6001 return 0;
6003 uint32 id = result->Fetch()[0].GetUInt32();
6004 delete result;
6005 return id;
6008 uint32 Player::GetRankFromDB(uint64 guid)
6010 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6011 if( result )
6013 uint32 v = result->Fetch()[0].GetUInt32();
6014 delete result;
6015 return v;
6017 else
6018 return 0;
6021 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6023 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);
6024 if(!result)
6025 return 0;
6027 uint32 id = (*result)[0].GetUInt32();
6028 delete result;
6029 return id;
6032 uint32 Player::GetZoneIdFromDB(uint64 guid)
6034 uint32 guidLow = GUID_LOPART(guid);
6035 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6036 if (!result)
6037 return 0;
6038 Field* fields = result->Fetch();
6039 uint32 zone = fields[0].GetUInt32();
6040 delete result;
6042 if (!zone)
6044 // stored zone is zero, use generic and slow zone detection
6045 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6046 if( !result )
6047 return 0;
6048 fields = result->Fetch();
6049 uint32 map = fields[0].GetUInt32();
6050 float posx = fields[1].GetFloat();
6051 float posy = fields[2].GetFloat();
6052 float posz = fields[3].GetFloat();
6053 delete result;
6055 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6057 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6060 return zone;
6063 void Player::UpdateArea(uint32 newArea)
6065 // FFA_PVP flags are area and not zone id dependent
6066 // so apply them accordingly
6067 m_areaUpdateId = newArea;
6069 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6071 if(area && (area->flags & AREA_FLAG_ARENA))
6073 if(!isGameMaster())
6074 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6076 else
6078 // remove ffa flag only if not ffapvp realm
6079 // removal in sanctuaries and capitals is handled in zone update
6080 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6081 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6084 UpdateAreaDependentAuras(newArea);
6087 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6089 if(m_zoneUpdateId != newZone)
6090 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6092 m_zoneUpdateId = newZone;
6093 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6095 // zone changed, so area changed as well, update it
6096 UpdateArea(newArea);
6098 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6099 if(!zone)
6100 return;
6102 if (sWorld.getConfig(CONFIG_WEATHER))
6104 Weather *wth = sWorld.FindWeather(zone->ID);
6105 if(wth)
6107 wth->SendWeatherUpdateToPlayer(this);
6109 else
6111 if(!sWorld.AddWeather(zone->ID))
6113 // send fine weather packet to remove old zone's weather
6114 Weather::SendFineWeatherUpdateToPlayer(this);
6119 // in PvP, any not controlled zone (except zone->team == 6, default case)
6120 // in PvE, only opposition team capital
6121 switch(zone->team)
6123 case AREATEAM_ALLY:
6124 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6125 break;
6126 case AREATEAM_HORDE:
6127 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6128 break;
6129 case AREATEAM_NONE:
6130 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6131 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6132 break;
6133 default: // 6 in fact
6134 pvpInfo.inHostileArea = false;
6135 break;
6138 if(pvpInfo.inHostileArea) // in hostile area
6140 if(!IsPvP() || pvpInfo.endTimer != 0)
6141 UpdatePvP(true, true);
6143 else // in friendly area
6145 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6146 pvpInfo.endTimer = time(0); // start toggle-off
6149 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6151 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6152 if(sWorld.IsFFAPvPRealm())
6153 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6155 else
6157 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6160 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6162 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6163 SetRestType(REST_TYPE_IN_CITY);
6164 InnEnter(time(0),GetMapId(),0,0,0);
6166 if(sWorld.IsFFAPvPRealm())
6167 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6169 else // anywhere else
6171 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6173 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6175 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6177 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6178 SetRestType(REST_TYPE_NO);
6180 if(sWorld.IsFFAPvPRealm())
6181 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6184 else // not in tavern (leave city then)
6186 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6187 SetRestType(REST_TYPE_NO);
6189 // Set player to FFA PVP when not in rested environment.
6190 if(sWorld.IsFFAPvPRealm())
6191 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6196 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6197 // if player resurrected at teleport this will be applied in resurrect code
6198 if(isAlive())
6199 DestroyZoneLimitedItem( true, newZone );
6201 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6202 AutoUnequipOffhandIfNeed();
6204 // recent client version not send leave/join channel packets for built-in local channels
6205 UpdateLocalChannels( newZone );
6207 // group update
6208 if(GetGroup())
6209 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6211 UpdateZoneDependentAuras(newZone);
6214 //If players are too far way of duel flag... then player loose the duel
6215 void Player::CheckDuelDistance(time_t currTime)
6217 if(!duel)
6218 return;
6220 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6221 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6222 if(!obj)
6223 return;
6225 if(duel->outOfBound == 0)
6227 if(!IsWithinDistInMap(obj, 50))
6229 duel->outOfBound = currTime;
6231 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6232 GetSession()->SendPacket(&data);
6235 else
6237 if(IsWithinDistInMap(obj, 40))
6239 duel->outOfBound = 0;
6241 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6242 GetSession()->SendPacket(&data);
6244 else if(currTime >= (duel->outOfBound+10))
6246 DuelComplete(DUEL_FLED);
6251 void Player::DuelComplete(DuelCompleteType type)
6253 // duel not requested
6254 if(!duel)
6255 return;
6257 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6258 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6259 GetSession()->SendPacket(&data);
6260 duel->opponent->GetSession()->SendPacket(&data);
6262 if(type != DUEL_INTERUPTED)
6264 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6265 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6266 data << duel->opponent->GetName();
6267 data << GetName();
6268 SendMessageToSet(&data,true);
6271 if (type == DUEL_WON)
6273 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6274 if (duel->opponent)
6275 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6278 //Remove Duel Flag object
6279 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6280 if(obj)
6281 duel->initiator->RemoveGameObject(obj,true);
6283 /* remove auras */
6284 std::vector<uint32> auras2remove;
6285 AuraMap const& vAuras = duel->opponent->GetAuras();
6286 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6288 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6289 auras2remove.push_back(i->second->GetId());
6292 for(size_t i=0; i<auras2remove.size(); ++i)
6293 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6295 auras2remove.clear();
6296 AuraMap const& auras = GetAuras();
6297 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6299 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6300 auras2remove.push_back(i->second->GetId());
6302 for(size_t i=0; i<auras2remove.size(); ++i)
6303 RemoveAurasDueToSpell(auras2remove[i]);
6305 // cleanup combo points
6306 if(GetComboTarget()==duel->opponent->GetGUID())
6307 ClearComboPoints();
6308 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6309 ClearComboPoints();
6311 if(duel->opponent->GetComboTarget()==GetGUID())
6312 duel->opponent->ClearComboPoints();
6313 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6314 duel->opponent->ClearComboPoints();
6316 //cleanups
6317 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6318 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6319 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6320 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6322 delete duel->opponent->duel;
6323 duel->opponent->duel = NULL;
6324 delete duel;
6325 duel = NULL;
6328 //---------------------------------------------------------//
6330 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6332 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6333 return;
6335 // not apply/remove mods for broken item
6336 if(item->IsBroken())
6337 return;
6339 ItemPrototype const *proto = item->GetProto();
6341 if(!proto)
6342 return;
6344 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6346 uint32 attacktype = Player::GetAttackBySlot(slot);
6347 if(attacktype < MAX_ATTACK)
6348 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6350 _ApplyItemBonuses(proto,slot,apply);
6352 if( slot==EQUIPMENT_SLOT_RANGED )
6353 _ApplyAmmoBonuses();
6355 ApplyItemEquipSpell(item,apply);
6356 ApplyEnchantment(item, apply);
6358 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6359 CorrectMetaGemEnchants(slot, apply);
6361 sLog.outDebug("_ApplyItemMods complete.");
6364 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6366 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6367 return;
6369 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : 0;
6370 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(getLevel()) : 0;
6372 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6374 uint32 statType = 0;
6375 int32 val = 0;
6376 // If set ScalingStatDistribution need get stats and values from it
6377 if (ssd && ssv)
6379 if (ssd->StatMod[i] < 0)
6380 continue;
6381 statType = ssd->StatMod[i];
6382 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6384 else
6386 if (i >= proto->StatsCount)
6387 continue;
6388 statType = proto->ItemStat[i].ItemStatType;
6389 val = proto->ItemStat[i].ItemStatValue;
6392 if(val == 0)
6393 continue;
6395 switch (statType)
6397 case ITEM_MOD_MANA:
6398 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6399 break;
6400 case ITEM_MOD_HEALTH: // modify HP
6401 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6402 break;
6403 case ITEM_MOD_AGILITY: // modify agility
6404 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6405 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6406 break;
6407 case ITEM_MOD_STRENGTH: //modify strength
6408 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6409 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6410 break;
6411 case ITEM_MOD_INTELLECT: //modify intellect
6412 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6413 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6414 break;
6415 case ITEM_MOD_SPIRIT: //modify spirit
6416 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6417 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6418 break;
6419 case ITEM_MOD_STAMINA: //modify stamina
6420 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6421 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6422 break;
6423 case ITEM_MOD_DEFENSE_SKILL_RATING:
6424 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6425 break;
6426 case ITEM_MOD_DODGE_RATING:
6427 ApplyRatingMod(CR_DODGE, int32(val), apply);
6428 break;
6429 case ITEM_MOD_PARRY_RATING:
6430 ApplyRatingMod(CR_PARRY, int32(val), apply);
6431 break;
6432 case ITEM_MOD_BLOCK_RATING:
6433 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6434 break;
6435 case ITEM_MOD_HIT_MELEE_RATING:
6436 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6437 break;
6438 case ITEM_MOD_HIT_RANGED_RATING:
6439 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6440 break;
6441 case ITEM_MOD_HIT_SPELL_RATING:
6442 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6443 break;
6444 case ITEM_MOD_CRIT_MELEE_RATING:
6445 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6446 break;
6447 case ITEM_MOD_CRIT_RANGED_RATING:
6448 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6449 break;
6450 case ITEM_MOD_CRIT_SPELL_RATING:
6451 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6452 break;
6453 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6454 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6455 break;
6456 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6457 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6458 break;
6459 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6460 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6461 break;
6462 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6463 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6464 break;
6465 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6466 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6467 break;
6468 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6469 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6470 break;
6471 case ITEM_MOD_HASTE_MELEE_RATING:
6472 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6473 break;
6474 case ITEM_MOD_HASTE_RANGED_RATING:
6475 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6476 break;
6477 case ITEM_MOD_HASTE_SPELL_RATING:
6478 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6479 break;
6480 case ITEM_MOD_HIT_RATING:
6481 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6482 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6483 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6484 break;
6485 case ITEM_MOD_CRIT_RATING:
6486 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6487 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6488 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6489 break;
6490 case ITEM_MOD_HIT_TAKEN_RATING:
6491 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6492 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6493 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6494 break;
6495 case ITEM_MOD_CRIT_TAKEN_RATING:
6496 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6497 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6498 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6499 break;
6500 case ITEM_MOD_RESILIENCE_RATING:
6501 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6502 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6503 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6504 break;
6505 case ITEM_MOD_HASTE_RATING:
6506 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6507 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6508 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6509 break;
6510 case ITEM_MOD_EXPERTISE_RATING:
6511 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6512 break;
6513 case ITEM_MOD_ATTACK_POWER:
6514 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6515 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6516 break;
6517 case ITEM_MOD_RANGED_ATTACK_POWER:
6518 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6519 break;
6520 case ITEM_MOD_FERAL_ATTACK_POWER:
6521 ApplyFeralAPBonus(int32(val), apply);
6522 break;
6523 case ITEM_MOD_SPELL_HEALING_DONE:
6524 ApplySpellHealingBonus(int32(val), apply);
6525 break;
6526 case ITEM_MOD_SPELL_DAMAGE_DONE:
6527 ApplySpellDamageBonus(int32(val), apply);
6528 break;
6529 case ITEM_MOD_MANA_REGENERATION:
6530 ApplyManaRegenBonus(int32(val), apply);
6531 break;
6532 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6533 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6534 break;
6535 case ITEM_MOD_SPELL_POWER:
6536 ApplySpellHealingBonus(int32(val), apply);
6537 ApplySpellDamageBonus(int32(val), apply);
6538 break;
6542 // If set ScalingStatValue armor get it or use item armor
6543 uint32 armor = proto->Armor;
6544 if (ssv)
6546 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6547 armor = ssvarmor;
6549 // Add armor bonus from ArmorDamageModifier if > 0
6550 if (proto->ArmorDamageModifier > 0)
6551 armor+=proto->ArmorDamageModifier;
6552 if (armor)
6553 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6555 if (proto->Block)
6556 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6558 if (proto->HolyRes)
6559 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6561 if (proto->FireRes)
6562 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6564 if (proto->NatureRes)
6565 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6567 if (proto->FrostRes)
6568 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6570 if (proto->ShadowRes)
6571 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6573 if (proto->ArcaneRes)
6574 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6576 WeaponAttackType attType = BASE_ATTACK;
6577 float damage = 0.0f;
6579 if( slot == EQUIPMENT_SLOT_RANGED && (
6580 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6581 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6583 attType = RANGED_ATTACK;
6585 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6587 attType = OFF_ATTACK;
6590 float minDamage = proto->Damage[0].DamageMin;
6591 float maxDamage = proto->Damage[0].DamageMax;
6592 int32 extraDPS = 0;
6593 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6594 if (ssv)
6596 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6598 float average = extraDPS * proto->Delay / 1000.0f;
6599 minDamage = 0.7f * average;
6600 maxDamage = 1.3f * average;
6603 if (minDamage > 0 )
6605 damage = apply ? minDamage : BASE_MINDAMAGE;
6606 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6607 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6610 if (maxDamage > 0 )
6612 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6613 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6616 // Apply feral bonus from ScalingStatValue if set
6617 if (ssv)
6619 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6620 ApplyFeralAPBonus(feral_bonus, apply);
6622 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6623 if(getClass() == CLASS_DRUID)
6625 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6626 if (feral_bonus > 0)
6627 ApplyFeralAPBonus(feral_bonus, apply);
6630 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6631 return;
6633 if (proto->Delay)
6635 if(slot == EQUIPMENT_SLOT_RANGED)
6636 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6637 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6638 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6639 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6640 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6643 if(CanModifyStats() && (damage || proto->Delay))
6644 UpdateDamagePhysical(attType);
6647 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6649 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6650 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6651 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6653 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6654 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6655 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6657 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6658 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6659 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6662 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6664 // generic not weapon specific case processes in aura code
6665 if(aura->GetSpellProto()->EquippedItemClass == -1)
6666 return;
6668 BaseModGroup mod = BASEMOD_END;
6669 switch(attackType)
6671 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6672 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6673 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6674 default: return;
6677 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6679 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6683 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6685 // ignore spell mods for not wands
6686 Modifier const* modifier = aura->GetModifier();
6687 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6688 return;
6690 // generic not weapon specific case processes in aura code
6691 if(aura->GetSpellProto()->EquippedItemClass == -1)
6692 return;
6694 UnitMods unitMod = UNIT_MOD_END;
6695 switch(attackType)
6697 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6698 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6699 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6700 default: return;
6703 UnitModifierType unitModType = TOTAL_VALUE;
6704 switch(modifier->m_auraname)
6706 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6707 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6708 default: return;
6711 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6713 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6717 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6719 if(!item)
6720 return;
6722 ItemPrototype const *proto = item->GetProto();
6723 if(!proto)
6724 return;
6726 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6728 _Spell const& spellData = proto->Spells[i];
6730 // no spell
6731 if(!spellData.SpellId )
6732 continue;
6734 // wrong triggering type
6735 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6736 continue;
6738 // check if it is valid spell
6739 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6740 if(!spellproto)
6741 continue;
6743 ApplyEquipSpell(spellproto,item,apply,form_change);
6747 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6749 if(apply)
6751 // Cannot be used in this stance/form
6752 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6753 return;
6755 if(form_change) // check aura active state from other form
6757 bool found = false;
6758 for (int k=0; k < 3; ++k)
6760 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6761 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6763 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6765 found = true;
6766 break;
6769 if(found)
6770 break;
6773 if(found) // and skip re-cast already active aura at form change
6774 return;
6777 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6779 CastSpell(this,spellInfo,true,item);
6781 else
6783 if(form_change) // check aura compatibility
6785 // Cannot be used in this stance/form
6786 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6787 return; // and remove only not compatible at form change
6790 if(item)
6791 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6792 else
6793 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6797 void Player::UpdateEquipSpellsAtFormChange()
6799 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6801 if(m_items[i] && !m_items[i]->IsBroken())
6803 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6804 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6808 // item set bonuses not dependent from item broken state
6809 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6811 ItemSetEffect* eff = ItemSetEff[setindex];
6812 if(!eff)
6813 continue;
6815 for(uint32 y=0;y<8; ++y)
6817 SpellEntry const* spellInfo = eff->spells[y];
6818 if(!spellInfo)
6819 continue;
6821 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6822 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6827 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
6829 Item *item = GetWeaponForAttack(attType, true);
6830 if(!item || item->IsBroken())
6831 return;
6833 ItemPrototype const *proto = item->GetProto();
6834 if(!proto)
6835 return;
6837 if (!Target || Target == this )
6838 return;
6840 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6842 _Spell const& spellData = proto->Spells[i];
6844 // no spell
6845 if(!spellData.SpellId )
6846 continue;
6848 // wrong triggering type
6849 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6850 continue;
6852 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6853 if(!spellInfo)
6855 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6856 continue;
6859 // not allow proc extra attack spell at extra attack
6860 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6861 return;
6863 float chance = spellInfo->procChance;
6865 if(spellData.SpellPPMRate)
6867 uint32 WeaponSpeed = GetAttackTime(attType);
6868 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6870 else if(chance > 100.0f)
6872 chance = GetWeaponProcChance();
6875 if (roll_chance_f(chance))
6876 CastSpell(Target, spellInfo->Id, true, item);
6879 // item combat enchantments
6880 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6882 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6883 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6884 if(!pEnchant) continue;
6885 for (int s=0;s<3;s++)
6887 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6888 continue;
6890 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6891 if (!spellInfo)
6893 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6894 continue;
6897 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6898 if (roll_chance_f(chance))
6900 if(IsPositiveSpell(pEnchant->spellid[s]))
6901 CastSpell(this, pEnchant->spellid[s], true, item);
6902 else
6903 CastSpell(Target, pEnchant->spellid[s], true, item);
6909 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6911 ItemPrototype const* proto = item->GetProto();
6912 // special learning case
6913 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6915 uint32 learn_spell_id = proto->Spells[0].SpellId;
6916 uint32 learning_spell_id = proto->Spells[1].SpellId;
6918 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6919 if(!spellInfo)
6921 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6922 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6923 return;
6926 Spell *spell = new Spell(this, spellInfo, false);
6927 spell->m_CastItem = item;
6928 spell->m_cast_count = cast_count; //set count of casts
6929 spell->m_currentBasePoints[0] = learning_spell_id;
6930 spell->prepare(&targets);
6931 return;
6934 // use triggered flag only for items with many spell casts and for not first cast
6935 int count = 0;
6937 // item spells casted at use
6938 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6940 _Spell const& spellData = proto->Spells[i];
6942 // no spell
6943 if(!spellData.SpellId)
6944 continue;
6946 // wrong triggering type
6947 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6948 continue;
6950 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6951 if(!spellInfo)
6953 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6954 continue;
6957 Spell *spell = new Spell(this, spellInfo, (count > 0));
6958 spell->m_CastItem = item;
6959 spell->m_cast_count = cast_count; // set count of casts
6960 spell->m_glyphIndex = glyphIndex; // glyph index
6961 spell->prepare(&targets);
6963 ++count;
6966 // Item enchantments spells casted at use
6967 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6969 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6970 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6971 if(!pEnchant) continue;
6972 for (int s=0;s<3;s++)
6974 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6975 continue;
6977 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6978 if (!spellInfo)
6980 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6981 continue;
6984 Spell *spell = new Spell(this, spellInfo, (count > 0));
6985 spell->m_CastItem = item;
6986 spell->m_cast_count = cast_count; // set count of casts
6987 spell->m_glyphIndex = glyphIndex; // glyph index
6988 spell->prepare(&targets);
6990 ++count;
6995 void Player::_RemoveAllItemMods()
6997 sLog.outDebug("_RemoveAllItemMods start.");
6999 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7001 if(m_items[i])
7003 ItemPrototype const *proto = m_items[i]->GetProto();
7004 if(!proto)
7005 continue;
7007 // item set bonuses not dependent from item broken state
7008 if(proto->ItemSet)
7009 RemoveItemsSetItem(this,proto);
7011 if(m_items[i]->IsBroken())
7012 continue;
7014 ApplyItemEquipSpell(m_items[i],false);
7015 ApplyEnchantment(m_items[i], false);
7019 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7021 if(m_items[i])
7023 if(m_items[i]->IsBroken())
7024 continue;
7025 ItemPrototype const *proto = m_items[i]->GetProto();
7026 if(!proto)
7027 continue;
7029 uint32 attacktype = Player::GetAttackBySlot(i);
7030 if(attacktype < MAX_ATTACK)
7031 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7033 _ApplyItemBonuses(proto,i, false);
7035 if( i == EQUIPMENT_SLOT_RANGED )
7036 _ApplyAmmoBonuses();
7040 sLog.outDebug("_RemoveAllItemMods complete.");
7043 void Player::_ApplyAllItemMods()
7045 sLog.outDebug("_ApplyAllItemMods start.");
7047 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7049 if(m_items[i])
7051 if(m_items[i]->IsBroken())
7052 continue;
7054 ItemPrototype const *proto = m_items[i]->GetProto();
7055 if(!proto)
7056 continue;
7058 uint32 attacktype = Player::GetAttackBySlot(i);
7059 if(attacktype < MAX_ATTACK)
7060 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7062 _ApplyItemBonuses(proto,i, true);
7064 if( i == EQUIPMENT_SLOT_RANGED )
7065 _ApplyAmmoBonuses();
7069 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7071 if(m_items[i])
7073 ItemPrototype const *proto = m_items[i]->GetProto();
7074 if(!proto)
7075 continue;
7077 // item set bonuses not dependent from item broken state
7078 if(proto->ItemSet)
7079 AddItemsSetItem(this,m_items[i]);
7081 if(m_items[i]->IsBroken())
7082 continue;
7084 ApplyItemEquipSpell(m_items[i],true);
7085 ApplyEnchantment(m_items[i], true);
7089 sLog.outDebug("_ApplyAllItemMods complete.");
7092 void Player::_ApplyAmmoBonuses()
7094 // check ammo
7095 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7096 if(!ammo_id)
7097 return;
7099 float currentAmmoDPS;
7101 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7102 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7103 currentAmmoDPS = 0.0f;
7104 else
7105 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7107 if(currentAmmoDPS == GetAmmoDPS())
7108 return;
7110 m_ammoDPS = currentAmmoDPS;
7112 if(CanModifyStats())
7113 UpdateDamagePhysical(RANGED_ATTACK);
7116 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7118 if(!ammo_proto)
7119 return false;
7121 // check ranged weapon
7122 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7123 if(!weapon || weapon->IsBroken() )
7124 return false;
7126 ItemPrototype const* weapon_proto = weapon->GetProto();
7127 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7128 return false;
7130 // check ammo ws. weapon compatibility
7131 switch(weapon_proto->SubClass)
7133 case ITEM_SUBCLASS_WEAPON_BOW:
7134 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7135 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7136 return false;
7137 break;
7138 case ITEM_SUBCLASS_WEAPON_GUN:
7139 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7140 return false;
7141 break;
7142 default:
7143 return false;
7146 return true;
7149 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7150 Called by remove insignia spell effect */
7151 void Player::RemovedInsignia(Player* looterPlr)
7153 if (!GetBattleGroundId())
7154 return;
7156 // If not released spirit, do it !
7157 if(m_deathTimer > 0)
7159 m_deathTimer = 0;
7160 BuildPlayerRepop();
7161 RepopAtGraveyard();
7164 Corpse *corpse = GetCorpse();
7165 if (!corpse)
7166 return;
7168 // We have to convert player corpse to bones, not to be able to resurrect there
7169 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7170 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7171 if (!bones)
7172 return;
7174 // Now we must make bones lootable, and send player loot
7175 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7177 // We store the level of our player in the gold field
7178 // We retrieve this information at Player::SendLoot()
7179 bones->loot.gold = getLevel();
7180 bones->lootRecipient = looterPlr;
7181 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7184 void Player::SendLootRelease( uint64 guid )
7186 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7187 data << uint64(guid) << uint8(1);
7188 SendDirectMessage( &data );
7191 void Player::SendLoot(uint64 guid, LootType loot_type)
7193 if (uint64 lguid = GetLootGUID())
7194 m_session->DoLootRelease(lguid);
7196 Loot *loot = 0;
7197 PermissionTypes permission = ALL_PERMISSION;
7199 sLog.outDebug("Player::SendLoot");
7200 if (IS_GAMEOBJECT_GUID(guid))
7202 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7203 GameObject *go = GetMap()->GetGameObject(guid);
7205 // not check distance for GO in case owned GO (fishing bobber case, for example)
7206 // And permit out of range GO with no owner in case fishing hole
7207 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7209 SendLootRelease(guid);
7210 return;
7213 loot = &go->loot;
7215 if (go->getLootState() == GO_READY)
7217 uint32 lootid = go->GetLootId();
7219 if (lootid)
7221 sLog.outDebug(" if(lootid)");
7222 loot->clear();
7223 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7226 if (loot_type == LOOT_FISHING)
7227 go->getFishLoot(loot,this);
7229 go->SetLootState(GO_ACTIVATED);
7232 else if (IS_ITEM_GUID(guid))
7234 Item *item = GetItemByGuid( guid );
7236 if (!item)
7238 SendLootRelease(guid);
7239 return;
7242 loot = &item->loot;
7244 if (!item->m_lootGenerated)
7246 item->m_lootGenerated = true;
7247 loot->clear();
7249 switch(loot_type)
7251 case LOOT_DISENCHANTING:
7252 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7253 break;
7254 case LOOT_PROSPECTING:
7255 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7256 break;
7257 case LOOT_MILLING:
7258 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7259 break;
7260 default:
7261 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7262 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7263 break;
7267 else if (IS_CORPSE_GUID(guid)) // remove insignia
7269 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7271 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7273 SendLootRelease(guid);
7274 return;
7277 loot = &bones->loot;
7279 if (!bones->lootForBody)
7281 bones->lootForBody = true;
7282 uint32 pLevel = bones->loot.gold;
7283 bones->loot.clear();
7284 // It may need a better formula
7285 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7286 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7289 if (bones->lootRecipient != this)
7290 permission = NONE_PERMISSION;
7292 else
7294 Creature *creature = GetMap()->GetCreature(guid);
7296 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7297 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7299 SendLootRelease(guid);
7300 return;
7303 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7305 SendLootRelease(guid);
7306 return;
7309 loot = &creature->loot;
7311 if (loot_type == LOOT_PICKPOCKETING)
7313 if (!creature->lootForPickPocketed)
7315 creature->lootForPickPocketed = true;
7316 loot->clear();
7318 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7319 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7321 // Generate extra money for pick pocket loot
7322 const uint32 a = urand(0, creature->getLevel()/2);
7323 const uint32 b = urand(0, getLevel()/2);
7324 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7327 else
7329 // the player whose group may loot the corpse
7330 Player *recipient = creature->GetLootRecipient();
7331 if (!recipient)
7333 creature->SetLootRecipient(this);
7334 recipient = this;
7337 if (creature->lootForPickPocketed)
7339 creature->lootForPickPocketed = false;
7340 loot->clear();
7343 if (!creature->lootForBody)
7345 creature->lootForBody = true;
7346 loot->clear();
7348 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7349 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7351 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7353 if (Group* group = recipient->GetGroup())
7355 group->UpdateLooterGuid(creature,true);
7357 switch (group->GetLootMethod())
7359 case GROUP_LOOT:
7360 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7361 group->GroupLoot(recipient->GetGUID(), loot, creature);
7362 break;
7363 case NEED_BEFORE_GREED:
7364 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7365 break;
7366 case MASTER_LOOT:
7367 group->MasterLoot(recipient->GetGUID(), loot, creature);
7368 break;
7369 default:
7370 break;
7375 // possible only if creature->lootForBody && loot->empty() at spell cast check
7376 if (loot_type == LOOT_SKINNING)
7378 loot->clear();
7379 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7381 // set group rights only for loot_type != LOOT_SKINNING
7382 else
7384 if(Group* group = GetGroup())
7386 if (group == recipient->GetGroup())
7388 if (group->GetLootMethod() == FREE_FOR_ALL)
7389 permission = ALL_PERMISSION;
7390 else if (group->GetLooterGuid() == GetGUID())
7392 if (group->GetLootMethod() == MASTER_LOOT)
7393 permission = MASTER_PERMISSION;
7394 else
7395 permission = ALL_PERMISSION;
7397 else
7398 permission = GROUP_PERMISSION;
7400 else
7401 permission = NONE_PERMISSION;
7403 else if (recipient == this)
7404 permission = ALL_PERMISSION;
7405 else
7406 permission = NONE_PERMISSION;
7411 SetLootGUID(guid);
7413 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7414 switch(loot_type)
7416 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7417 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7418 default: break;
7421 // need know merged fishing/corpse loot type for achievements
7422 loot->loot_type = loot_type;
7424 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7426 data << uint64(guid);
7427 data << uint8(loot_type);
7428 data << LootView(*loot, this, permission);
7430 SendDirectMessage(&data);
7432 // add 'this' player as one of the players that are looting 'loot'
7433 if (permission != NONE_PERMISSION)
7434 loot->AddLooter(GetGUID());
7436 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7437 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7440 void Player::SendNotifyLootMoneyRemoved()
7442 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7443 GetSession()->SendPacket( &data );
7446 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7448 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7449 data << uint8(lootSlot);
7450 GetSession()->SendPacket( &data );
7453 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7455 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7456 data << Field;
7457 data << Value;
7458 GetSession()->SendPacket(&data);
7461 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7463 // data depends on zoneid/mapid...
7464 BattleGround* bg = GetBattleGround();
7465 uint16 NumberOfFields = 0;
7466 uint32 mapid = GetMapId();
7468 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7470 // may be exist better way to do this...
7471 switch(zoneid)
7473 case 0:
7474 case 1:
7475 case 4:
7476 case 8:
7477 case 10:
7478 case 11:
7479 case 12:
7480 case 36:
7481 case 38:
7482 case 40:
7483 case 41:
7484 case 51:
7485 case 267:
7486 case 1519:
7487 case 1537:
7488 case 2257:
7489 case 2918:
7490 NumberOfFields = 8;
7491 break;
7492 case 139:
7493 NumberOfFields = 41;
7494 break;
7495 case 1377:
7496 NumberOfFields = 15;
7497 break;
7498 case 2597:
7499 NumberOfFields = 83;
7500 break;
7501 case 3277:
7502 NumberOfFields = 16;
7503 break;
7504 case 3358:
7505 case 3820:
7506 NumberOfFields = 40;
7507 break;
7508 case 3483:
7509 NumberOfFields = 27;
7510 break;
7511 case 3518:
7512 NumberOfFields = 39;
7513 break;
7514 case 3519:
7515 NumberOfFields = 38;
7516 break;
7517 case 3521:
7518 NumberOfFields = 37;
7519 break;
7520 case 3698:
7521 case 3702:
7522 case 3968:
7523 NumberOfFields = 11;
7524 break;
7525 case 3703:
7526 NumberOfFields = 11;
7527 break;
7528 default:
7529 NumberOfFields = 12;
7530 break;
7533 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7534 data << uint32(mapid); // mapid
7535 data << uint32(zoneid); // zone id
7536 data << uint32(areaid); // area id, new 2.1.0
7537 data << uint16(NumberOfFields); // count of uint64 blocks
7538 data << uint32(0x8d8) << uint32(0x0); // 1
7539 data << uint32(0x8d7) << uint32(0x0); // 2
7540 data << uint32(0x8d6) << uint32(0x0); // 3
7541 data << uint32(0x8d5) << uint32(0x0); // 4
7542 data << uint32(0x8d4) << uint32(0x0); // 5
7543 data << uint32(0x8d3) << uint32(0x0); // 6
7544 // 7 1 - Arena season in progress, 0 - end of season
7545 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7546 // 8 Arena season id
7547 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7548 if(mapid == 530) // Outland
7550 data << uint32(0x9bf) << uint32(0x0); // 7
7551 data << uint32(0x9bd) << uint32(0xF); // 8
7552 data << uint32(0x9bb) << uint32(0xF); // 9
7554 switch(zoneid)
7556 case 1:
7557 case 11:
7558 case 12:
7559 case 38:
7560 case 40:
7561 case 51:
7562 case 1519:
7563 case 1537:
7564 case 2257:
7565 break;
7566 case 2597: // AV
7567 data << uint32(0x7ae) << uint32(0x1); // 7
7568 data << uint32(0x532) << uint32(0x1); // 8
7569 data << uint32(0x531) << uint32(0x0); // 9
7570 data << uint32(0x52e) << uint32(0x0); // 10
7571 data << uint32(0x571) << uint32(0x0); // 11
7572 data << uint32(0x570) << uint32(0x0); // 12
7573 data << uint32(0x567) << uint32(0x1); // 13
7574 data << uint32(0x566) << uint32(0x1); // 14
7575 data << uint32(0x550) << uint32(0x1); // 15
7576 data << uint32(0x544) << uint32(0x0); // 16
7577 data << uint32(0x536) << uint32(0x0); // 17
7578 data << uint32(0x535) << uint32(0x1); // 18
7579 data << uint32(0x518) << uint32(0x0); // 19
7580 data << uint32(0x517) << uint32(0x0); // 20
7581 data << uint32(0x574) << uint32(0x0); // 21
7582 data << uint32(0x573) << uint32(0x0); // 22
7583 data << uint32(0x572) << uint32(0x0); // 23
7584 data << uint32(0x56f) << uint32(0x0); // 24
7585 data << uint32(0x56e) << uint32(0x0); // 25
7586 data << uint32(0x56d) << uint32(0x0); // 26
7587 data << uint32(0x56c) << uint32(0x0); // 27
7588 data << uint32(0x56b) << uint32(0x0); // 28
7589 data << uint32(0x56a) << uint32(0x1); // 29
7590 data << uint32(0x569) << uint32(0x1); // 30
7591 data << uint32(0x568) << uint32(0x1); // 13
7592 data << uint32(0x565) << uint32(0x0); // 32
7593 data << uint32(0x564) << uint32(0x0); // 33
7594 data << uint32(0x563) << uint32(0x0); // 34
7595 data << uint32(0x562) << uint32(0x0); // 35
7596 data << uint32(0x561) << uint32(0x0); // 36
7597 data << uint32(0x560) << uint32(0x0); // 37
7598 data << uint32(0x55f) << uint32(0x0); // 38
7599 data << uint32(0x55e) << uint32(0x0); // 39
7600 data << uint32(0x55d) << uint32(0x0); // 40
7601 data << uint32(0x3c6) << uint32(0x4); // 41
7602 data << uint32(0x3c4) << uint32(0x6); // 42
7603 data << uint32(0x3c2) << uint32(0x4); // 43
7604 data << uint32(0x516) << uint32(0x1); // 44
7605 data << uint32(0x515) << uint32(0x0); // 45
7606 data << uint32(0x3b6) << uint32(0x6); // 46
7607 data << uint32(0x55c) << uint32(0x0); // 47
7608 data << uint32(0x55b) << uint32(0x0); // 48
7609 data << uint32(0x55a) << uint32(0x0); // 49
7610 data << uint32(0x559) << uint32(0x0); // 50
7611 data << uint32(0x558) << uint32(0x0); // 51
7612 data << uint32(0x557) << uint32(0x0); // 52
7613 data << uint32(0x556) << uint32(0x0); // 53
7614 data << uint32(0x555) << uint32(0x0); // 54
7615 data << uint32(0x554) << uint32(0x1); // 55
7616 data << uint32(0x553) << uint32(0x1); // 56
7617 data << uint32(0x552) << uint32(0x1); // 57
7618 data << uint32(0x551) << uint32(0x1); // 58
7619 data << uint32(0x54f) << uint32(0x0); // 59
7620 data << uint32(0x54e) << uint32(0x0); // 60
7621 data << uint32(0x54d) << uint32(0x1); // 61
7622 data << uint32(0x54c) << uint32(0x0); // 62
7623 data << uint32(0x54b) << uint32(0x0); // 63
7624 data << uint32(0x545) << uint32(0x0); // 64
7625 data << uint32(0x543) << uint32(0x1); // 65
7626 data << uint32(0x542) << uint32(0x0); // 66
7627 data << uint32(0x540) << uint32(0x0); // 67
7628 data << uint32(0x53f) << uint32(0x0); // 68
7629 data << uint32(0x53e) << uint32(0x0); // 69
7630 data << uint32(0x53d) << uint32(0x0); // 70
7631 data << uint32(0x53c) << uint32(0x0); // 71
7632 data << uint32(0x53b) << uint32(0x0); // 72
7633 data << uint32(0x53a) << uint32(0x1); // 73
7634 data << uint32(0x539) << uint32(0x0); // 74
7635 data << uint32(0x538) << uint32(0x0); // 75
7636 data << uint32(0x537) << uint32(0x0); // 76
7637 data << uint32(0x534) << uint32(0x0); // 77
7638 data << uint32(0x533) << uint32(0x0); // 78
7639 data << uint32(0x530) << uint32(0x0); // 79
7640 data << uint32(0x52f) << uint32(0x0); // 80
7641 data << uint32(0x52d) << uint32(0x1); // 81
7642 break;
7643 case 3277: // WS
7644 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7645 bg->FillInitialWorldStates(data);
7646 else
7648 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7649 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7650 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7651 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7652 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7653 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7654 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7655 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7657 break;
7658 case 3358: // AB
7659 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7660 bg->FillInitialWorldStates(data);
7661 else
7663 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7664 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7665 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7666 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7667 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7668 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7669 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7670 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7671 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7672 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7673 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7674 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7675 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7676 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7677 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7678 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7679 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7680 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7681 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7682 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7683 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7684 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7685 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7686 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7687 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7688 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7689 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7690 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7691 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7692 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7693 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7694 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7696 break;
7697 case 3820: // EY
7698 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7699 bg->FillInitialWorldStates(data);
7700 else
7702 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7703 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7704 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7705 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7706 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7707 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7708 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7709 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7710 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7711 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7712 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7713 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7714 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7715 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7716 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7717 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7718 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7719 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7720 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7721 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7722 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7723 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7724 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7725 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7726 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7727 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7728 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7729 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7730 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7731 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7732 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7733 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7734 // and some more ... unknown
7736 break;
7737 case 3483: // Hellfire Peninsula
7738 data << uint32(0x9ba) << uint32(0x1); // 10
7739 data << uint32(0x9b9) << uint32(0x1); // 11
7740 data << uint32(0x9b5) << uint32(0x0); // 12
7741 data << uint32(0x9b4) << uint32(0x1); // 13
7742 data << uint32(0x9b3) << uint32(0x0); // 14
7743 data << uint32(0x9b2) << uint32(0x0); // 15
7744 data << uint32(0x9b1) << uint32(0x1); // 16
7745 data << uint32(0x9b0) << uint32(0x0); // 17
7746 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7747 data << uint32(0x9ac) << uint32(0x0); // 19
7748 data << uint32(0x9a8) << uint32(0x0); // 20
7749 data << uint32(0x9a7) << uint32(0x0); // 21
7750 data << uint32(0x9a6) << uint32(0x1); // 22
7751 break;
7752 case 3519: // Terokkar Forest
7753 data << uint32(0xa41) << uint32(0x0); // 10
7754 data << uint32(0xa40) << uint32(0x14); // 11
7755 data << uint32(0xa3f) << uint32(0x0); // 12
7756 data << uint32(0xa3e) << uint32(0x0); // 13
7757 data << uint32(0xa3d) << uint32(0x5); // 14
7758 data << uint32(0xa3c) << uint32(0x0); // 15
7759 data << uint32(0xa87) << uint32(0x0); // 16
7760 data << uint32(0xa86) << uint32(0x0); // 17
7761 data << uint32(0xa85) << uint32(0x0); // 18
7762 data << uint32(0xa84) << uint32(0x0); // 19
7763 data << uint32(0xa83) << uint32(0x0); // 20
7764 data << uint32(0xa82) << uint32(0x0); // 21
7765 data << uint32(0xa81) << uint32(0x0); // 22
7766 data << uint32(0xa80) << uint32(0x0); // 23
7767 data << uint32(0xa7e) << uint32(0x0); // 24
7768 data << uint32(0xa7d) << uint32(0x0); // 25
7769 data << uint32(0xa7c) << uint32(0x0); // 26
7770 data << uint32(0xa7b) << uint32(0x0); // 27
7771 data << uint32(0xa7a) << uint32(0x0); // 28
7772 data << uint32(0xa79) << uint32(0x0); // 29
7773 data << uint32(0x9d0) << uint32(0x5); // 30
7774 data << uint32(0x9ce) << uint32(0x0); // 31
7775 data << uint32(0x9cd) << uint32(0x0); // 32
7776 data << uint32(0x9cc) << uint32(0x0); // 33
7777 data << uint32(0xa88) << uint32(0x0); // 34
7778 data << uint32(0xad0) << uint32(0x0); // 35
7779 data << uint32(0xacf) << uint32(0x1); // 36
7780 break;
7781 case 3521: // Zangarmarsh
7782 data << uint32(0x9e1) << uint32(0x0); // 10
7783 data << uint32(0x9e0) << uint32(0x0); // 11
7784 data << uint32(0x9df) << uint32(0x0); // 12
7785 data << uint32(0xa5d) << uint32(0x1); // 13
7786 data << uint32(0xa5c) << uint32(0x0); // 14
7787 data << uint32(0xa5b) << uint32(0x1); // 15
7788 data << uint32(0xa5a) << uint32(0x0); // 16
7789 data << uint32(0xa59) << uint32(0x1); // 17
7790 data << uint32(0xa58) << uint32(0x0); // 18
7791 data << uint32(0xa57) << uint32(0x0); // 19
7792 data << uint32(0xa56) << uint32(0x0); // 20
7793 data << uint32(0xa55) << uint32(0x1); // 21
7794 data << uint32(0xa54) << uint32(0x0); // 22
7795 data << uint32(0x9e7) << uint32(0x0); // 23
7796 data << uint32(0x9e6) << uint32(0x0); // 24
7797 data << uint32(0x9e5) << uint32(0x0); // 25
7798 data << uint32(0xa00) << uint32(0x0); // 26
7799 data << uint32(0x9ff) << uint32(0x1); // 27
7800 data << uint32(0x9fe) << uint32(0x0); // 28
7801 data << uint32(0x9fd) << uint32(0x0); // 29
7802 data << uint32(0x9fc) << uint32(0x1); // 30
7803 data << uint32(0x9fb) << uint32(0x0); // 31
7804 data << uint32(0xa62) << uint32(0x0); // 32
7805 data << uint32(0xa61) << uint32(0x1); // 33
7806 data << uint32(0xa60) << uint32(0x1); // 34
7807 data << uint32(0xa5f) << uint32(0x0); // 35
7808 break;
7809 case 3698: // Nagrand Arena
7810 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7811 bg->FillInitialWorldStates(data);
7812 else
7814 data << uint32(0xa0f) << uint32(0x0); // 7
7815 data << uint32(0xa10) << uint32(0x0); // 8
7816 data << uint32(0xa11) << uint32(0x0); // 9 show
7818 break;
7819 case 3702: // Blade's Edge Arena
7820 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7821 bg->FillInitialWorldStates(data);
7822 else
7824 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7825 data << uint32(0x9f1) << uint32(0x0); // 8 green
7826 data << uint32(0x9f3) << uint32(0x0); // 9 show
7828 break;
7829 case 3968: // Ruins of Lordaeron
7830 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7831 bg->FillInitialWorldStates(data);
7832 else
7834 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7835 data << uint32(0xbb9) << uint32(0x0); // 8 green
7836 data << uint32(0xbba) << uint32(0x0); // 9 show
7838 break;
7839 case 3703: // Shattrath City
7840 break;
7841 default:
7842 data << uint32(0x914) << uint32(0x0); // 7
7843 data << uint32(0x913) << uint32(0x0); // 8
7844 data << uint32(0x912) << uint32(0x0); // 9
7845 data << uint32(0x915) << uint32(0x0); // 10
7846 break;
7848 GetSession()->SendPacket(&data);
7851 uint32 Player::GetXPRestBonus(uint32 xp)
7853 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7855 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7856 rested_bonus = xp;
7858 SetRestBonus( GetRestBonus() - rested_bonus);
7860 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7861 return rested_bonus;
7864 void Player::SetBindPoint(uint64 guid)
7866 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7867 data << uint64(guid);
7868 GetSession()->SendPacket( &data );
7871 void Player::SendTalentWipeConfirm(uint64 guid)
7873 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7874 data << uint64(guid);
7875 data << uint32(resetTalentsCost());
7876 GetSession()->SendPacket( &data );
7879 void Player::SendPetSkillWipeConfirm()
7881 Pet* pet = GetPet();
7882 if(!pet)
7883 return;
7884 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7885 data << pet->GetGUID();
7886 data << uint32(pet->resetTalentsCost());
7887 GetSession()->SendPacket( &data );
7890 /*********************************************************/
7891 /*** STORAGE SYSTEM ***/
7892 /*********************************************************/
7894 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7896 assert(i < 3);
7897 if(i < 2 && item)
7899 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7900 return;
7901 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7902 if(charges == 0)
7903 return;
7904 if(charges > 1)
7905 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7906 else if(charges <= 1)
7908 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7909 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7914 void Player::SetSheath( SheathState sheathed )
7916 switch (sheathed)
7918 case SHEATH_STATE_UNARMED: // no prepared weapon
7919 SetVirtualItemSlot(0,NULL);
7920 SetVirtualItemSlot(1,NULL);
7921 SetVirtualItemSlot(2,NULL);
7922 break;
7923 case SHEATH_STATE_MELEE: // prepared melee weapon
7925 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7926 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7927 SetVirtualItemSlot(2,NULL);
7928 }; break;
7929 case SHEATH_STATE_RANGED: // prepared ranged weapon
7930 SetVirtualItemSlot(0,NULL);
7931 SetVirtualItemSlot(1,NULL);
7932 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7933 break;
7934 default:
7935 SetVirtualItemSlot(0,NULL);
7936 SetVirtualItemSlot(1,NULL);
7937 SetVirtualItemSlot(2,NULL);
7938 break;
7940 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
7943 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7945 uint8 pClass = getClass();
7947 uint8 slots[4];
7948 slots[0] = NULL_SLOT;
7949 slots[1] = NULL_SLOT;
7950 slots[2] = NULL_SLOT;
7951 slots[3] = NULL_SLOT;
7952 switch( proto->InventoryType )
7954 case INVTYPE_HEAD:
7955 slots[0] = EQUIPMENT_SLOT_HEAD;
7956 break;
7957 case INVTYPE_NECK:
7958 slots[0] = EQUIPMENT_SLOT_NECK;
7959 break;
7960 case INVTYPE_SHOULDERS:
7961 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7962 break;
7963 case INVTYPE_BODY:
7964 slots[0] = EQUIPMENT_SLOT_BODY;
7965 break;
7966 case INVTYPE_CHEST:
7967 slots[0] = EQUIPMENT_SLOT_CHEST;
7968 break;
7969 case INVTYPE_ROBE:
7970 slots[0] = EQUIPMENT_SLOT_CHEST;
7971 break;
7972 case INVTYPE_WAIST:
7973 slots[0] = EQUIPMENT_SLOT_WAIST;
7974 break;
7975 case INVTYPE_LEGS:
7976 slots[0] = EQUIPMENT_SLOT_LEGS;
7977 break;
7978 case INVTYPE_FEET:
7979 slots[0] = EQUIPMENT_SLOT_FEET;
7980 break;
7981 case INVTYPE_WRISTS:
7982 slots[0] = EQUIPMENT_SLOT_WRISTS;
7983 break;
7984 case INVTYPE_HANDS:
7985 slots[0] = EQUIPMENT_SLOT_HANDS;
7986 break;
7987 case INVTYPE_FINGER:
7988 slots[0] = EQUIPMENT_SLOT_FINGER1;
7989 slots[1] = EQUIPMENT_SLOT_FINGER2;
7990 break;
7991 case INVTYPE_TRINKET:
7992 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7993 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7994 break;
7995 case INVTYPE_CLOAK:
7996 slots[0] = EQUIPMENT_SLOT_BACK;
7997 break;
7998 case INVTYPE_WEAPON:
8000 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8002 // suggest offhand slot only if know dual wielding
8003 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8004 if(CanDualWield())
8005 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8006 break;
8008 case INVTYPE_SHIELD:
8009 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8010 break;
8011 case INVTYPE_RANGED:
8012 slots[0] = EQUIPMENT_SLOT_RANGED;
8013 break;
8014 case INVTYPE_2HWEAPON:
8015 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8016 if (CanDualWield() && CanTitanGrip())
8017 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8018 break;
8019 case INVTYPE_TABARD:
8020 slots[0] = EQUIPMENT_SLOT_TABARD;
8021 break;
8022 case INVTYPE_WEAPONMAINHAND:
8023 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8024 break;
8025 case INVTYPE_WEAPONOFFHAND:
8026 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8027 break;
8028 case INVTYPE_HOLDABLE:
8029 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8030 break;
8031 case INVTYPE_THROWN:
8032 slots[0] = EQUIPMENT_SLOT_RANGED;
8033 break;
8034 case INVTYPE_RANGEDRIGHT:
8035 slots[0] = EQUIPMENT_SLOT_RANGED;
8036 break;
8037 case INVTYPE_BAG:
8038 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8039 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8040 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8041 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8042 break;
8043 case INVTYPE_RELIC:
8045 switch(proto->SubClass)
8047 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8048 if (pClass == CLASS_PALADIN)
8049 slots[0] = EQUIPMENT_SLOT_RANGED;
8050 break;
8051 case ITEM_SUBCLASS_ARMOR_IDOL:
8052 if (pClass == CLASS_DRUID)
8053 slots[0] = EQUIPMENT_SLOT_RANGED;
8054 break;
8055 case ITEM_SUBCLASS_ARMOR_TOTEM:
8056 if (pClass == CLASS_SHAMAN)
8057 slots[0] = EQUIPMENT_SLOT_RANGED;
8058 break;
8059 case ITEM_SUBCLASS_ARMOR_MISC:
8060 if (pClass == CLASS_WARLOCK)
8061 slots[0] = EQUIPMENT_SLOT_RANGED;
8062 break;
8063 case ITEM_SUBCLASS_ARMOR_SIGIL:
8064 if (pClass == CLASS_DEATH_KNIGHT)
8065 slots[0] = EQUIPMENT_SLOT_RANGED;
8066 break;
8068 break;
8070 default :
8071 return NULL_SLOT;
8074 if( slot != NULL_SLOT )
8076 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8078 for (int i = 0; i < 4; ++i)
8080 if ( slots[i] == slot )
8081 return slot;
8085 else
8087 // search free slot at first
8088 for (int i = 0; i < 4; ++i)
8090 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8092 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8093 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8094 return slots[i];
8098 // if not found free and can swap return first appropriate from used
8099 for (int i = 0; i < 4; ++i)
8101 if ( slots[i] != NULL_SLOT && swap )
8102 return slots[i];
8106 // no free position
8107 return NULL_SLOT;
8110 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8112 Item *pItem;
8113 uint32 tempcount = 0;
8115 uint8 res = EQUIP_ERR_OK;
8117 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8119 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8120 if( pItem && pItem->GetEntry() == item )
8122 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8123 if(ires==EQUIP_ERR_OK)
8125 tempcount += pItem->GetCount();
8126 if( tempcount >= count )
8127 return EQUIP_ERR_OK;
8129 else
8130 res = ires;
8133 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8135 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8136 if( pItem && pItem->GetEntry() == item )
8138 tempcount += pItem->GetCount();
8139 if( tempcount >= count )
8140 return EQUIP_ERR_OK;
8143 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8145 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem->GetEntry() == item )
8148 tempcount += pItem->GetCount();
8149 if( tempcount >= count )
8150 return EQUIP_ERR_OK;
8153 Bag *pBag;
8154 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8156 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8157 if( pBag )
8159 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8161 pItem = GetItemByPos( i, j );
8162 if( pItem && pItem->GetEntry() == item )
8164 tempcount += pItem->GetCount();
8165 if( tempcount >= count )
8166 return EQUIP_ERR_OK;
8172 // not found req. item count and have unequippable items
8173 return res;
8176 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8178 uint32 count = 0;
8179 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8181 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8182 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8183 count += pItem->GetCount();
8185 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8187 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8188 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8189 count += pItem->GetCount();
8191 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8193 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8194 if( pBag )
8195 count += pBag->GetItemCount(item,skipItem);
8198 if(skipItem && skipItem->GetProto()->GemProperties)
8200 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8202 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8203 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8204 count += pItem->GetGemCountWithID(item);
8208 if(inBankAlso)
8210 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8212 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8213 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8214 count += pItem->GetCount();
8216 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8218 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8219 if( pBag )
8220 count += pBag->GetItemCount(item,skipItem);
8223 if(skipItem && skipItem->GetProto()->GemProperties)
8225 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8227 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8228 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8229 count += pItem->GetGemCountWithID(item);
8234 return count;
8237 Item* Player::GetItemByGuid( uint64 guid ) const
8239 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8241 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8242 if( pItem && pItem->GetGUID() == guid )
8243 return pItem;
8245 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8247 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8248 if( pItem && pItem->GetGUID() == guid )
8249 return pItem;
8252 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8254 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8255 if( pBag )
8257 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8259 Item* pItem = pBag->GetItemByPos( j );
8260 if( pItem && pItem->GetGUID() == guid )
8261 return pItem;
8265 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8267 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8268 if( pBag )
8270 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8272 Item* pItem = pBag->GetItemByPos( j );
8273 if( pItem && pItem->GetGUID() == guid )
8274 return pItem;
8279 return NULL;
8282 Item* Player::GetItemByPos( uint16 pos ) const
8284 uint8 bag = pos >> 8;
8285 uint8 slot = pos & 255;
8286 return GetItemByPos( bag, slot );
8289 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8291 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8292 return m_items[slot];
8293 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8294 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8296 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8297 if ( pBag )
8298 return pBag->GetItemByPos(slot);
8300 return NULL;
8303 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8305 uint16 slot;
8306 switch (attackType)
8308 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8309 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8310 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8311 default: return NULL;
8314 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8315 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8316 return NULL;
8318 if(!useable)
8319 return item;
8321 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8322 return NULL;
8324 return item;
8327 Item* Player::GetShield(bool useable) const
8329 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8330 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8331 return NULL;
8333 if(!useable)
8334 return item;
8336 if( item->IsBroken())
8337 return NULL;
8339 return item;
8342 uint32 Player::GetAttackBySlot( uint8 slot )
8344 switch(slot)
8346 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8347 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8348 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8349 default: return MAX_ATTACK;
8353 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8355 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8356 return true;
8357 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8358 return true;
8359 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8360 return true;
8361 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8362 return true;
8363 return false;
8366 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8368 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8369 return true;
8370 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8371 return true;
8372 return false;
8375 bool Player::IsBankPos( uint8 bag, uint8 slot )
8377 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8378 return true;
8379 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8380 return true;
8381 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8382 return true;
8383 return false;
8386 bool Player::IsBagPos( uint16 pos )
8388 uint8 bag = pos >> 8;
8389 uint8 slot = pos & 255;
8390 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8391 return true;
8392 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8393 return true;
8394 return false;
8397 bool Player::IsValidPos( uint8 bag, uint8 slot )
8399 // post selected
8400 if(bag == NULL_BAG)
8401 return true;
8403 if (bag == INVENTORY_SLOT_BAG_0)
8405 // any post selected
8406 if (slot == NULL_SLOT)
8407 return true;
8409 // equipment
8410 if (slot < EQUIPMENT_SLOT_END)
8411 return true;
8413 // bag equip slots
8414 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8415 return true;
8417 // backpack slots
8418 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8419 return true;
8421 // keyring slots
8422 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8423 return true;
8425 // bank main slots
8426 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8427 return true;
8429 // bank bag slots
8430 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8431 return true;
8433 return false;
8436 // bag content slots
8437 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8439 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8440 if(!pBag)
8441 return false;
8443 // any post selected
8444 if (slot == NULL_SLOT)
8445 return true;
8447 return slot < pBag->GetBagSize();
8450 // bank bag content slots
8451 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8453 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8454 if(!pBag)
8455 return false;
8457 // any post selected
8458 if (slot == NULL_SLOT)
8459 return true;
8461 return slot < pBag->GetBagSize();
8464 // where this?
8465 return false;
8469 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8471 uint32 tempcount = 0;
8472 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8474 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8475 if( pItem && pItem->GetEntry() == item )
8477 tempcount += pItem->GetCount();
8478 if( tempcount >= count )
8479 return true;
8482 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8484 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8485 if( pItem && pItem->GetEntry() == item )
8487 tempcount += pItem->GetCount();
8488 if( tempcount >= count )
8489 return true;
8492 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8494 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8496 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8498 Item* pItem = GetItemByPos( i, j );
8499 if( pItem && pItem->GetEntry() == item )
8501 tempcount += pItem->GetCount();
8502 if( tempcount >= count )
8503 return true;
8509 if(inBankAlso)
8511 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8513 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8514 if( pItem && pItem->GetEntry() == item )
8516 tempcount += pItem->GetCount();
8517 if( tempcount >= count )
8518 return true;
8521 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8523 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8525 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8527 Item* pItem = GetItemByPos( i, j );
8528 if( pItem && pItem->GetEntry() == item )
8530 tempcount += pItem->GetCount();
8531 if( tempcount >= count )
8532 return true;
8539 return false;
8542 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8544 uint32 tempcount = 0;
8545 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8547 if(i==int(except_slot))
8548 continue;
8550 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8551 if( pItem && pItem->GetEntry() == item)
8553 tempcount += pItem->GetCount();
8554 if( tempcount >= count )
8555 return true;
8559 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8560 if (pProto && pProto->GemProperties)
8562 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8564 if(i==int(except_slot))
8565 continue;
8567 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8568 if( pItem && pItem->GetProto()->Socket[0].Color)
8570 tempcount += pItem->GetGemCountWithID(item);
8571 if( tempcount >= count )
8572 return true;
8577 return false;
8580 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8582 uint32 tempcount = 0;
8583 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8585 if(i==int(except_slot))
8586 continue;
8588 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8589 if (!pItem)
8590 continue;
8592 ItemPrototype const *pProto = pItem->GetProto();
8593 if (!pProto)
8594 continue;
8596 if (pProto->ItemLimitCategory == limitCategory)
8598 tempcount += pItem->GetCount();
8599 if( tempcount >= count )
8600 return true;
8603 if( pProto->Socket[0].Color)
8605 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8606 if( tempcount >= count )
8607 return true;
8611 return false;
8614 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8616 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8617 if( !pProto )
8619 if(no_space_count)
8620 *no_space_count = count;
8621 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8624 // no maximum
8625 if(pProto->MaxCount <= 0)
8626 return EQUIP_ERR_OK;
8628 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8630 if (curcount + count > uint32(pProto->MaxCount))
8632 if(no_space_count)
8633 *no_space_count = count +curcount - pProto->MaxCount;
8634 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8637 return EQUIP_ERR_OK;
8640 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8642 Item *pItem;
8643 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8645 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8646 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8647 return true;
8649 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8651 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8652 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8653 return true;
8655 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8657 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8659 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8661 pItem = GetItemByPos( i, j );
8662 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8663 return true;
8667 return false;
8670 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8672 Item* pItem2 = GetItemByPos( bag, slot );
8674 // ignore move item (this slot will be empty at move)
8675 if(pItem2==pSrcItem)
8676 pItem2 = NULL;
8678 uint32 need_space;
8680 // empty specific slot - check item fit to slot
8681 if( !pItem2 || swap )
8683 if( bag == INVENTORY_SLOT_BAG_0 )
8685 // keyring case
8686 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8687 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8689 // currencytoken case
8690 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8691 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8693 // prevent cheating
8694 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8695 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8697 else
8699 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8700 if( !pBag )
8701 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8703 ItemPrototype const* pBagProto = pBag->GetProto();
8704 if( !pBagProto )
8705 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8707 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8708 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8711 // non empty stack with space
8712 need_space = pProto->GetMaxStackSize();
8714 // non empty slot, check item type
8715 else
8717 // check item type
8718 if(pItem2->GetEntry() != pProto->ItemId)
8719 return EQUIP_ERR_ITEM_CANT_STACK;
8721 // check free space
8722 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8723 return EQUIP_ERR_ITEM_CANT_STACK;
8725 // free stack space or infinity
8726 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8729 if(need_space > count)
8730 need_space = count;
8732 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8733 if(!newPosition.isContainedIn(dest))
8735 dest.push_back(newPosition);
8736 count -= need_space;
8738 return EQUIP_ERR_OK;
8741 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
8743 // skip specific bag already processed in first called _CanStoreItem_InBag
8744 if(bag==skip_bag)
8745 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8747 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8748 if( !pBag )
8749 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8751 ItemPrototype const* pBagProto = pBag->GetProto();
8752 if( !pBagProto )
8753 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8755 // specialized bag mode or non-specilized
8756 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8757 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8759 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8760 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8762 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8764 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8765 if(j==skip_slot)
8766 continue;
8768 Item* pItem2 = GetItemByPos( bag, j );
8770 // ignore move item (this slot will be empty at move)
8771 if(pItem2==pSrcItem)
8772 pItem2 = NULL;
8774 // if merge skip empty, if !merge skip non-empty
8775 if((pItem2!=NULL)!=merge)
8776 continue;
8778 if( pItem2 )
8780 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8782 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8783 if(need_space > count)
8784 need_space = count;
8786 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8787 if(!newPosition.isContainedIn(dest))
8789 dest.push_back(newPosition);
8790 count -= need_space;
8792 if(count==0)
8793 return EQUIP_ERR_OK;
8797 else
8799 uint32 need_space = pProto->GetMaxStackSize();
8800 if(need_space > count)
8801 need_space = count;
8803 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8804 if(!newPosition.isContainedIn(dest))
8806 dest.push_back(newPosition);
8807 count -= need_space;
8809 if(count==0)
8810 return EQUIP_ERR_OK;
8814 return EQUIP_ERR_OK;
8817 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
8819 for(uint32 j = slot_begin; j < slot_end; ++j)
8821 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8822 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8823 continue;
8825 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8827 // ignore move item (this slot will be empty at move)
8828 if(pItem2==pSrcItem)
8829 pItem2 = NULL;
8831 // if merge skip empty, if !merge skip non-empty
8832 if((pItem2!=NULL)!=merge)
8833 continue;
8835 if( pItem2 )
8837 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8839 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8840 if(need_space > count)
8841 need_space = count;
8842 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8843 if(!newPosition.isContainedIn(dest))
8845 dest.push_back(newPosition);
8846 count -= need_space;
8848 if(count==0)
8849 return EQUIP_ERR_OK;
8853 else
8855 uint32 need_space = pProto->GetMaxStackSize();
8856 if(need_space > count)
8857 need_space = count;
8859 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8860 if(!newPosition.isContainedIn(dest))
8862 dest.push_back(newPosition);
8863 count -= need_space;
8865 if(count==0)
8866 return EQUIP_ERR_OK;
8870 return EQUIP_ERR_OK;
8873 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8875 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8877 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8878 if( !pProto )
8880 if(no_space_count)
8881 *no_space_count = count;
8882 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8885 if(pItem && pItem->IsBindedNotWith(this))
8887 if(no_space_count)
8888 *no_space_count = count;
8889 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8892 // check count of items (skip for auto move for same player from bank)
8893 uint32 no_similar_count = 0; // can't store this amount similar items
8894 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8895 if(res!=EQUIP_ERR_OK)
8897 if(count==no_similar_count)
8899 if(no_space_count)
8900 *no_space_count = no_similar_count;
8901 return res;
8903 count -= no_similar_count;
8906 // in specific slot
8907 if( bag != NULL_BAG && slot != NULL_SLOT )
8909 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8910 if(res!=EQUIP_ERR_OK)
8912 if(no_space_count)
8913 *no_space_count = count + no_similar_count;
8914 return res;
8917 if(count==0)
8919 if(no_similar_count==0)
8920 return EQUIP_ERR_OK;
8922 if(no_space_count)
8923 *no_space_count = count + no_similar_count;
8924 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8928 // not specific slot or have space for partly store only in specific slot
8930 // in specific bag
8931 if( bag != NULL_BAG )
8933 // search stack in bag for merge to
8934 if( pProto->Stackable != 1 )
8936 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8938 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8939 if(res!=EQUIP_ERR_OK)
8941 if(no_space_count)
8942 *no_space_count = count + no_similar_count;
8943 return res;
8946 if(count==0)
8948 if(no_similar_count==0)
8949 return EQUIP_ERR_OK;
8951 if(no_space_count)
8952 *no_space_count = count + no_similar_count;
8953 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8956 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8957 if(res!=EQUIP_ERR_OK)
8959 if(no_space_count)
8960 *no_space_count = count + no_similar_count;
8961 return res;
8964 if(count==0)
8966 if(no_similar_count==0)
8967 return EQUIP_ERR_OK;
8969 if(no_space_count)
8970 *no_space_count = count + no_similar_count;
8971 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8974 else // equipped bag
8976 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8977 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8978 if(res!=EQUIP_ERR_OK)
8979 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8981 if(res!=EQUIP_ERR_OK)
8983 if(no_space_count)
8984 *no_space_count = count + no_similar_count;
8985 return res;
8988 if(count==0)
8990 if(no_similar_count==0)
8991 return EQUIP_ERR_OK;
8993 if(no_space_count)
8994 *no_space_count = count + no_similar_count;
8995 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9000 // search free slot in bag for place to
9001 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9003 // search free slot - keyring case
9004 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9006 uint32 keyringSize = GetMaxKeyringSize();
9007 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9008 if(res!=EQUIP_ERR_OK)
9010 if(no_space_count)
9011 *no_space_count = count + no_similar_count;
9012 return res;
9015 if(count==0)
9017 if(no_similar_count==0)
9018 return EQUIP_ERR_OK;
9020 if(no_space_count)
9021 *no_space_count = count + no_similar_count;
9022 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9025 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9026 if(res!=EQUIP_ERR_OK)
9028 if(no_space_count)
9029 *no_space_count = count + no_similar_count;
9030 return res;
9033 if(count==0)
9035 if(no_similar_count==0)
9036 return EQUIP_ERR_OK;
9038 if(no_space_count)
9039 *no_space_count = count + no_similar_count;
9040 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9043 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9045 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9046 if(res!=EQUIP_ERR_OK)
9048 if(no_space_count)
9049 *no_space_count = count + no_similar_count;
9050 return res;
9053 if(count==0)
9055 if(no_similar_count==0)
9056 return EQUIP_ERR_OK;
9058 if(no_space_count)
9059 *no_space_count = count + no_similar_count;
9060 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9064 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9065 if(res!=EQUIP_ERR_OK)
9067 if(no_space_count)
9068 *no_space_count = count + no_similar_count;
9069 return res;
9072 if(count==0)
9074 if(no_similar_count==0)
9075 return EQUIP_ERR_OK;
9077 if(no_space_count)
9078 *no_space_count = count + no_similar_count;
9079 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9082 else // equipped bag
9084 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9085 if(res!=EQUIP_ERR_OK)
9086 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9088 if(res!=EQUIP_ERR_OK)
9090 if(no_space_count)
9091 *no_space_count = count + no_similar_count;
9092 return res;
9095 if(count==0)
9097 if(no_similar_count==0)
9098 return EQUIP_ERR_OK;
9100 if(no_space_count)
9101 *no_space_count = count + no_similar_count;
9102 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9107 // not specific bag or have space for partly store only in specific bag
9109 // search stack for merge to
9110 if( pProto->Stackable != 1 )
9112 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9113 if(res!=EQUIP_ERR_OK)
9115 if(no_space_count)
9116 *no_space_count = count + no_similar_count;
9117 return res;
9120 if(count==0)
9122 if(no_similar_count==0)
9123 return EQUIP_ERR_OK;
9125 if(no_space_count)
9126 *no_space_count = count + no_similar_count;
9127 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9130 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9131 if(res!=EQUIP_ERR_OK)
9133 if(no_space_count)
9134 *no_space_count = count + no_similar_count;
9135 return res;
9138 if(count==0)
9140 if(no_similar_count==0)
9141 return EQUIP_ERR_OK;
9143 if(no_space_count)
9144 *no_space_count = count + no_similar_count;
9145 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9148 if( pProto->BagFamily )
9150 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9152 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9153 if(res!=EQUIP_ERR_OK)
9154 continue;
9156 if(count==0)
9158 if(no_similar_count==0)
9159 return EQUIP_ERR_OK;
9161 if(no_space_count)
9162 *no_space_count = count + no_similar_count;
9163 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9168 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9170 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9171 if(res!=EQUIP_ERR_OK)
9172 continue;
9174 if(count==0)
9176 if(no_similar_count==0)
9177 return EQUIP_ERR_OK;
9179 if(no_space_count)
9180 *no_space_count = count + no_similar_count;
9181 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9186 // search free slot - special bag case
9187 if( pProto->BagFamily )
9189 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9191 uint32 keyringSize = GetMaxKeyringSize();
9192 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9193 if(res!=EQUIP_ERR_OK)
9195 if(no_space_count)
9196 *no_space_count = count + no_similar_count;
9197 return res;
9200 if(count==0)
9202 if(no_similar_count==0)
9203 return EQUIP_ERR_OK;
9205 if(no_space_count)
9206 *no_space_count = count + no_similar_count;
9207 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9210 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9212 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9213 if(res!=EQUIP_ERR_OK)
9215 if(no_space_count)
9216 *no_space_count = count + no_similar_count;
9217 return res;
9220 if(count==0)
9222 if(no_similar_count==0)
9223 return EQUIP_ERR_OK;
9225 if(no_space_count)
9226 *no_space_count = count + no_similar_count;
9227 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9231 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9233 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9234 if(res!=EQUIP_ERR_OK)
9235 continue;
9237 if(count==0)
9239 if(no_similar_count==0)
9240 return EQUIP_ERR_OK;
9242 if(no_space_count)
9243 *no_space_count = count + no_similar_count;
9244 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9249 // search free slot
9250 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9251 if(res!=EQUIP_ERR_OK)
9253 if(no_space_count)
9254 *no_space_count = count + no_similar_count;
9255 return res;
9258 if(count==0)
9260 if(no_similar_count==0)
9261 return EQUIP_ERR_OK;
9263 if(no_space_count)
9264 *no_space_count = count + no_similar_count;
9265 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9268 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9270 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9271 if(res!=EQUIP_ERR_OK)
9272 continue;
9274 if(count==0)
9276 if(no_similar_count==0)
9277 return EQUIP_ERR_OK;
9279 if(no_space_count)
9280 *no_space_count = count + no_similar_count;
9281 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9285 if(no_space_count)
9286 *no_space_count = count + no_similar_count;
9288 return EQUIP_ERR_INVENTORY_FULL;
9291 //////////////////////////////////////////////////////////////////////////
9292 uint8 Player::CanStoreItems( Item **pItems,int count) const
9294 Item *pItem2;
9296 // fill space table
9297 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9298 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9299 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9300 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9302 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9303 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9304 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9305 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9307 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9309 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9311 if (pItem2 && !pItem2->IsInTrade())
9313 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9317 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9319 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9321 if (pItem2 && !pItem2->IsInTrade())
9323 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9327 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9329 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9331 if (pItem2 && !pItem2->IsInTrade())
9333 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9337 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9339 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9341 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9343 pItem2 = GetItemByPos( i, j );
9344 if (pItem2 && !pItem2->IsInTrade())
9346 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9352 // check free space for all items
9353 for (int k = 0; k < count; ++k)
9355 Item *pItem = pItems[k];
9357 // no item
9358 if (!pItem) continue;
9360 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9361 ItemPrototype const *pProto = pItem->GetProto();
9363 // strange item
9364 if( !pProto )
9365 return EQUIP_ERR_ITEM_NOT_FOUND;
9367 // item it 'bind'
9368 if(pItem->IsBindedNotWith(this))
9369 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9371 Bag *pBag;
9372 ItemPrototype const *pBagProto;
9374 // item is 'one item only'
9375 uint8 res = CanTakeMoreSimilarItems(pItem);
9376 if(res != EQUIP_ERR_OK)
9377 return res;
9379 // search stack for merge to
9380 if( pProto->Stackable != 1 )
9382 bool b_found = false;
9384 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9386 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9387 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9389 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9390 b_found = true;
9391 break;
9394 if (b_found) continue;
9396 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9398 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9399 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9401 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9402 b_found = true;
9403 break;
9406 if (b_found) continue;
9408 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9410 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9411 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9413 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9414 b_found = true;
9415 break;
9418 if (b_found) continue;
9420 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9422 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9423 if( pBag )
9425 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9427 pItem2 = GetItemByPos( t, j );
9428 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9430 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9431 b_found = true;
9432 break;
9437 if (b_found) continue;
9440 // special bag case
9441 if( pProto->BagFamily )
9443 bool b_found = false;
9444 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9446 uint32 keyringSize = GetMaxKeyringSize();
9447 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9449 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9451 inv_keys[t-KEYRING_SLOT_START] = 1;
9452 b_found = true;
9453 break;
9458 if (b_found) continue;
9460 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9462 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9464 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9466 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9467 b_found = true;
9468 break;
9473 if (b_found) continue;
9475 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9477 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9478 if( pBag )
9480 pBagProto = pBag->GetProto();
9482 // not plain container check
9483 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9484 ItemCanGoIntoBag(pProto,pBagProto) )
9486 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9488 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9490 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9491 b_found = true;
9492 break;
9498 if (b_found) continue;
9501 // search free slot
9502 bool b_found = false;
9503 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9505 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9507 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9508 b_found = true;
9509 break;
9512 if (b_found) continue;
9514 // search free slot in bags
9515 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9517 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9518 if( pBag )
9520 pBagProto = pBag->GetProto();
9522 // special bag already checked
9523 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9524 continue;
9526 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9528 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9530 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9531 b_found = true;
9532 break;
9538 // no free slot found?
9539 if (!b_found)
9540 return EQUIP_ERR_INVENTORY_FULL;
9543 return EQUIP_ERR_OK;
9546 //////////////////////////////////////////////////////////////////////////
9547 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9549 dest = 0;
9550 Item *pItem = Item::CreateItem( item, 1, this );
9551 if( pItem )
9553 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9554 delete pItem;
9555 return result;
9558 return EQUIP_ERR_ITEM_NOT_FOUND;
9561 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9563 dest = 0;
9564 if( pItem )
9566 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9567 ItemPrototype const *pProto = pItem->GetProto();
9568 if( pProto )
9570 if(pItem->IsBindedNotWith(this))
9571 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9573 // check count of items (skip for auto move for same player from bank)
9574 uint8 res = CanTakeMoreSimilarItems(pItem);
9575 if(res != EQUIP_ERR_OK)
9576 return res;
9578 // check this only in game
9579 if(not_loading)
9581 // May be here should be more stronger checks; STUNNED checked
9582 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9583 if (hasUnitState(UNIT_STAT_STUNNED))
9584 return EQUIP_ERR_YOU_ARE_STUNNED;
9586 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9587 // - combat
9588 // - in-progress arenas
9589 if( !pProto->CanChangeEquipStateInCombat() )
9591 if( isInCombat() )
9592 return EQUIP_ERR_NOT_IN_COMBAT;
9594 if(BattleGround* bg = GetBattleGround())
9595 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9596 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9599 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9600 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9602 if(IsNonMeleeSpellCasted(false))
9603 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9606 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9607 if (ssd && ssd->MaxLevel < getLevel())
9608 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9610 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9611 if (eslot == NULL_SLOT)
9612 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9614 uint8 msg = CanUseItem(pItem , not_loading);
9615 if (msg != EQUIP_ERR_OK)
9616 return msg;
9617 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9618 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9620 // if swap ignore item (equipped also)
9621 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9622 return res2;
9624 // check unique-equipped special item classes
9625 if (pProto->Class == ITEM_CLASS_QUIVER)
9627 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9629 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9631 if (pBag != pItem)
9633 if (ItemPrototype const* pBagProto = pBag->GetProto())
9635 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9636 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9637 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9638 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9645 uint32 type = pProto->InventoryType;
9647 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9649 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9651 if (!CanDualWield())
9652 return EQUIP_ERR_CANT_DUAL_WIELD;
9654 else if (type == INVTYPE_2HWEAPON)
9656 if (!CanDualWield() || !CanTitanGrip())
9657 return EQUIP_ERR_CANT_DUAL_WIELD;
9660 if (IsTwoHandUsed())
9661 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9664 // equip two-hand weapon case (with possible unequip 2 items)
9665 if (type == INVTYPE_2HWEAPON)
9667 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9669 if (!CanTitanGrip())
9670 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9672 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9673 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9675 if (!CanTitanGrip())
9677 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9678 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9679 ItemPosCountVec off_dest;
9680 if (offItem && (!not_loading ||
9681 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9682 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9683 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9686 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9687 return EQUIP_ERR_OK;
9691 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9694 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9696 // Applied only to equipped items and bank bags
9697 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9698 return EQUIP_ERR_OK;
9700 Item* pItem = GetItemByPos(pos);
9702 // Applied only to existed equipped item
9703 if( !pItem )
9704 return EQUIP_ERR_OK;
9706 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9708 ItemPrototype const *pProto = pItem->GetProto();
9709 if( !pProto )
9710 return EQUIP_ERR_ITEM_NOT_FOUND;
9712 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9713 // - combat
9714 // - in-progress arenas
9715 if( !pProto->CanChangeEquipStateInCombat() )
9717 if( isInCombat() )
9718 return EQUIP_ERR_NOT_IN_COMBAT;
9720 if(BattleGround* bg = GetBattleGround())
9721 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9722 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9725 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9726 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9728 return EQUIP_ERR_OK;
9731 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9733 if (!pItem)
9734 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9736 uint32 count = pItem->GetCount();
9738 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9739 ItemPrototype const *pProto = pItem->GetProto();
9740 if (!pProto)
9741 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9743 if (pItem->IsBindedNotWith(this))
9744 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9746 // check count of items (skip for auto move for same player from bank)
9747 uint8 res = CanTakeMoreSimilarItems(pItem);
9748 if (res != EQUIP_ERR_OK)
9749 return res;
9751 // in specific slot
9752 if (bag != NULL_BAG && slot != NULL_SLOT)
9754 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9756 if (!pItem->IsBag())
9757 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9759 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9760 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9762 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9763 return cantuse;
9766 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9767 if (res!=EQUIP_ERR_OK)
9768 return res;
9770 if (count==0)
9771 return EQUIP_ERR_OK;
9774 // not specific slot or have space for partly store only in specific slot
9776 // in specific bag
9777 if( bag != NULL_BAG )
9779 if( pProto->InventoryType == INVTYPE_BAG )
9781 Bag *pBag = (Bag*)pItem;
9782 if( pBag && !pBag->IsEmpty() )
9783 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9786 // search stack in bag for merge to
9787 if( pProto->Stackable != 1 )
9789 if( bag == INVENTORY_SLOT_BAG_0 )
9791 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9792 if(res!=EQUIP_ERR_OK)
9793 return res;
9795 if(count==0)
9796 return EQUIP_ERR_OK;
9798 else
9800 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9801 if(res!=EQUIP_ERR_OK)
9802 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9804 if(res!=EQUIP_ERR_OK)
9805 return res;
9807 if(count==0)
9808 return EQUIP_ERR_OK;
9812 // search free slot in bag
9813 if( bag == INVENTORY_SLOT_BAG_0 )
9815 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9816 if(res!=EQUIP_ERR_OK)
9817 return res;
9819 if(count==0)
9820 return EQUIP_ERR_OK;
9822 else
9824 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9825 if(res != EQUIP_ERR_OK)
9826 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9828 if(res != EQUIP_ERR_OK)
9829 return res;
9831 if(count == 0)
9832 return EQUIP_ERR_OK;
9836 // not specific bag or have space for partly store only in specific bag
9838 // search stack for merge to
9839 if( pProto->Stackable != 1 )
9841 // in slots
9842 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9843 if(res != EQUIP_ERR_OK)
9844 return res;
9846 if(count == 0)
9847 return EQUIP_ERR_OK;
9849 // in special bags
9850 if( pProto->BagFamily )
9852 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9854 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9855 if(res!=EQUIP_ERR_OK)
9856 continue;
9858 if(count==0)
9859 return EQUIP_ERR_OK;
9863 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9865 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9866 if(res!=EQUIP_ERR_OK)
9867 continue;
9869 if(count==0)
9870 return EQUIP_ERR_OK;
9874 // search free place in special bag
9875 if( pProto->BagFamily )
9877 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9879 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9880 if(res!=EQUIP_ERR_OK)
9881 continue;
9883 if(count==0)
9884 return EQUIP_ERR_OK;
9888 // search free space
9889 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9890 if(res!=EQUIP_ERR_OK)
9891 return res;
9893 if(count==0)
9894 return EQUIP_ERR_OK;
9896 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9898 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9899 if(res!=EQUIP_ERR_OK)
9900 continue;
9902 if(count==0)
9903 return EQUIP_ERR_OK;
9905 return EQUIP_ERR_BANK_FULL;
9908 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9910 if (pItem)
9912 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9914 if (!isAlive() && not_loading)
9915 return EQUIP_ERR_YOU_ARE_DEAD;
9917 //if (isStunned())
9918 // return EQUIP_ERR_YOU_ARE_STUNNED;
9920 ItemPrototype const *pProto = pItem->GetProto();
9921 if (pProto)
9923 if (pItem->IsBindedNotWith(this))
9924 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9926 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
9927 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9929 if (pItem->GetSkill() != 0)
9931 if (GetSkillValue( pItem->GetSkill() ) == 0)
9932 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9935 if (pProto->RequiredSkill != 0)
9937 if (GetSkillValue( pProto->RequiredSkill ) == 0)
9938 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9940 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
9941 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9944 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
9945 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9947 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
9948 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9950 if (getLevel() < pProto->RequiredLevel)
9951 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9953 return EQUIP_ERR_OK;
9956 return EQUIP_ERR_ITEM_NOT_FOUND;
9959 bool Player::CanUseItem( ItemPrototype const *pProto )
9961 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9963 if( pProto )
9965 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9966 return false;
9967 if( pProto->RequiredSkill != 0 )
9969 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9970 return false;
9971 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9972 return false;
9974 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9975 return false;
9976 if( getLevel() < pProto->RequiredLevel )
9977 return false;
9978 return true;
9980 return false;
9983 uint8 Player::CanUseAmmo( uint32 item ) const
9985 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9986 if( !isAlive() )
9987 return EQUIP_ERR_YOU_ARE_DEAD;
9988 //if( isStunned() )
9989 // return EQUIP_ERR_YOU_ARE_STUNNED;
9990 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9991 if( pProto )
9993 if( pProto->InventoryType!= INVTYPE_AMMO )
9994 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9995 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9996 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9997 if( pProto->RequiredSkill != 0 )
9999 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10000 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10001 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10002 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10004 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10005 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10006 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10007 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10009 if( getLevel() < pProto->RequiredLevel )
10010 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10012 // Requires No Ammo
10013 if(GetDummyAura(46699))
10014 return EQUIP_ERR_BAG_FULL6;
10016 return EQUIP_ERR_OK;
10018 return EQUIP_ERR_ITEM_NOT_FOUND;
10021 void Player::SetAmmo( uint32 item )
10023 if(!item)
10024 return;
10026 // already set
10027 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10028 return;
10030 // check ammo
10031 if(item)
10033 uint8 msg = CanUseAmmo( item );
10034 if( msg != EQUIP_ERR_OK )
10036 SendEquipError( msg, NULL, NULL );
10037 return;
10041 SetUInt32Value(PLAYER_AMMO_ID, item);
10043 _ApplyAmmoBonuses();
10046 void Player::RemoveAmmo()
10048 SetUInt32Value(PLAYER_AMMO_ID, 0);
10050 m_ammoDPS = 0.0f;
10052 if(CanModifyStats())
10053 UpdateDamagePhysical(RANGED_ATTACK);
10056 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10057 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10059 uint32 count = 0;
10060 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10061 count += itr->count;
10063 Item *pItem = Item::CreateItem( item, count, this );
10064 if( pItem )
10066 ItemAddedQuestCheck( item, count );
10067 if(randomPropertyId)
10068 pItem->SetItemRandomProperties(randomPropertyId);
10069 pItem = StoreItem( dest, pItem, update );
10071 return pItem;
10074 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10076 if( !pItem )
10077 return NULL;
10079 Item* lastItem = pItem;
10080 uint32 entry = pItem->GetEntry();
10081 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10083 uint16 pos = itr->pos;
10084 uint32 count = itr->count;
10086 ++itr;
10088 if(itr == dest.end())
10090 lastItem = _StoreItem(pos,pItem,count,false,update);
10091 break;
10094 lastItem = _StoreItem(pos,pItem,count,true,update);
10096 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10097 return lastItem;
10100 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10101 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10103 if( !pItem )
10104 return NULL;
10106 uint8 bag = pos >> 8;
10107 uint8 slot = pos & 255;
10109 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10111 Item *pItem2 = GetItemByPos( bag, slot );
10113 if (!pItem2)
10115 if (clone)
10116 pItem = pItem->CloneItem(count, this);
10117 else
10118 pItem->SetCount(count);
10120 if (!pItem)
10121 return NULL;
10123 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10124 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10125 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10126 pItem->SetBinding( true );
10128 if (bag == INVENTORY_SLOT_BAG_0)
10130 m_items[slot] = pItem;
10131 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10132 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10133 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10135 pItem->SetSlot( slot );
10136 pItem->SetContainer( NULL );
10138 // need update known currency
10139 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10140 UpdateKnownCurrencies(pItem->GetEntry(), true);
10142 if (IsInWorld() && update)
10144 pItem->AddToWorld();
10145 pItem->SendUpdateToPlayer( this );
10148 pItem->SetState(ITEM_CHANGED, this);
10150 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10152 pBag->StoreItem( slot, pItem, update );
10153 if( IsInWorld() && update )
10155 pItem->AddToWorld();
10156 pItem->SendUpdateToPlayer( this );
10158 pItem->SetState(ITEM_CHANGED, this);
10159 pBag->SetState(ITEM_CHANGED, this);
10162 AddEnchantmentDurations(pItem);
10163 AddItemDurations(pItem);
10165 return pItem;
10167 else
10169 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10170 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10171 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10172 pItem2->SetBinding( true );
10174 pItem2->SetCount( pItem2->GetCount() + count );
10175 if (IsInWorld() && update)
10176 pItem2->SendUpdateToPlayer( this );
10178 if (!clone)
10180 // delete item (it not in any slot currently)
10181 if (IsInWorld() && update)
10183 pItem->RemoveFromWorld();
10184 pItem->DestroyForPlayer( this );
10187 RemoveEnchantmentDurations(pItem);
10188 RemoveItemDurations(pItem);
10190 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10191 pItem->SetState(ITEM_REMOVED, this);
10194 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10195 AddEnchantmentDurations(pItem2);
10197 pItem2->SetState(ITEM_CHANGED, this);
10199 return pItem2;
10203 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10205 if (Item *pItem = Item::CreateItem( item, 1, this ))
10207 ItemAddedQuestCheck( item, 1 );
10208 return EquipItem( pos, pItem, update );
10211 return NULL;
10214 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10217 AddEnchantmentDurations(pItem);
10218 AddItemDurations(pItem);
10220 uint8 bag = pos >> 8;
10221 uint8 slot = pos & 255;
10223 Item *pItem2 = GetItemByPos( bag, slot );
10225 if( !pItem2 )
10227 VisualizeItem( slot, pItem);
10229 if(isAlive())
10231 ItemPrototype const *pProto = pItem->GetProto();
10233 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10234 if(pProto && pProto->ItemSet)
10235 AddItemsSetItem(this, pItem);
10237 _ApplyItemMods(pItem, slot, true);
10239 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10241 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10243 if (getClass() == CLASS_ROGUE)
10244 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10246 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10248 if (!spellProto)
10249 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10250 else
10252 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10254 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10255 data << uint64(GetGUID());
10256 data << uint8(1);
10257 data << uint32(cooldownSpell);
10258 data << uint32(0);
10259 GetSession()->SendPacket(&data);
10264 if( IsInWorld() && update )
10266 pItem->AddToWorld();
10267 pItem->SendUpdateToPlayer( this );
10270 ApplyEquipCooldown(pItem);
10272 if( slot == EQUIPMENT_SLOT_MAINHAND )
10273 UpdateExpertise(BASE_ATTACK);
10274 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10275 UpdateExpertise(OFF_ATTACK);
10277 else
10279 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10280 if( IsInWorld() && update )
10281 pItem2->SendUpdateToPlayer( this );
10283 // delete item (it not in any slot currently)
10284 //pItem->DeleteFromDB();
10285 if( IsInWorld() && update )
10287 pItem->RemoveFromWorld();
10288 pItem->DestroyForPlayer( this );
10291 RemoveEnchantmentDurations(pItem);
10292 RemoveItemDurations(pItem);
10294 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10295 pItem->SetState(ITEM_REMOVED, this);
10296 pItem2->SetState(ITEM_CHANGED, this);
10298 ApplyEquipCooldown(pItem2);
10300 return pItem2;
10303 // only for full equip instead adding to stack
10304 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10306 return pItem;
10309 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10311 if( pItem )
10313 AddEnchantmentDurations(pItem);
10314 AddItemDurations(pItem);
10316 uint8 slot = pos & 255;
10317 VisualizeItem( slot, pItem);
10319 if( IsInWorld() )
10321 pItem->AddToWorld();
10322 pItem->SendUpdateToPlayer( this );
10325 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10329 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10331 if(pItem)
10333 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10334 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10335 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10337 else
10339 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10340 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10344 void Player::VisualizeItem( uint8 slot, Item *pItem)
10346 if(!pItem)
10347 return;
10349 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10350 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10351 pItem->SetBinding( true );
10353 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10355 m_items[slot] = pItem;
10356 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10357 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10358 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10359 pItem->SetSlot( slot );
10360 pItem->SetContainer( NULL );
10362 if( slot < EQUIPMENT_SLOT_END )
10363 SetVisibleItemSlot(slot, pItem);
10365 pItem->SetState(ITEM_CHANGED, this);
10368 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10370 // note: removeitem does not actually change the item
10371 // it only takes the item out of storage temporarily
10372 // note2: if removeitem is to be used for delinking
10373 // the item must be removed from the player's updatequeue
10375 Item *pItem = GetItemByPos( bag, slot );
10376 if( pItem )
10378 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10380 RemoveEnchantmentDurations(pItem);
10381 RemoveItemDurations(pItem);
10383 if( bag == INVENTORY_SLOT_BAG_0 )
10385 if ( slot < INVENTORY_SLOT_BAG_END )
10387 ItemPrototype const *pProto = pItem->GetProto();
10388 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10390 if(pProto && pProto->ItemSet)
10391 RemoveItemsSetItem(this, pProto);
10393 _ApplyItemMods(pItem, slot, false);
10395 // remove item dependent auras and casts (only weapon and armor slots)
10396 if(slot < EQUIPMENT_SLOT_END)
10398 RemoveItemDependentAurasAndCasts(pItem);
10400 // remove held enchantments, update expertise
10401 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10403 if (pItem->GetItemSuffixFactor())
10405 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10406 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10408 else
10410 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10411 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10414 UpdateExpertise(BASE_ATTACK);
10416 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10417 UpdateExpertise(OFF_ATTACK);
10420 // need update known currency
10421 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10422 UpdateKnownCurrencies(pItem->GetEntry(), false);
10424 m_items[slot] = NULL;
10425 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10427 if ( slot < EQUIPMENT_SLOT_END )
10428 SetVisibleItemSlot(slot, NULL);
10430 else
10432 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10433 if( pBag )
10434 pBag->RemoveItem(slot, update);
10436 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10437 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10438 pItem->SetSlot( NULL_SLOT );
10439 if( IsInWorld() && update )
10440 pItem->SendUpdateToPlayer( this );
10444 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10445 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10447 if(Item* it = GetItemByPos(bag,slot))
10449 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10450 RemoveItem(bag, slot, update);
10451 it->RemoveFromUpdateQueueOf(this);
10452 if(it->IsInWorld())
10454 it->RemoveFromWorld();
10455 it->DestroyForPlayer( this );
10460 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10461 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10463 // update quest counters
10464 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10466 // store item
10467 Item* pLastItem = StoreItem(dest, pItem, update);
10469 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10470 if(pLastItem == pItem)
10472 // update owner for last item (this can be original item with wrong owner
10473 if(pLastItem->GetOwnerGUID() != GetGUID())
10474 pLastItem->SetOwnerGUID(GetGUID());
10476 // if this original item then it need create record in inventory
10477 // in case trade we already have item in other player inventory
10478 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10482 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10484 Item *pItem = GetItemByPos( bag, slot );
10485 if( pItem )
10487 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10489 // start from destroy contained items (only equipped bag can have its)
10490 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10492 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10493 DestroyItem(slot, i, update);
10496 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10497 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10499 RemoveEnchantmentDurations(pItem);
10500 RemoveItemDurations(pItem);
10502 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10504 if( bag == INVENTORY_SLOT_BAG_0 )
10506 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10508 // equipment and equipped bags can have applied bonuses
10509 if ( slot < INVENTORY_SLOT_BAG_END )
10511 ItemPrototype const *pProto = pItem->GetProto();
10513 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10514 if(pProto && pProto->ItemSet)
10515 RemoveItemsSetItem(this, pProto);
10517 _ApplyItemMods(pItem, slot, false);
10520 if ( slot < EQUIPMENT_SLOT_END )
10522 // remove item dependent auras and casts (only weapon and armor slots)
10523 RemoveItemDependentAurasAndCasts(pItem);
10525 // update expertise
10526 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10527 UpdateExpertise(BASE_ATTACK);
10528 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10529 UpdateExpertise(OFF_ATTACK);
10531 // equipment visual show
10532 SetVisibleItemSlot(slot, NULL);
10534 // need update known currency
10535 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10536 UpdateKnownCurrencies(pItem->GetEntry(), false);
10538 m_items[slot] = NULL;
10540 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10541 pBag->RemoveItem(slot, update);
10543 if( IsInWorld() && update )
10545 pItem->RemoveFromWorld();
10546 pItem->DestroyForPlayer(this);
10549 //pItem->SetOwnerGUID(0);
10550 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10551 pItem->SetSlot( NULL_SLOT );
10552 pItem->SetState(ITEM_REMOVED, this);
10556 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10558 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10559 uint32 remcount = 0;
10561 // in inventory
10562 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10564 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10566 if (pItem->GetEntry() == item)
10568 if (pItem->GetCount() + remcount <= count)
10570 // all items in inventory can unequipped
10571 remcount += pItem->GetCount();
10572 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10574 if (remcount >= count)
10575 return;
10577 else
10579 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10580 pItem->SetCount( pItem->GetCount() - count + remcount );
10581 if (IsInWorld() & update)
10582 pItem->SendUpdateToPlayer( this );
10583 pItem->SetState(ITEM_CHANGED, this);
10584 return;
10590 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10592 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10594 if (pItem->GetEntry() == item)
10596 if (pItem->GetCount() + remcount <= count)
10598 // all keys can be unequipped
10599 remcount += pItem->GetCount();
10600 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10602 if (remcount >= count)
10603 return;
10605 else
10607 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10608 pItem->SetCount( pItem->GetCount() - count + remcount );
10609 if (IsInWorld() & update)
10610 pItem->SendUpdateToPlayer( this );
10611 pItem->SetState(ITEM_CHANGED, this);
10612 return;
10618 // in inventory bags
10619 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10621 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10623 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10625 if(Item* pItem = pBag->GetItemByPos(j))
10627 if (pItem->GetEntry() == item)
10629 // all items in bags can be unequipped
10630 if (pItem->GetCount() + remcount <= count)
10632 remcount += pItem->GetCount();
10633 DestroyItem( i, j, update );
10635 if (remcount >= count)
10636 return;
10638 else
10640 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10641 pItem->SetCount( pItem->GetCount() - count + remcount );
10642 if (IsInWorld() && update)
10643 pItem->SendUpdateToPlayer( this );
10644 pItem->SetState(ITEM_CHANGED, this);
10645 return;
10653 // in equipment and bag list
10654 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10656 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10658 if (pItem && pItem->GetEntry() == item)
10660 if (pItem->GetCount() + remcount <= count)
10662 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10664 remcount += pItem->GetCount();
10665 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10667 if (remcount >= count)
10668 return;
10671 else
10673 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10674 pItem->SetCount( pItem->GetCount() - count + remcount );
10675 if (IsInWorld() & update)
10676 pItem->SendUpdateToPlayer( this );
10677 pItem->SetState(ITEM_CHANGED, this);
10678 return;
10685 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10687 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10689 // in inventory
10690 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10691 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10692 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10693 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10695 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10696 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10697 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10698 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10700 // in inventory bags
10701 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10702 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10703 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10704 if (Item* pItem = pBag->GetItemByPos(j))
10705 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10706 DestroyItem(i, j, update);
10708 // in equipment and bag list
10709 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10710 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10711 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10712 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10715 void Player::DestroyConjuredItems( bool update )
10717 // used when entering arena
10718 // destroys all conjured items
10719 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10721 // in inventory
10722 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10723 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10724 if (pItem->IsConjuredConsumable())
10725 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10727 // in inventory bags
10728 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10729 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10730 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10731 if (Item* pItem = pBag->GetItemByPos(j))
10732 if (pItem->IsConjuredConsumable())
10733 DestroyItem( i, j, update);
10735 // in equipment and bag list
10736 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10737 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10738 if (pItem->IsConjuredConsumable())
10739 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10742 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10744 if(!pItem)
10745 return;
10747 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10749 if( pItem->GetCount() <= count )
10751 count -= pItem->GetCount();
10753 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10755 else
10757 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10758 pItem->SetCount( pItem->GetCount() - count );
10759 count = 0;
10760 if( IsInWorld() & update )
10761 pItem->SendUpdateToPlayer( this );
10762 pItem->SetState(ITEM_CHANGED, this);
10766 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10768 uint8 srcbag = src >> 8;
10769 uint8 srcslot = src & 255;
10771 uint8 dstbag = dst >> 8;
10772 uint8 dstslot = dst & 255;
10774 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10775 if( !pSrcItem )
10777 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10778 return;
10781 // not let split all items (can be only at cheating)
10782 if(pSrcItem->GetCount() == count)
10784 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10785 return;
10788 // not let split more existed items (can be only at cheating)
10789 if(pSrcItem->GetCount() < count)
10791 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10792 return;
10795 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10797 //best error message found for attempting to split while looting
10798 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10799 return;
10802 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10803 Item *pNewItem = pSrcItem->CloneItem( count, this );
10804 if( !pNewItem )
10806 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10807 return;
10810 if( IsInventoryPos( dst ) )
10812 // change item amount before check (for unique max count check)
10813 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10815 ItemPosCountVec dest;
10816 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10817 if( msg != EQUIP_ERR_OK )
10819 delete pNewItem;
10820 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10821 SendEquipError( msg, pSrcItem, NULL );
10822 return;
10825 if( IsInWorld() )
10826 pSrcItem->SendUpdateToPlayer( this );
10827 pSrcItem->SetState(ITEM_CHANGED, this);
10828 StoreItem( dest, pNewItem, true);
10830 else if( IsBankPos ( dst ) )
10832 // change item amount before check (for unique max count check)
10833 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10835 ItemPosCountVec dest;
10836 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10837 if( msg != EQUIP_ERR_OK )
10839 delete pNewItem;
10840 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10841 SendEquipError( msg, pSrcItem, NULL );
10842 return;
10845 if( IsInWorld() )
10846 pSrcItem->SendUpdateToPlayer( this );
10847 pSrcItem->SetState(ITEM_CHANGED, this);
10848 BankItem( dest, pNewItem, true);
10850 else if( IsEquipmentPos ( dst ) )
10852 // change item amount before check (for unique max count check), provide space for splitted items
10853 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10855 uint16 dest;
10856 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10857 if( msg != EQUIP_ERR_OK )
10859 delete pNewItem;
10860 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10861 SendEquipError( msg, pSrcItem, NULL );
10862 return;
10865 if( IsInWorld() )
10866 pSrcItem->SendUpdateToPlayer( this );
10867 pSrcItem->SetState(ITEM_CHANGED, this);
10868 EquipItem( dest, pNewItem, true);
10869 AutoUnequipOffhandIfNeed();
10873 void Player::SwapItem( uint16 src, uint16 dst )
10875 uint8 srcbag = src >> 8;
10876 uint8 srcslot = src & 255;
10878 uint8 dstbag = dst >> 8;
10879 uint8 dstslot = dst & 255;
10881 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10882 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10884 if( !pSrcItem )
10885 return;
10887 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10889 if(!isAlive() )
10891 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10892 return;
10895 // SRC checks
10897 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10899 //best error message found for attempting to swap while looting
10900 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10901 return;
10904 // check unequip potability for equipped items and bank bags
10905 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10907 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10908 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10909 if(msg != EQUIP_ERR_OK)
10911 SendEquipError( msg, pSrcItem, pDstItem );
10912 return;
10916 // prevent put equipped/bank bag in self
10917 if( IsBagPos ( src ) && srcslot == dstbag)
10919 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10920 return;
10923 // DST checks
10925 if (pDstItem)
10927 if(pDstItem->m_lootGenerated) // prevent swap looting item
10929 //best error message found for attempting to swap while looting
10930 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10931 return;
10934 // check unequip potability for equipped items and bank bags
10935 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10937 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10938 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10939 if(msg != EQUIP_ERR_OK)
10941 SendEquipError( msg, pSrcItem, pDstItem );
10942 return;
10947 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10948 // or swap empty bag with another empty or not empty bag (with items exchange)
10950 // Move case
10951 if( !pDstItem )
10953 if( IsInventoryPos( dst ) )
10955 ItemPosCountVec dest;
10956 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10957 if( msg != EQUIP_ERR_OK )
10959 SendEquipError( msg, pSrcItem, NULL );
10960 return;
10963 RemoveItem(srcbag, srcslot, true);
10964 StoreItem( dest, pSrcItem, true);
10966 else if( IsBankPos ( dst ) )
10968 ItemPosCountVec dest;
10969 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10970 if( msg != EQUIP_ERR_OK )
10972 SendEquipError( msg, pSrcItem, NULL );
10973 return;
10976 RemoveItem(srcbag, srcslot, true);
10977 BankItem( dest, pSrcItem, true);
10979 else if( IsEquipmentPos ( dst ) )
10981 uint16 dest;
10982 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10983 if( msg != EQUIP_ERR_OK )
10985 SendEquipError( msg, pSrcItem, NULL );
10986 return;
10989 RemoveItem(srcbag, srcslot, true);
10990 EquipItem(dest, pSrcItem, true);
10991 AutoUnequipOffhandIfNeed();
10994 return;
10997 // attempt merge to / fill target item
10998 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11000 uint8 msg;
11001 ItemPosCountVec sDest;
11002 uint16 eDest;
11003 if( IsInventoryPos( dst ) )
11004 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11005 else if( IsBankPos ( dst ) )
11006 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11007 else if( IsEquipmentPos ( dst ) )
11008 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11009 else
11010 return;
11012 // can be merge/fill
11013 if(msg == EQUIP_ERR_OK)
11015 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11017 RemoveItem(srcbag, srcslot, true);
11019 if( IsInventoryPos( dst ) )
11020 StoreItem( sDest, pSrcItem, true);
11021 else if( IsBankPos ( dst ) )
11022 BankItem( sDest, pSrcItem, true);
11023 else if( IsEquipmentPos ( dst ) )
11025 EquipItem( eDest, pSrcItem, true);
11026 AutoUnequipOffhandIfNeed();
11029 else
11031 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11032 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11033 pSrcItem->SetState(ITEM_CHANGED, this);
11034 pDstItem->SetState(ITEM_CHANGED, this);
11035 if( IsInWorld() )
11037 pSrcItem->SendUpdateToPlayer( this );
11038 pDstItem->SendUpdateToPlayer( this );
11041 return;
11045 // impossible merge/fill, do real swap
11046 uint8 msg;
11048 // check src->dest move possibility
11049 ItemPosCountVec sDest;
11050 uint16 eDest = 0;
11051 if( IsInventoryPos( dst ) )
11052 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11053 else if( IsBankPos( dst ) )
11054 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11055 else if( IsEquipmentPos( dst ) )
11057 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11058 if( msg == EQUIP_ERR_OK )
11059 msg = CanUnequipItem( eDest, true );
11062 if( msg != EQUIP_ERR_OK )
11064 SendEquipError( msg, pSrcItem, pDstItem );
11065 return;
11068 // check dest->src move possibility
11069 ItemPosCountVec sDest2;
11070 uint16 eDest2 = 0;
11071 if( IsInventoryPos( src ) )
11072 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11073 else if( IsBankPos( src ) )
11074 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11075 else if( IsEquipmentPos( src ) )
11077 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11078 if( msg == EQUIP_ERR_OK )
11079 msg = CanUnequipItem( eDest2, true);
11082 if( msg != EQUIP_ERR_OK )
11084 SendEquipError( msg, pDstItem, pSrcItem );
11085 return;
11088 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11089 if(pSrcItem->IsBag() && pDstItem->IsBag())
11091 Bag* emptyBag = NULL;
11092 Bag* fullBag = NULL;
11093 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11095 emptyBag = (Bag*)pSrcItem;
11096 fullBag = (Bag*)pDstItem;
11098 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11100 emptyBag = (Bag*)pDstItem;
11101 fullBag = (Bag*)pSrcItem;
11104 // bag swap (with items exchange) case
11105 if(emptyBag && fullBag)
11107 ItemPrototype const* emotyProto = emptyBag->GetProto();
11109 uint32 count = 0;
11111 for(int i=0; i < fullBag->GetBagSize(); ++i)
11113 Item *bagItem = fullBag->GetItemByPos(i);
11114 if (!bagItem)
11115 continue;
11117 ItemPrototype const* bagItemProto = bagItem->GetProto();
11118 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11120 // one from items not go to empty target bag
11121 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11122 return;
11125 ++count;
11129 if (count > emptyBag->GetBagSize())
11131 // too small targeted bag
11132 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11133 return;
11136 // Items swap
11137 count = 0; // will pos in new bag
11138 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11140 Item *bagItem = fullBag->GetItemByPos(i);
11141 if (!bagItem)
11142 continue;
11144 fullBag->RemoveItem(i, true);
11145 emptyBag->StoreItem(count, bagItem, true);
11146 bagItem->SetState(ITEM_CHANGED, this);
11148 ++count;
11153 // now do moves, remove...
11154 RemoveItem(dstbag, dstslot, false);
11155 RemoveItem(srcbag, srcslot, false);
11157 // add to dest
11158 if( IsInventoryPos( dst ) )
11159 StoreItem(sDest, pSrcItem, true);
11160 else if( IsBankPos( dst ) )
11161 BankItem(sDest, pSrcItem, true);
11162 else if( IsEquipmentPos( dst ) )
11163 EquipItem(eDest, pSrcItem, true);
11165 // add to src
11166 if( IsInventoryPos( src ) )
11167 StoreItem(sDest2, pDstItem, true);
11168 else if( IsBankPos( src ) )
11169 BankItem(sDest2, pDstItem, true);
11170 else if( IsEquipmentPos( src ) )
11171 EquipItem(eDest2, pDstItem, true);
11173 AutoUnequipOffhandIfNeed();
11176 void Player::AddItemToBuyBackSlot( Item *pItem )
11178 if( pItem )
11180 uint32 slot = m_currentBuybackSlot;
11181 // if current back slot non-empty search oldest or free
11182 if(m_items[slot])
11184 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11185 uint32 oldest_slot = BUYBACK_SLOT_START;
11187 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11189 // found empty
11190 if(!m_items[i])
11192 slot = i;
11193 break;
11196 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11198 if(oldest_time > i_time)
11200 oldest_time = i_time;
11201 oldest_slot = i;
11205 // find oldest
11206 slot = oldest_slot;
11209 RemoveItemFromBuyBackSlot( slot, true );
11210 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11212 m_items[slot] = pItem;
11213 time_t base = time(NULL);
11214 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11215 uint32 eslot = slot - BUYBACK_SLOT_START;
11217 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11218 ItemPrototype const *pProto = pItem->GetProto();
11219 if( pProto )
11220 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11221 else
11222 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11223 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11225 // move to next (for non filled list is move most optimized choice)
11226 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11227 ++m_currentBuybackSlot;
11231 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11233 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11234 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11235 return m_items[slot];
11236 return NULL;
11239 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11241 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11242 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11244 Item *pItem = m_items[slot];
11245 if( pItem )
11247 pItem->RemoveFromWorld();
11248 if(del) pItem->SetState(ITEM_REMOVED, this);
11251 m_items[slot] = NULL;
11253 uint32 eslot = slot - BUYBACK_SLOT_START;
11254 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11255 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11256 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11258 // if current backslot is filled set to now free slot
11259 if(m_items[m_currentBuybackSlot])
11260 m_currentBuybackSlot = slot;
11264 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11266 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11267 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11268 data << uint8(msg);
11270 if(msg)
11272 data << uint64(pItem ? pItem->GetGUID() : 0);
11273 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11274 data << uint8(0); // not 0 there...
11276 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11278 uint32 level = 0;
11280 if(pItem)
11281 if(ItemPrototype const* proto = pItem->GetProto())
11282 level = proto->RequiredLevel;
11284 data << uint32(level); // new 2.4.0
11287 GetSession()->SendPacket(&data);
11290 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11292 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11293 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11294 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11295 data << uint32(item);
11296 if( param > 0 )
11297 data << uint32(param);
11298 data << uint8(msg);
11299 GetSession()->SendPacket(&data);
11302 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11304 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11305 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11306 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11307 data << uint64(guid);
11308 if( param > 0 )
11309 data << uint32(param);
11310 data << uint8(msg);
11311 GetSession()->SendPacket(&data);
11314 void Player::ClearTrade()
11316 tradeGold = 0;
11317 acceptTrade = false;
11318 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11319 tradeItems[i] = NULL_SLOT;
11322 void Player::TradeCancel(bool sendback)
11324 if(pTrader)
11326 // send yellow "Trade canceled" message to both traders
11327 WorldSession* ws;
11328 ws = GetSession();
11329 if(sendback)
11330 ws->SendCancelTrade();
11331 ws = pTrader->GetSession();
11332 if(!ws->PlayerLogout())
11333 ws->SendCancelTrade();
11335 // cleanup
11336 ClearTrade();
11337 pTrader->ClearTrade();
11338 // prevent loss of reference
11339 pTrader->pTrader = NULL;
11340 pTrader = NULL;
11344 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11346 if(m_itemDuration.empty())
11347 return;
11349 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11351 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11353 Item* item = *itr;
11354 ++itr; // current element can be erased in UpdateDuration
11356 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11357 item->UpdateDuration(this,time);
11361 void Player::UpdateEnchantTime(uint32 time)
11363 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11365 assert(itr->item);
11366 next = itr;
11367 if(!itr->item->GetEnchantmentId(itr->slot))
11369 next = m_enchantDuration.erase(itr);
11371 else if(itr->leftduration <= time)
11373 ApplyEnchantment(itr->item, itr->slot, false, false);
11374 itr->item->ClearEnchantment(itr->slot);
11375 next = m_enchantDuration.erase(itr);
11377 else if(itr->leftduration > time)
11379 itr->leftduration -= time;
11380 ++next;
11385 void Player::AddEnchantmentDurations(Item *item)
11387 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11389 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11390 continue;
11392 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11393 if( duration > 0 )
11394 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11398 void Player::RemoveEnchantmentDurations(Item *item)
11400 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11402 if(itr->item == item)
11404 // save duration in item
11405 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11406 itr = m_enchantDuration.erase(itr);
11408 else
11409 ++itr;
11413 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11415 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11416 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11418 next = itr;
11419 if(itr->slot == slot)
11421 if(itr->item && itr->item->GetEnchantmentId(slot))
11423 // remove from stats
11424 ApplyEnchantment(itr->item, slot, false, false);
11425 // remove visual
11426 itr->item->ClearEnchantment(slot);
11428 // remove from update list
11429 next = m_enchantDuration.erase(itr);
11431 else
11432 ++next;
11435 // remove enchants from inventory items
11436 // NOTE: no need to remove these from stats, since these aren't equipped
11437 // in inventory
11438 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11440 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11441 if( pItem && pItem->GetEnchantmentId(slot) )
11442 pItem->ClearEnchantment(slot);
11445 // in inventory bags
11446 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11448 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11449 if( pBag )
11451 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11453 Item* pItem = pBag->GetItemByPos(j);
11454 if( pItem && pItem->GetEnchantmentId(slot) )
11455 pItem->ClearEnchantment(slot);
11461 // duration == 0 will remove item enchant
11462 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11464 if(!item)
11465 return;
11467 if(slot >= MAX_ENCHANTMENT_SLOT)
11468 return;
11470 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11472 if(itr->item == item && itr->slot == slot)
11474 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11475 m_enchantDuration.erase(itr);
11476 break;
11479 if(item && duration > 0 )
11481 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11482 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11486 void Player::ApplyEnchantment(Item *item,bool apply)
11488 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11489 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11492 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11494 if(!item)
11495 return;
11497 if(!item->IsEquipped())
11498 return;
11500 if(slot >= MAX_ENCHANTMENT_SLOT)
11501 return;
11503 uint32 enchant_id = item->GetEnchantmentId(slot);
11504 if(!enchant_id)
11505 return;
11507 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11508 if(!pEnchant)
11509 return;
11511 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11512 return;
11514 if (!item->IsBroken())
11516 for (int s = 0; s < 3; ++s)
11518 uint32 enchant_display_type = pEnchant->type[s];
11519 uint32 enchant_amount = pEnchant->amount[s];
11520 uint32 enchant_spell_id = pEnchant->spellid[s];
11522 switch(enchant_display_type)
11524 case ITEM_ENCHANTMENT_TYPE_NONE:
11525 break;
11526 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11527 // processed in Player::CastItemCombatSpell
11528 break;
11529 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11530 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11531 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11532 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11533 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11534 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11535 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11536 break;
11537 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11538 if(enchant_spell_id)
11540 if(apply)
11542 int32 basepoints = 0;
11543 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11544 if (item->GetItemRandomPropertyId())
11546 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11547 if (item_rand)
11549 // Search enchant_amount
11550 for (int k = 0; k < 3; ++k)
11552 if(item_rand->enchant_id[k] == enchant_id)
11554 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11555 break;
11560 // Cast custom spell vs all equal basepoints getted from enchant_amount
11561 if (basepoints)
11562 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11563 else
11564 CastSpell(this, enchant_spell_id, true, item);
11566 else
11567 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11569 break;
11570 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11571 if (!enchant_amount)
11573 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11574 if(item_rand)
11576 for (int k = 0; k < 3; ++k)
11578 if(item_rand->enchant_id[k] == enchant_id)
11580 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11581 break;
11587 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11588 break;
11589 case ITEM_ENCHANTMENT_TYPE_STAT:
11591 if (!enchant_amount)
11593 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11594 if(item_rand_suffix)
11596 for (int k = 0; k < 3; ++k)
11598 if(item_rand_suffix->enchant_id[k] == enchant_id)
11600 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11601 break;
11607 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11608 switch (enchant_spell_id)
11610 case ITEM_MOD_MANA:
11611 sLog.outDebug("+ %u MANA",enchant_amount);
11612 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11613 break;
11614 case ITEM_MOD_HEALTH:
11615 sLog.outDebug("+ %u HEALTH",enchant_amount);
11616 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11617 break;
11618 case ITEM_MOD_AGILITY:
11619 sLog.outDebug("+ %u AGILITY",enchant_amount);
11620 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11621 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11622 break;
11623 case ITEM_MOD_STRENGTH:
11624 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11625 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11626 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11627 break;
11628 case ITEM_MOD_INTELLECT:
11629 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11630 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11631 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11632 break;
11633 case ITEM_MOD_SPIRIT:
11634 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11635 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11636 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11637 break;
11638 case ITEM_MOD_STAMINA:
11639 sLog.outDebug("+ %u STAMINA",enchant_amount);
11640 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11641 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11642 break;
11643 case ITEM_MOD_DEFENSE_SKILL_RATING:
11644 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11645 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11646 break;
11647 case ITEM_MOD_DODGE_RATING:
11648 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11649 sLog.outDebug("+ %u DODGE", enchant_amount);
11650 break;
11651 case ITEM_MOD_PARRY_RATING:
11652 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11653 sLog.outDebug("+ %u PARRY", enchant_amount);
11654 break;
11655 case ITEM_MOD_BLOCK_RATING:
11656 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11657 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11658 break;
11659 case ITEM_MOD_HIT_MELEE_RATING:
11660 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11661 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11662 break;
11663 case ITEM_MOD_HIT_RANGED_RATING:
11664 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11665 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11666 break;
11667 case ITEM_MOD_HIT_SPELL_RATING:
11668 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11669 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11670 break;
11671 case ITEM_MOD_CRIT_MELEE_RATING:
11672 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11673 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11674 break;
11675 case ITEM_MOD_CRIT_RANGED_RATING:
11676 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11677 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11678 break;
11679 case ITEM_MOD_CRIT_SPELL_RATING:
11680 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11681 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11682 break;
11683 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11684 // in Enchantments
11685 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11686 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11687 // break;
11688 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11689 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11690 // break;
11691 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11692 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11693 // break;
11694 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11695 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11696 // break;
11697 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11698 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11699 // break;
11700 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11701 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11702 // break;
11703 // case ITEM_MOD_HASTE_MELEE_RATING:
11704 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11705 // break;
11706 // case ITEM_MOD_HASTE_RANGED_RATING:
11707 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11708 // break;
11709 case ITEM_MOD_HASTE_SPELL_RATING:
11710 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11711 break;
11712 case ITEM_MOD_HIT_RATING:
11713 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11714 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11715 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11716 sLog.outDebug("+ %u HIT", enchant_amount);
11717 break;
11718 case ITEM_MOD_CRIT_RATING:
11719 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11720 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11721 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11722 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11723 break;
11724 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11725 // case ITEM_MOD_HIT_TAKEN_RATING:
11726 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11727 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11728 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11729 // break;
11730 // case ITEM_MOD_CRIT_TAKEN_RATING:
11731 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11732 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11733 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11734 // break;
11735 case ITEM_MOD_RESILIENCE_RATING:
11736 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11737 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11738 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11739 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11740 break;
11741 case ITEM_MOD_HASTE_RATING:
11742 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11743 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11744 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11745 sLog.outDebug("+ %u HASTE", enchant_amount);
11746 break;
11747 case ITEM_MOD_EXPERTISE_RATING:
11748 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11749 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11750 break;
11751 case ITEM_MOD_ATTACK_POWER:
11752 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11753 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11754 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11755 break;
11756 case ITEM_MOD_RANGED_ATTACK_POWER:
11757 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11758 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11759 break;
11760 case ITEM_MOD_FERAL_ATTACK_POWER:
11761 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11762 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11763 break;
11764 case ITEM_MOD_SPELL_HEALING_DONE:
11765 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11766 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11767 break;
11768 case ITEM_MOD_SPELL_DAMAGE_DONE:
11769 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11770 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11771 break;
11772 case ITEM_MOD_MANA_REGENERATION:
11773 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11774 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11775 break;
11776 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11777 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11778 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11779 break;
11780 case ITEM_MOD_SPELL_POWER:
11781 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11782 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11783 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11784 break;
11785 default:
11786 break;
11788 break;
11790 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11792 if(getClass() == CLASS_SHAMAN)
11794 float addValue = 0.0f;
11795 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11797 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11798 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11800 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11802 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11803 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11806 break;
11808 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11809 // processed in Player::CastItemUseSpell
11810 break;
11811 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11812 // nothing do..
11813 break;
11814 default:
11815 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11816 break;
11817 } /*switch(enchant_display_type)*/
11818 } /*for*/
11821 // visualize enchantment at player and equipped items
11822 if(slot == PERM_ENCHANTMENT_SLOT)
11823 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11825 if(slot == TEMP_ENCHANTMENT_SLOT)
11826 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11829 if(apply_dur)
11831 if(apply)
11833 // set duration
11834 uint32 duration = item->GetEnchantmentDuration(slot);
11835 if(duration > 0)
11836 AddEnchantmentDuration(item, slot, duration);
11838 else
11840 // duration == 0 will remove EnchantDuration
11841 AddEnchantmentDuration(item, slot, 0);
11846 void Player::SendEnchantmentDurations()
11848 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11850 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11854 void Player::SendItemDurations()
11856 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11858 (*itr)->SendTimeUpdate(this);
11862 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11864 if(!item) // prevent crash
11865 return;
11867 // last check 2.0.10
11868 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11869 data << uint64(GetGUID()); // player GUID
11870 data << uint32(received); // 0=looted, 1=from npc
11871 data << uint32(created); // 0=received, 1=created
11872 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11873 data << uint8(item->GetBagSlot()); // bagslot
11874 // item slot, but when added to stack: 0xFFFFFFFF
11875 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11876 data << uint32(item->GetEntry()); // item id
11877 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11878 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11879 data << uint32(count); // count of items
11880 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11882 if (broadcast && GetGroup())
11883 GetGroup()->BroadcastPacket(&data, true);
11884 else
11885 GetSession()->SendPacket(&data);
11888 /*********************************************************/
11889 /*** QUEST SYSTEM ***/
11890 /*********************************************************/
11892 void Player::PrepareQuestMenu( uint64 guid )
11894 Object *pObject;
11895 QuestRelations* pObjectQR;
11896 QuestRelations* pObjectQIR;
11898 // pets also can have quests
11899 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11900 if( pCreature )
11902 pObject = (Object*)pCreature;
11903 pObjectQR = &objmgr.mCreatureQuestRelations;
11904 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11906 else
11908 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11909 if( pGameObject )
11911 pObject = (Object*)pGameObject;
11912 pObjectQR = &objmgr.mGOQuestRelations;
11913 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11915 else
11916 return;
11919 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11920 qm.ClearMenu();
11922 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11924 uint32 quest_id = i->second;
11925 QuestStatus status = GetQuestStatus( quest_id );
11926 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11927 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11928 else if ( status == QUEST_STATUS_INCOMPLETE )
11929 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11930 else if (status == QUEST_STATUS_AVAILABLE )
11931 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11934 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11936 uint32 quest_id = i->second;
11937 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11938 if(!pQuest) continue;
11940 QuestStatus status = GetQuestStatus( quest_id );
11942 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11943 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11944 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11945 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11949 void Player::SendPreparedQuest( uint64 guid )
11951 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11952 if( questMenu.Empty() )
11953 return;
11955 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11957 uint32 status = qmi0.m_qIcon;
11959 // single element case
11960 if ( questMenu.MenuItemCount() == 1 )
11962 // Auto open -- maybe also should verify there is no greeting
11963 uint32 quest_id = qmi0.m_qId;
11964 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11966 if ( pQuest )
11968 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
11969 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11970 else if( status == DIALOG_STATUS_UNK2 )
11971 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11972 // Send completable on repeatable quest if player don't have quest
11973 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11974 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11975 else
11976 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11979 // multiply entries
11980 else
11982 QEmote qe;
11983 qe._Delay = 0;
11984 qe._Emote = 0;
11985 std::string title = "";
11987 // need pet case for some quests
11988 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11989 if( pCreature )
11991 uint32 textid = pCreature->GetNpcTextId();
11992 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11993 if( !gossiptext )
11995 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11996 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11997 title = "";
11999 else
12001 qe = gossiptext->Options[0].Emotes[0];
12003 if(!gossiptext->Options[0].Text_0.empty())
12005 title = gossiptext->Options[0].Text_0;
12007 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12008 if (loc_idx >= 0)
12010 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12011 if (nl)
12013 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12014 title = nl->Text_0[0][loc_idx];
12018 else
12020 title = gossiptext->Options[0].Text_1;
12022 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12023 if (loc_idx >= 0)
12025 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12026 if (nl)
12028 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12029 title = nl->Text_1[0][loc_idx];
12035 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12039 bool Player::IsActiveQuest( uint32 quest_id ) const
12041 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12043 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12046 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12048 Object *pObject;
12049 QuestRelations* pObjectQR;
12050 QuestRelations* pObjectQIR;
12052 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12053 if( pCreature )
12055 pObject = (Object*)pCreature;
12056 pObjectQR = &objmgr.mCreatureQuestRelations;
12057 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12059 else
12061 GameObject *pGameObject = GetMap()->GetGameObject(guid);
12062 if( pGameObject )
12064 pObject = (Object*)pGameObject;
12065 pObjectQR = &objmgr.mGOQuestRelations;
12066 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12068 else
12069 return NULL;
12072 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12073 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12075 if (itr->second == nextQuestID)
12076 return objmgr.GetQuestTemplate(nextQuestID);
12079 return NULL;
12082 bool Player::CanSeeStartQuest( Quest const *pQuest )
12084 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12085 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12086 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12087 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12089 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12092 return false;
12095 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12097 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12098 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12099 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12100 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12101 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12102 && SatisfyQuestDay( pQuest, msg );
12105 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12107 if( !SatisfyQuestLog( msg ) )
12108 return false;
12110 uint32 srcitem = pQuest->GetSrcItemId();
12111 if( srcitem > 0 )
12113 uint32 count = pQuest->GetSrcItemCount();
12114 ItemPosCountVec dest;
12115 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12117 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12118 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12119 return true;
12120 else if( msg2 != EQUIP_ERR_OK )
12122 SendEquipError( msg2, NULL, NULL );
12123 return false;
12126 return true;
12129 bool Player::CanCompleteQuest( uint32 quest_id )
12131 if( quest_id )
12133 QuestStatusData& q_status = mQuestStatus[quest_id];
12134 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12135 return false; // not allow re-complete quest
12137 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12139 if(!qInfo)
12140 return false;
12142 // auto complete quest
12143 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12144 return true;
12146 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12149 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12151 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12153 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12154 return false;
12158 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12160 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12162 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12163 continue;
12165 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12166 return false;
12170 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12171 return false;
12173 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12174 return false;
12176 if ( qInfo->GetRewOrReqMoney() < 0 )
12178 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12179 return false;
12182 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12183 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12184 return false;
12186 return true;
12189 return false;
12192 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12194 // Solve problem that player don't have the quest and try complete it.
12195 // if repeatable she must be able to complete event if player don't have it.
12196 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12197 if( !CanTakeQuest(pQuest, false) )
12198 return false;
12200 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12201 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12202 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12203 return false;
12205 if( !CanRewardQuest(pQuest, false) )
12206 return false;
12208 return true;
12211 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12213 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12214 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12215 return false;
12217 // daily quest can't be rewarded (25 daily quest already completed)
12218 if(!SatisfyQuestDay(pQuest,true))
12219 return false;
12221 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12222 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12223 return false;
12225 // prevent receive reward with quest items in bank
12226 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12228 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12230 if( pQuest->ReqItemCount[i]!= 0 &&
12231 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12233 if(msg)
12234 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12235 return false;
12240 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12241 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12242 return false;
12244 return true;
12247 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12249 // prevent receive reward with quest items in bank or for not completed quest
12250 if(!CanRewardQuest(pQuest,msg))
12251 return false;
12253 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12255 if( pQuest->RewChoiceItemId[reward] )
12257 ItemPosCountVec dest;
12258 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12259 if( res != EQUIP_ERR_OK )
12261 SendEquipError( res, NULL, NULL );
12262 return false;
12267 if ( pQuest->GetRewItemsCount() > 0 )
12269 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12271 if( pQuest->RewItemId[i] )
12273 ItemPosCountVec dest;
12274 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12275 if( res != EQUIP_ERR_OK )
12277 SendEquipError( res, NULL, NULL );
12278 return false;
12284 return true;
12287 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12289 uint16 log_slot = FindQuestSlot( 0 );
12290 assert(log_slot < MAX_QUEST_LOG_SIZE);
12292 uint32 quest_id = pQuest->GetQuestId();
12294 // if not exist then created with set uState==NEW and rewarded=false
12295 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12297 // check for repeatable quests status reset
12298 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12299 questStatusData.m_explored = false;
12301 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12303 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12304 questStatusData.m_itemcount[i] = 0;
12307 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12309 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12310 questStatusData.m_creatureOrGOcount[i] = 0;
12313 GiveQuestSourceItem( pQuest );
12314 AdjustQuestReqItemCount( pQuest, questStatusData );
12316 if( pQuest->GetRepObjectiveFaction() )
12317 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12318 GetReputationMgr().SetVisible(factionEntry);
12320 uint32 qtime = 0;
12321 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12323 uint32 limittime = pQuest->GetLimitTime();
12325 // shared timed quest
12326 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12327 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12329 AddTimedQuest( quest_id );
12330 questStatusData.m_timer = limittime * IN_MILISECONDS;
12331 qtime = static_cast<uint32>(time(NULL)) + limittime;
12333 else
12334 questStatusData.m_timer = 0;
12336 SetQuestSlot(log_slot, quest_id, qtime);
12338 if (questStatusData.uState != QUEST_NEW)
12339 questStatusData.uState = QUEST_CHANGED;
12341 //starting initial quest script
12342 if(questGiver && pQuest->GetQuestStartScript()!=0)
12343 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12345 // Some spells applied at quest activation
12346 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12347 if(saBounds.first != saBounds.second)
12349 uint32 zone, area;
12350 GetZoneAndAreaId(zone,area);
12352 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12353 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12354 if( !HasAura(itr->second->spellId,0) )
12355 CastSpell(this,itr->second->spellId,true);
12358 UpdateForQuestWorldObjects();
12361 void Player::CompleteQuest( uint32 quest_id )
12363 if( quest_id )
12365 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12367 uint16 log_slot = FindQuestSlot( quest_id );
12368 if( log_slot < MAX_QUEST_LOG_SIZE)
12369 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12371 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12373 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12374 RewardQuest(qInfo,0,this,false);
12375 else
12376 SendQuestComplete( quest_id );
12381 void Player::IncompleteQuest( uint32 quest_id )
12383 if( quest_id )
12385 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12387 uint16 log_slot = FindQuestSlot( quest_id );
12388 if( log_slot < MAX_QUEST_LOG_SIZE)
12389 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12393 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12395 uint32 quest_id = pQuest->GetQuestId();
12397 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12399 if ( pQuest->ReqItemId[i] )
12400 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12403 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12404 // SetTimedQuest( 0 );
12405 m_timedquests.erase(pQuest->GetQuestId());
12407 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12409 if( pQuest->RewChoiceItemId[reward] )
12411 ItemPosCountVec dest;
12412 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12414 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12415 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12420 if ( pQuest->GetRewItemsCount() > 0 )
12422 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12424 if( pQuest->RewItemId[i] )
12426 ItemPosCountVec dest;
12427 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12429 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12430 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12436 RewardReputation( pQuest );
12438 if( pQuest->GetRewSpellCast() > 0 )
12439 CastSpell( this, pQuest->GetRewSpellCast(), true);
12440 else if( pQuest->GetRewSpell() > 0)
12441 CastSpell( this, pQuest->GetRewSpell(), true);
12443 uint16 log_slot = FindQuestSlot( quest_id );
12444 if( log_slot < MAX_QUEST_LOG_SIZE)
12445 SetQuestSlot(log_slot,0);
12447 QuestStatusData& q_status = mQuestStatus[quest_id];
12449 // Not give XP in case already completed once repeatable quest
12450 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12452 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12453 GiveXP( XP , NULL );
12454 else
12456 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12457 ModifyMoney( money );
12458 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12461 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12462 if(pQuest->GetRewOrReqMoney())
12464 ModifyMoney( pQuest->GetRewOrReqMoney() );
12466 if(pQuest->GetRewOrReqMoney() > 0)
12467 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12470 // honor reward
12471 if(pQuest->GetRewHonorableKills())
12472 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12474 // title reward
12475 if(pQuest->GetCharTitleId())
12477 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12478 SetTitle(titleEntry);
12481 if(pQuest->GetBonusTalents())
12483 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12484 InitTalentForLevel();
12487 // Send reward mail
12488 if(pQuest->GetRewMailTemplateId())
12490 MailMessageType mailType;
12491 uint32 senderGuidOrEntry;
12492 switch(questGiver->GetTypeId())
12494 case TYPEID_UNIT:
12495 mailType = MAIL_CREATURE;
12496 senderGuidOrEntry = questGiver->GetEntry();
12497 break;
12498 case TYPEID_GAMEOBJECT:
12499 mailType = MAIL_GAMEOBJECT;
12500 senderGuidOrEntry = questGiver->GetEntry();
12501 break;
12502 case TYPEID_ITEM:
12503 mailType = MAIL_ITEM;
12504 senderGuidOrEntry = questGiver->GetEntry();
12505 break;
12506 case TYPEID_PLAYER:
12507 mailType = MAIL_NORMAL;
12508 senderGuidOrEntry = questGiver->GetGUIDLow();
12509 break;
12510 default:
12511 mailType = MAIL_NORMAL;
12512 senderGuidOrEntry = GetGUIDLow();
12513 break;
12516 Loot questMailLoot;
12518 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12520 // fill mail
12521 MailItemsInfo mi; // item list preparing
12523 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12524 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12526 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12528 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12530 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12531 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12536 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12539 if(pQuest->IsDaily())
12541 SetDailyQuestStatus(quest_id);
12542 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12545 if ( !pQuest->IsRepeatable() )
12546 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12547 else
12548 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12550 q_status.m_rewarded = true;
12552 if(announce)
12553 SendQuestReward( pQuest, XP, questGiver );
12555 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12556 if (pQuest->GetZoneOrSort() > 0)
12557 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12558 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12559 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12561 uint32 zone = 0;
12562 uint32 area = 0;
12564 // remove auras from spells with quest reward state limitations
12565 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12566 if(saEndBounds.first != saEndBounds.second)
12568 GetZoneAndAreaId(zone,area);
12570 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12571 if(!itr->second->IsFitToRequirements(this,zone,area))
12572 RemoveAurasDueToSpell(itr->second->spellId);
12575 // Some spells applied at quest reward
12576 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12577 if(saBounds.first != saBounds.second)
12579 if(!zone || !area)
12580 GetZoneAndAreaId(zone,area);
12582 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12583 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12584 if( !HasAura(itr->second->spellId,0) )
12585 CastSpell(this,itr->second->spellId,true);
12589 void Player::FailQuest( uint32 quest_id )
12591 if( quest_id )
12593 IncompleteQuest( quest_id );
12595 uint16 log_slot = FindQuestSlot( quest_id );
12596 if( log_slot < MAX_QUEST_LOG_SIZE)
12598 SetQuestSlotTimer(log_slot, 1 );
12599 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12601 SendQuestFailed( quest_id );
12605 void Player::FailTimedQuest( uint32 quest_id )
12607 if( quest_id )
12609 QuestStatusData& q_status = mQuestStatus[quest_id];
12611 q_status.m_timer = 0;
12612 if (q_status.uState != QUEST_NEW)
12613 q_status.uState = QUEST_CHANGED;
12615 IncompleteQuest( quest_id );
12617 uint16 log_slot = FindQuestSlot( quest_id );
12618 if( log_slot < MAX_QUEST_LOG_SIZE)
12620 SetQuestSlotTimer(log_slot, 1 );
12621 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12623 SendQuestTimerFailed( quest_id );
12627 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12629 int32 zoneOrSort = qInfo->GetZoneOrSort();
12630 int32 skillOrClass = qInfo->GetSkillOrClass();
12632 // skip zone zoneOrSort and 0 case skillOrClass
12633 if( zoneOrSort >= 0 && skillOrClass == 0 )
12634 return true;
12636 int32 questSort = -zoneOrSort;
12637 uint8 reqSortClass = ClassByQuestSort(questSort);
12639 // check class sort cases in zoneOrSort
12640 if( reqSortClass != 0 && getClass() != reqSortClass)
12642 if( msg )
12643 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12644 return false;
12647 // check class
12648 if( skillOrClass < 0 )
12650 uint8 reqClass = -int32(skillOrClass);
12651 if(getClass() != reqClass)
12653 if( msg )
12654 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12655 return false;
12658 // check skill
12659 else if( skillOrClass > 0 )
12661 uint32 reqSkill = skillOrClass;
12662 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12664 if( msg )
12665 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12666 return false;
12670 return true;
12673 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12675 if( getLevel() < qInfo->GetMinLevel() )
12677 if( msg )
12678 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12679 return false;
12681 return true;
12684 bool Player::SatisfyQuestLog( bool msg )
12686 // exist free slot
12687 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12688 return true;
12690 if( msg )
12692 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12693 GetSession()->SendPacket( &data );
12694 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12696 return false;
12699 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12701 // No previous quest (might be first quest in a series)
12702 if( qInfo->prevQuests.empty())
12703 return true;
12705 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12707 uint32 prevId = abs(*iter);
12709 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12710 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12712 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12714 // If any of the positive previous quests completed, return true
12715 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12717 // skip one-from-all exclusive group
12718 if(qPrevInfo->GetExclusiveGroup() >= 0)
12719 return true;
12721 // each-from-all exclusive group ( < 0)
12722 // can be start if only all quests in prev quest exclusive group completed and rewarded
12723 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12724 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12726 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12728 for(; iter2 != end; ++iter2)
12730 uint32 exclude_Id = iter2->second;
12732 // skip checked quest id, only state of other quests in group is interesting
12733 if(exclude_Id == prevId)
12734 continue;
12736 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12738 // alternative quest from group also must be completed and rewarded(reported)
12739 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12741 if( msg )
12742 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12743 return false;
12746 return true;
12748 // If any of the negative previous quests active, return true
12749 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12750 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12752 // skip one-from-all exclusive group
12753 if(qPrevInfo->GetExclusiveGroup() >= 0)
12754 return true;
12756 // each-from-all exclusive group ( < 0)
12757 // can be start if only all quests in prev quest exclusive group active
12758 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12759 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12761 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12763 for(; iter2 != end; ++iter2)
12765 uint32 exclude_Id = iter2->second;
12767 // skip checked quest id, only state of other quests in group is interesting
12768 if(exclude_Id == prevId)
12769 continue;
12771 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12773 // alternative quest from group also must be active
12774 if( i_exstatus == mQuestStatus.end() ||
12775 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12776 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12778 if( msg )
12779 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12780 return false;
12783 return true;
12788 // Has only positive prev. quests in non-rewarded state
12789 // and negative prev. quests in non-active state
12790 if( msg )
12791 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12793 return false;
12796 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12798 uint32 reqraces = qInfo->GetRequiredRaces();
12799 if ( reqraces == 0 )
12800 return true;
12801 if( (reqraces & getRaceMask()) == 0 )
12803 if( msg )
12804 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12805 return false;
12807 return true;
12810 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12812 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12813 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12815 if( msg )
12816 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12817 return false;
12820 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12821 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12825 return false;
12828 return true;
12831 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12833 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12834 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12836 if( msg )
12837 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12838 return false;
12840 return true;
12843 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12845 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12847 if( msg )
12848 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12849 return false;
12851 return true;
12854 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12856 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12857 if(qInfo->GetExclusiveGroup() <= 0)
12858 return true;
12860 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12861 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12863 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12865 for(; iter != end; ++iter)
12867 uint32 exclude_Id = iter->second;
12869 // skip checked quest id, only state of other quests in group is interesting
12870 if(exclude_Id == qInfo->GetQuestId())
12871 continue;
12873 // not allow have daily quest if daily quest from exclusive group already recently completed
12874 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12875 if( !SatisfyQuestDay(Nquest, false) )
12877 if( msg )
12878 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12879 return false;
12882 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12884 // alternative quest already started or completed
12885 if( i_exstatus != mQuestStatus.end()
12886 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12888 if( msg )
12889 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12890 return false;
12893 return true;
12896 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12898 if(!qInfo->GetNextQuestInChain())
12899 return true;
12901 // next quest in chain already started or completed
12902 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12903 if( itr != mQuestStatus.end()
12904 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12906 if( msg )
12907 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12908 return false;
12911 // check for all quests further up the chain
12912 // only necessary if there are quest chains with more than one quest that can be skipped
12913 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12914 return true;
12917 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12919 // No previous quest in chain
12920 if( qInfo->prevChainQuests.empty())
12921 return true;
12923 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12925 uint32 prevId = *iter;
12927 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12929 if( i_prevstatus != mQuestStatus.end() )
12931 // If any of the previous quests in chain active, return false
12932 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12933 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12935 if( msg )
12936 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12937 return false;
12941 // check for all quests further down the chain
12942 // only necessary if there are quest chains with more than one quest that can be skipped
12943 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12944 // return false;
12947 // No previous quest in chain active
12948 return true;
12951 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12953 if(!qInfo->IsDaily())
12954 return true;
12956 bool have_slot = false;
12957 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12959 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12960 if(qInfo->GetQuestId()==id)
12961 return false;
12963 if(!id)
12964 have_slot = true;
12967 if(!have_slot)
12969 if( msg )
12970 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12971 return false;
12974 return true;
12977 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12979 uint32 srcitem = pQuest->GetSrcItemId();
12980 if( srcitem > 0 )
12982 uint32 count = pQuest->GetSrcItemCount();
12983 if( count <= 0 )
12984 count = 1;
12986 ItemPosCountVec dest;
12987 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12988 if( msg == EQUIP_ERR_OK )
12990 Item * item = StoreNewItem(dest, srcitem, true);
12991 SendNewItem(item, count, true, false);
12992 return true;
12994 // player already have max amount required item, just report success
12995 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12996 return true;
12997 else
12998 SendEquipError( msg, NULL, NULL );
12999 return false;
13002 return true;
13005 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13007 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13008 if( qInfo )
13010 uint32 srcitem = qInfo->GetSrcItemId();
13011 if( srcitem > 0 )
13013 uint32 count = qInfo->GetSrcItemCount();
13014 if( count <= 0 )
13015 count = 1;
13017 // exist one case when destroy source quest item not possible:
13018 // non un-equippable item (equipped non-empty bag, for example)
13019 uint8 res = CanUnequipItems(srcitem,count);
13020 if(res != EQUIP_ERR_OK)
13022 if(msg)
13023 SendEquipError( res, NULL, NULL );
13024 return false;
13027 DestroyItemCount(srcitem, count, true, true);
13030 return true;
13033 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13035 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13036 if( qInfo )
13038 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13039 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13040 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13041 && !qInfo->IsRepeatable() )
13042 return itr->second.m_rewarded;
13044 return false;
13046 return false;
13049 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13051 if( quest_id )
13053 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13054 if( itr != mQuestStatus.end() )
13055 return itr->second.m_status;
13057 return QUEST_STATUS_NONE;
13060 bool Player::CanShareQuest(uint32 quest_id) const
13062 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13063 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13065 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13066 if( itr != mQuestStatus.end() )
13067 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13069 return false;
13072 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13074 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13075 if( qInfo )
13077 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13079 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13080 m_timedquests.erase(qInfo->GetQuestId());
13083 QuestStatusData& q_status = mQuestStatus[quest_id];
13085 q_status.m_status = status;
13086 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13089 UpdateForQuestWorldObjects();
13092 // not used in MaNGOS, but used in scripting code
13093 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13095 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13096 if( !qInfo )
13097 return 0;
13099 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13100 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13101 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13103 return 0;
13106 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13108 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13110 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13112 uint32 reqitemcount = pQuest->ReqItemCount[i];
13113 if( reqitemcount != 0 )
13115 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13117 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13118 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13124 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13126 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13127 if ( GetQuestSlotQuestId(i) == quest_id )
13128 return i;
13130 return MAX_QUEST_LOG_SIZE;
13133 void Player::AreaExploredOrEventHappens( uint32 questId )
13135 if( questId )
13137 uint16 log_slot = FindQuestSlot( questId );
13138 if( log_slot < MAX_QUEST_LOG_SIZE)
13140 QuestStatusData& q_status = mQuestStatus[questId];
13142 if(!q_status.m_explored)
13144 q_status.m_explored = true;
13145 if (q_status.uState != QUEST_NEW)
13146 q_status.uState = QUEST_CHANGED;
13149 if( CanCompleteQuest( questId ) )
13150 CompleteQuest( questId );
13154 //not used in mangosd, function for external script library
13155 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13157 if( Group *pGroup = GetGroup() )
13159 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13161 Player *pGroupGuy = itr->getSource();
13163 // for any leave or dead (with not released body) group member at appropriate distance
13164 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13165 pGroupGuy->AreaExploredOrEventHappens(questId);
13168 else
13169 AreaExploredOrEventHappens(questId);
13172 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13174 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13176 uint32 questid = GetQuestSlotQuestId(i);
13177 if ( questid == 0 )
13178 continue;
13180 QuestStatusData& q_status = mQuestStatus[questid];
13182 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13183 continue;
13185 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13186 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13187 continue;
13189 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13191 uint32 reqitem = qInfo->ReqItemId[j];
13192 if ( reqitem == entry )
13194 uint32 reqitemcount = qInfo->ReqItemCount[j];
13195 uint32 curitemcount = q_status.m_itemcount[j];
13196 if ( curitemcount < reqitemcount )
13198 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13199 q_status.m_itemcount[j] += additemcount;
13200 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13202 SendQuestUpdateAddItem( qInfo, j, additemcount );
13204 if ( CanCompleteQuest( questid ) )
13205 CompleteQuest( questid );
13206 return;
13210 UpdateForQuestWorldObjects();
13213 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13215 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13217 uint32 questid = GetQuestSlotQuestId(i);
13218 if(!questid)
13219 continue;
13220 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13221 if ( !qInfo )
13222 continue;
13223 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13224 continue;
13226 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13228 uint32 reqitem = qInfo->ReqItemId[j];
13229 if ( reqitem == entry )
13231 QuestStatusData& q_status = mQuestStatus[questid];
13233 uint32 reqitemcount = qInfo->ReqItemCount[j];
13234 uint32 curitemcount;
13235 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13236 curitemcount = q_status.m_itemcount[j];
13237 else
13238 curitemcount = GetItemCount(entry,true);
13239 if ( curitemcount < reqitemcount + count )
13241 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13242 q_status.m_itemcount[j] = curitemcount - remitemcount;
13243 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13245 IncompleteQuest( questid );
13247 return;
13251 UpdateForQuestWorldObjects();
13254 void Player::KilledMonster( uint32 entry, uint64 guid )
13256 uint32 addkillcount = 1;
13257 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13258 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13260 uint32 questid = GetQuestSlotQuestId(i);
13261 if(!questid)
13262 continue;
13264 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13265 if( !qInfo )
13266 continue;
13267 // just if !ingroup || !noraidgroup || raidgroup
13268 QuestStatusData& q_status = mQuestStatus[questid];
13269 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13271 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13273 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13275 // skip GO activate objective or none
13276 if(qInfo->ReqCreatureOrGOId[j] <=0)
13277 continue;
13279 // skip Cast at creature objective
13280 if(qInfo->ReqSpell[j] !=0 )
13281 continue;
13283 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13285 if ( reqkill == entry )
13287 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13288 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13289 if ( curkillcount < reqkillcount )
13291 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13292 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13294 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13296 if ( CanCompleteQuest( questid ) )
13297 CompleteQuest( questid );
13299 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13300 continue;
13308 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13310 bool isCreature = IS_CREATURE_GUID(guid);
13312 uint32 addCastCount = 1;
13313 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13315 uint32 questid = GetQuestSlotQuestId(i);
13316 if(!questid)
13317 continue;
13319 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13320 if ( !qInfo )
13321 continue;
13323 QuestStatusData& q_status = mQuestStatus[questid];
13325 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13327 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13329 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13331 // skip kill creature objective (0) or wrong spell casts
13332 if(qInfo->ReqSpell[j] != spell_id )
13333 continue;
13335 uint32 reqTarget = 0;
13337 if(isCreature)
13339 // creature activate objectives
13340 if(qInfo->ReqCreatureOrGOId[j] > 0)
13341 // checked at quest_template loading
13342 reqTarget = qInfo->ReqCreatureOrGOId[j];
13344 else
13346 // GO activate objective
13347 if(qInfo->ReqCreatureOrGOId[j] < 0)
13348 // checked at quest_template loading
13349 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13352 // other not this creature/GO related objectives
13353 if( reqTarget != entry )
13354 continue;
13356 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13357 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13358 if ( curCastCount < reqCastCount )
13360 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13361 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13363 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13366 if ( CanCompleteQuest( questid ) )
13367 CompleteQuest( questid );
13369 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13370 break;
13377 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13379 uint32 addTalkCount = 1;
13380 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13382 uint32 questid = GetQuestSlotQuestId(i);
13383 if(!questid)
13384 continue;
13386 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13387 if ( !qInfo )
13388 continue;
13390 QuestStatusData& q_status = mQuestStatus[questid];
13392 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13394 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13396 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13398 // skip spell casts and Gameobject objectives
13399 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13400 continue;
13402 uint32 reqTarget = 0;
13404 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13405 // checked at quest_template loading
13406 reqTarget = qInfo->ReqCreatureOrGOId[j];
13407 else
13408 continue;
13410 if ( reqTarget == entry )
13412 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13413 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13414 if ( curTalkCount < reqTalkCount )
13416 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13417 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13419 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13421 if ( CanCompleteQuest( questid ) )
13422 CompleteQuest( questid );
13424 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13425 continue;
13433 void Player::MoneyChanged( uint32 count )
13435 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13437 uint32 questid = GetQuestSlotQuestId(i);
13438 if (!questid)
13439 continue;
13441 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13442 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13444 QuestStatusData& q_status = mQuestStatus[questid];
13446 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13448 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13450 if ( CanCompleteQuest( questid ) )
13451 CompleteQuest( questid );
13454 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13456 if(int32(count) < -qInfo->GetRewOrReqMoney())
13457 IncompleteQuest( questid );
13463 void Player::ReputationChanged(FactionEntry const* factionEntry )
13465 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13467 if(uint32 questid = GetQuestSlotQuestId(i))
13469 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13471 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13473 QuestStatusData& q_status = mQuestStatus[questid];
13474 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13476 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13477 if ( CanCompleteQuest( questid ) )
13478 CompleteQuest( questid );
13480 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13482 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13483 IncompleteQuest( questid );
13491 bool Player::HasQuestForItem( uint32 itemid ) const
13493 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13495 uint32 questid = GetQuestSlotQuestId(i);
13496 if ( questid == 0 )
13497 continue;
13499 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13500 if(qs_itr == mQuestStatus.end())
13501 continue;
13503 QuestStatusData const& q_status = qs_itr->second;
13505 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13507 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13508 if(!qinfo)
13509 continue;
13511 // hide quest if player is in raid-group and quest is no raid quest
13512 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13513 continue;
13515 // There should be no mixed ReqItem/ReqSource drop
13516 // This part for ReqItem drop
13517 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13519 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13520 return true;
13522 // This part - for ReqSource
13523 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13525 // examined item is a source item
13526 if (qinfo->ReqSourceId[j] == itemid)
13528 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13530 // 'unique' item
13531 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13532 return true;
13534 // allows custom amount drop when not 0
13535 if (qinfo->ReqSourceCount[j])
13537 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13538 return true;
13539 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13540 return true;
13545 return false;
13548 void Player::SendQuestComplete( uint32 quest_id )
13550 if( quest_id )
13552 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13553 data << uint32(quest_id);
13554 GetSession()->SendPacket( &data );
13555 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13559 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13561 uint32 questid = pQuest->GetQuestId();
13562 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13563 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13564 data << uint32(questid);
13566 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13568 data << uint32(XP);
13569 data << uint32(pQuest->GetRewOrReqMoney());
13571 else
13573 data << uint32(0);
13574 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13577 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13578 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13579 GetSession()->SendPacket( &data );
13581 if (pQuest->GetQuestCompleteScript() != 0)
13582 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13585 void Player::SendQuestFailed( uint32 quest_id )
13587 if( quest_id )
13589 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13590 data << quest_id;
13591 data << uint32(0); // failed reason (4 for inventory is full)
13592 GetSession()->SendPacket( &data );
13593 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13597 void Player::SendQuestTimerFailed( uint32 quest_id )
13599 if( quest_id )
13601 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13602 data << quest_id;
13603 GetSession()->SendPacket( &data );
13604 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13608 void Player::SendCanTakeQuestResponse( uint32 msg )
13610 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13611 data << uint32(msg);
13612 GetSession()->SendPacket( &data );
13613 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13616 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13618 if( pPlayer )
13620 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13621 data << uint64(pPlayer->GetGUID());
13622 data << uint8(msg); // valid values: 0-8
13623 GetSession()->SendPacket( &data );
13624 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13628 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13630 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13631 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13632 //data << pQuest->ReqItemId[item_idx];
13633 //data << count;
13634 GetSession()->SendPacket( &data );
13637 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13639 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13641 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13642 if (entry < 0)
13643 // client expected gameobject template id in form (id|0x80000000)
13644 entry = (-entry) | 0x80000000;
13646 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13647 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13648 data << uint32(pQuest->GetQuestId());
13649 data << uint32(entry);
13650 data << uint32(old_count + add_count);
13651 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13652 data << uint64(guid);
13653 GetSession()->SendPacket(&data);
13655 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13656 if( log_slot < MAX_QUEST_LOG_SIZE)
13657 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13660 /*********************************************************/
13661 /*** LOAD SYSTEM ***/
13662 /*********************************************************/
13664 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13666 bool delete_result = true;
13667 if (!result)
13669 // 0 1 2 3 4 5 6 7 8 9 10
13670 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone FROM characters WHERE guid = '%u'",guid);
13671 if (!result)
13672 return false;
13674 else
13675 delete_result = false;
13677 Field *fields = result->Fetch();
13679 if (!LoadValues( fields[1].GetString()))
13681 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13682 if (delete_result)
13683 delete result;
13684 return false;
13687 // overwrite possible wrong/corrupted guid
13688 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13690 m_name = fields[2].GetCppString();
13692 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13693 SetMapId(fields[6].GetUInt32());
13694 // the instance id is not needed at character enum
13696 m_Played_time[0] = fields[7].GetUInt32();
13697 m_Played_time[1] = fields[8].GetUInt32();
13699 m_atLoginFlags = fields[9].GetUInt32();
13701 // I don't see these used anywhere ..
13702 /*_LoadGroup();
13704 _LoadBoundInstances();*/
13706 if (delete_result)
13707 delete result;
13709 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13710 m_items[i] = NULL;
13712 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
13713 m_deathState = DEAD;
13715 return true;
13718 void Player::_LoadDeclinedNames(QueryResult* result)
13720 if(!result)
13721 return;
13723 if(m_declinedname)
13724 delete m_declinedname;
13726 m_declinedname = new DeclinedName;
13727 Field *fields = result->Fetch();
13728 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13729 m_declinedname->name[i] = fields[i].GetCppString();
13731 delete result;
13734 void Player::_LoadArenaTeamInfo(QueryResult *result)
13736 // arenateamid, played_week, played_season, personal_rating
13737 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13738 if (!result)
13739 return;
13743 Field *fields = result->Fetch();
13745 uint32 arenateamid = fields[0].GetUInt32();
13746 uint32 played_week = fields[1].GetUInt32();
13747 uint32 played_season = fields[2].GetUInt32();
13748 uint32 personal_rating = fields[3].GetUInt32();
13750 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13751 if(!aTeam)
13753 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13754 continue;
13756 uint8 arenaSlot = aTeam->GetSlot();
13758 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13759 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13760 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13761 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13762 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13763 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13765 }while (result->NextRow());
13766 delete result;
13769 void Player::_LoadEquipmentSets(QueryResult *result)
13771 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13772 if (!result)
13773 return;
13775 uint32 count = 0;
13778 Field *fields = result->Fetch();
13780 EquipmentSet eqSet;
13782 eqSet.Guid = fields[0].GetUInt64();
13783 uint32 index = fields[1].GetUInt32();
13784 eqSet.Name = fields[2].GetCppString();
13785 eqSet.IconName = fields[3].GetCppString();
13786 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13788 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13789 eqSet.Items[i] = fields[4+i].GetUInt32();
13791 m_EquipmentSets[index] = eqSet;
13793 ++count;
13795 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13796 break;
13797 } while (result->NextRow());
13798 delete result;
13801 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13803 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13804 if(!result)
13805 return false;
13807 Field *fields = result->Fetch();
13809 x = fields[0].GetFloat();
13810 y = fields[1].GetFloat();
13811 z = fields[2].GetFloat();
13812 o = fields[3].GetFloat();
13813 mapid = fields[4].GetUInt32();
13814 in_flight = !fields[5].GetCppString().empty();
13816 delete result;
13817 return true;
13820 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13822 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13823 if( !result )
13824 return false;
13826 Field *fields = result->Fetch();
13828 data = StrSplit(fields[0].GetCppString(), " ");
13830 delete result;
13832 return true;
13835 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13837 if(index >= data.size())
13838 return 0;
13840 return (uint32)atoi(data[index].c_str());
13843 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13845 float result;
13846 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13847 memcpy(&result, &temp, sizeof(result));
13849 return result;
13852 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13854 Tokens data;
13855 if(!LoadValuesArrayFromDB(data,guid))
13856 return 0;
13858 return GetUInt32ValueFromArray(data,index);
13861 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13863 float result;
13864 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13865 memcpy(&result, &temp, sizeof(result));
13867 return result;
13870 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13872 //// 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
13873 //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);
13874 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13876 if(!result)
13878 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13879 return false;
13882 Field *fields = result->Fetch();
13884 uint32 dbAccountId = fields[1].GetUInt32();
13886 // check if the character's account in the db and the logged in account match.
13887 // player should be able to load/delete character only with correct account!
13888 if( dbAccountId != GetSession()->GetAccountId() )
13890 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13891 delete result;
13892 return false;
13895 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13897 m_name = fields[3].GetCppString();
13899 // check name limitations
13900 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13902 delete result;
13903 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13904 return false;
13907 if(!LoadValues( fields[2].GetString()))
13909 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13910 delete result;
13911 return false;
13914 // overwrite possible wrong/corrupted guid
13915 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13917 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13918 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13920 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13921 SetVisibleItemSlot(slot, NULL);
13923 if (m_items[slot])
13925 delete m_items[slot];
13926 m_items[slot] = NULL;
13930 // update money limits
13931 if(GetMoney() > MAX_MONEY_AMOUNT)
13932 SetMoney(MAX_MONEY_AMOUNT);
13934 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13935 outDebugValues();
13937 m_race = fields[4].GetUInt8();
13938 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13939 //Other way is to saves m_team into characters table.
13940 setFactionForRace(m_race);
13941 SetCharm(NULL);
13943 m_class = fields[5].GetUInt8();
13945 // load home bind and check in same time class/race pair, it used later for restore broken positions
13946 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13948 delete result;
13949 return false;
13952 InitPrimaryProfessions(); // to max set before any spell loaded
13954 // init saved position, and fix it later if problematic
13955 uint32 transGUID = fields[24].GetUInt32();
13956 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13957 SetMapId(fields[9].GetUInt32());
13958 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13960 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13962 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13964 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13965 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13966 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13968 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13970 // check arena teams integrity
13971 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13973 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13974 if(!arena_team_id)
13975 continue;
13977 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13978 if(at->HaveMember(GetGUID()))
13979 continue;
13981 // arena team not exist or not member, cleanup fields
13982 for(int j =0; j < 6; ++j)
13983 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13986 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13988 if(!IsPositionValid())
13990 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());
13991 RelocateToHomebind();
13993 transGUID = 0;
13995 m_movementInfo.t_x = 0.0f;
13996 m_movementInfo.t_y = 0.0f;
13997 m_movementInfo.t_z = 0.0f;
13998 m_movementInfo.t_o = 0.0f;
14001 uint32 bgid = fields[34].GetUInt32();
14002 uint32 bgteam = fields[35].GetUInt32();
14004 if(bgid) //saved in BattleGround
14006 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14008 // check entry point and fix to homebind if need
14009 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14010 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14011 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14013 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14015 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14017 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14018 AddBattleGroundQueueId(bgQueueTypeId);
14020 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14021 SetBGTeam(bgteam);
14023 //join player to battleground group
14024 currentBg->EventPlayerLoggedIn(this, GetGUID());
14025 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14027 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14029 else
14031 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14032 SetMapId(_loc.mapid);
14033 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14034 //RemoveArenaAuras(true);
14037 else
14039 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14040 // if server restart after player save in BG or area
14041 // player can have current coordinates in to BG/Arean map, fix this
14042 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14044 // return to BG master
14045 SetMapId(fields[36].GetUInt32());
14046 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14048 // check entry point and fix to homebind if need
14049 mapEntry = sMapStore.LookupEntry(GetMapId());
14050 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14051 RelocateToHomebind();
14055 if (transGUID != 0)
14057 m_movementInfo.t_x = fields[20].GetFloat();
14058 m_movementInfo.t_y = fields[21].GetFloat();
14059 m_movementInfo.t_z = fields[22].GetFloat();
14060 m_movementInfo.t_o = fields[23].GetFloat();
14062 if( !MaNGOS::IsValidMapCoord(
14063 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14064 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14065 // transport size limited
14066 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14068 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14069 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14070 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14072 RelocateToHomebind();
14074 m_movementInfo.t_x = 0.0f;
14075 m_movementInfo.t_y = 0.0f;
14076 m_movementInfo.t_z = 0.0f;
14077 m_movementInfo.t_o = 0.0f;
14079 transGUID = 0;
14083 if (transGUID != 0)
14085 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14087 if( (*iter)->GetGUIDLow() == transGUID)
14089 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14090 // client without expansion support
14091 if(GetSession()->Expansion() < transMapEntry->Expansion())
14093 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14094 break;
14097 m_transport = *iter;
14098 m_transport->AddPassenger(this);
14099 SetMapId(m_transport->GetMapId());
14100 break;
14104 if(!m_transport)
14106 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14107 guid,transGUID);
14109 RelocateToHomebind();
14111 m_movementInfo.t_x = 0.0f;
14112 m_movementInfo.t_y = 0.0f;
14113 m_movementInfo.t_z = 0.0f;
14114 m_movementInfo.t_o = 0.0f;
14116 transGUID = 0;
14119 else // not transport case
14121 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14122 // client without expansion support
14123 if(GetSession()->Expansion() < mapEntry->Expansion())
14125 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14126 RelocateToHomebind();
14130 // NOW player must have valid map
14131 // load the player's map here if it's not already loaded
14132 Map *map = GetMap();
14134 // since the player may not be bound to the map yet, make sure subsequent
14135 // getmap calls won't create new maps
14136 SetInstanceId(map->GetInstanceId());
14138 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14139 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14141 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14142 if(at)
14143 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14144 else
14145 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14148 SaveRecallPosition();
14150 time_t now = time(NULL);
14151 time_t logoutTime = time_t(fields[16].GetUInt64());
14153 // since last logout (in seconds)
14154 uint64 time_diff = uint64(now - logoutTime);
14156 // set value, including drunk invisibility detection
14157 // calculate sobering. after 15 minutes logged out, the player will be sober again
14158 float soberFactor;
14159 if(time_diff > 15*MINUTE)
14160 soberFactor = 0;
14161 else
14162 soberFactor = 1-time_diff/(15.0f*MINUTE);
14163 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14164 SetDrunkValue(newDrunkenValue);
14166 m_rest_bonus = fields[15].GetFloat();
14167 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14168 float bubble0 = 0.031;
14169 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14170 float bubble1 = 0.125;
14172 if((int32)fields[16].GetUInt32() > 0)
14174 float bubble = fields[17].GetUInt32() > 0
14175 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14176 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14178 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14181 m_cinematic = fields[12].GetUInt32();
14182 m_Played_time[0]= fields[13].GetUInt32();
14183 m_Played_time[1]= fields[14].GetUInt32();
14185 m_resetTalentsCost = fields[18].GetUInt32();
14186 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14188 // reserve some flags
14189 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14191 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14192 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14194 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14196 uint32 extraflags = fields[25].GetUInt32();
14198 m_stableSlots = fields[26].GetUInt32();
14199 if(m_stableSlots > MAX_PET_STABLES)
14201 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14202 m_stableSlots = MAX_PET_STABLES;
14205 m_atLoginFlags = fields[27].GetUInt32();
14207 // Honor system
14208 // Update Honor kills data
14209 m_lastHonorUpdateTime = logoutTime;
14210 UpdateHonorFields();
14212 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14213 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14214 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14216 std::string taxi_nodes = fields[31].GetCppString();
14218 delete result;
14220 // clear channel spell data (if saved at channel spell casting)
14221 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14222 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14224 // clear charm/summon related fields
14225 SetCharm(NULL);
14226 SetPet(NULL);
14227 SetCharmerGUID(0);
14228 SetOwnerGUID(0);
14229 SetCreatorGUID(0);
14231 // reset some aura modifiers before aura apply
14232 SetFarSightGUID(0);
14233 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14234 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14236 _LoadSkills();
14238 // make sure the unit is considered out of combat for proper loading
14239 ClearInCombat();
14241 // make sure the unit is considered not in duel for proper loading
14242 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14243 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14245 // remember loaded power/health values to restore after stats initialization and modifier applying
14246 uint32 savedHealth = GetHealth();
14247 uint32 savedPower[MAX_POWERS];
14248 for(uint32 i = 0; i < MAX_POWERS; ++i)
14249 savedPower[i] = GetPower(Powers(i));
14251 // reset stats before loading any modifiers
14252 InitStatsForLevel();
14253 InitTaxiNodesForLevel();
14254 InitGlyphsForLevel();
14255 InitRunes();
14257 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14259 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14260 //_LoadMail();
14262 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14263 _LoadGlyphAuras();
14265 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14266 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14267 m_deathState = DEAD;
14269 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14271 // after spell load, learn rewarded spell if need also
14272 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14273 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14275 // after spell and quest load
14276 InitTalentForLevel();
14277 learnDefaultSpells();
14279 // must be before inventory (some items required reputation check)
14280 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14282 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14284 // update items with duration and realtime
14285 UpdateItemDuration(time_diff, true);
14287 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14289 // unread mails and next delivery time, actual mails not loaded
14290 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14292 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14294 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14295 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14296 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14298 if(!HasTitle(curTitle))
14299 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14302 // Not finish taxi flight path
14303 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14305 // problems with taxi path loading
14306 TaxiNodesEntry const* nodeEntry = NULL;
14307 if(uint32 node_id = m_taxi.GetTaxiSource())
14308 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14310 if(!nodeEntry) // don't know taxi start node, to homebind
14312 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14313 RelocateToHomebind();
14314 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14316 else // have start node, to it
14318 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14319 SetMapId(nodeEntry->map_id);
14320 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14321 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14323 m_taxi.ClearTaxiDestinations();
14325 else if(uint32 node_id = m_taxi.GetTaxiSource())
14327 // save source node as recall coord to prevent recall and fall from sky
14328 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14329 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14330 m_recallMap = nodeEntry->map_id;
14331 m_recallX = nodeEntry->x;
14332 m_recallY = nodeEntry->y;
14333 m_recallZ = nodeEntry->z;
14335 // flight will started later
14338 // has to be called after last Relocate() in Player::LoadFromDB
14339 SetFallInformation(0, GetPositionZ());
14341 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14343 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14344 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14345 if(!isAlive())
14346 RemoveAllAurasOnDeath();
14348 //apply all stat bonuses from items and auras
14349 SetCanModifyStats(true);
14350 UpdateAllStats();
14352 // restore remembered power/health values (but not more max values)
14353 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14354 for(uint32 i = 0; i < MAX_POWERS; ++i)
14355 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14357 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14358 outDebugValues();
14360 // GM state
14361 if(GetSession()->GetSecurity() > SEC_PLAYER)
14363 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14365 default:
14366 case 0: break; // disable
14367 case 1: SetGameMaster(true); break; // enable
14368 case 2: // save state
14369 if(extraflags & PLAYER_EXTRA_GM_ON)
14370 SetGameMaster(true);
14371 break;
14374 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14376 default:
14377 case 0: SetGMVisible(false); break; // invisible
14378 case 1: break; // visible
14379 case 2: // save state
14380 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14381 SetGMVisible(false);
14382 break;
14385 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14387 default:
14388 case 0: break; // disable
14389 case 1: SetAcceptTicket(true); break; // enable
14390 case 2: // save state
14391 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14392 SetAcceptTicket(true);
14393 break;
14396 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14398 default:
14399 case 0: break; // disable
14400 case 1: SetGMChat(true); break; // enable
14401 case 2: // save state
14402 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14403 SetGMChat(true);
14404 break;
14407 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14409 default:
14410 case 0: break; // disable
14411 case 1: SetAcceptWhispers(true); break; // enable
14412 case 2: // save state
14413 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14414 SetAcceptWhispers(true);
14415 break;
14419 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14421 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14422 m_achievementMgr.CheckAllAchievementCriteria();
14424 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14426 return true;
14429 bool Player::isAllowedToLoot(Creature* creature)
14431 if(Player* recipient = creature->GetLootRecipient())
14433 if (recipient == this)
14434 return true;
14435 if( Group* otherGroup = recipient->GetGroup())
14437 Group* thisGroup = GetGroup();
14438 if(!thisGroup)
14439 return false;
14440 return thisGroup == otherGroup;
14442 return false;
14444 else
14445 // prevent other players from looting if the recipient got disconnected
14446 return !creature->hasLootRecipient();
14449 void Player::_LoadActions(QueryResult *result)
14451 m_actionButtons.clear();
14453 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14455 if(result)
14459 Field *fields = result->Fetch();
14461 uint8 button = fields[0].GetUInt8();
14463 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14464 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14465 else
14467 sLog.outError( " ...at loading, and will deleted in DB also");
14469 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14470 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14473 while( result->NextRow() );
14475 delete result;
14479 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14481 m_Auras.clear();
14482 for (int i = 0; i < TOTAL_AURAS; ++i)
14483 m_modAuras[i].clear();
14485 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14487 if(result)
14491 Field *fields = result->Fetch();
14492 uint64 caster_guid = fields[0].GetUInt64();
14493 uint32 spellid = fields[1].GetUInt32();
14494 uint32 effindex = fields[2].GetUInt32();
14495 uint32 stackcount = fields[3].GetUInt32();
14496 int32 damage = (int32)fields[4].GetUInt32();
14497 int32 maxduration = (int32)fields[5].GetUInt32();
14498 int32 remaintime = (int32)fields[6].GetUInt32();
14499 int32 remaincharges = (int32)fields[7].GetUInt32();
14501 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14502 if(!spellproto)
14504 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14505 continue;
14508 if(effindex >= 3)
14510 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14511 continue;
14514 // negative effects should continue counting down after logout
14515 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14517 if(remaintime <= int32(timediff))
14518 continue;
14520 remaintime -= timediff;
14523 // prevent wrong values of remaincharges
14524 if(spellproto->procCharges)
14526 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14527 remaincharges = spellproto->procCharges;
14529 else
14530 remaincharges = 0;
14533 for(uint32 i=0; i<stackcount; ++i)
14535 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14536 if(!damage)
14537 damage = aura->GetModifier()->m_amount;
14539 // reset stolen single target auras
14540 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14541 aura->SetIsSingleTarget(false);
14543 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14544 AddAura(aura);
14545 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14548 while( result->NextRow() );
14550 delete result;
14553 if(m_class == CLASS_WARRIOR)
14554 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14557 void Player::_LoadGlyphAuras()
14559 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14561 if (uint32 glyph = GetGlyph(i))
14563 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14565 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14567 if(gp->TypeFlags == gs->TypeFlags)
14569 CastSpell(this, gp->SpellId, true);
14570 continue;
14572 else
14573 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14575 else
14576 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14578 else
14579 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14581 // On any error remove glyph
14582 SetGlyph(i, 0);
14587 void Player::LoadCorpse()
14589 if( isAlive() )
14591 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14593 else
14595 if(Corpse *corpse = GetCorpse())
14597 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14599 else
14601 //Prevent Dead Player login without corpse
14602 ResurrectPlayer(0.5f);
14607 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14609 //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());
14610 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14611 //NOTE: the "order by `bag`" is important because it makes sure
14612 //the bagMap is filled before items in the bags are loaded
14613 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14614 //expected to be equipped before offhand items (TODO: fixme)
14616 uint32 zone = GetZoneId();
14618 if (result)
14620 std::list<Item*> problematicItems;
14622 // prevent items from being added to the queue when stored
14623 m_itemUpdateQueueBlocked = true;
14626 Field *fields = result->Fetch();
14627 uint32 bag_guid = fields[1].GetUInt32();
14628 uint8 slot = fields[2].GetUInt8();
14629 uint32 item_guid = fields[3].GetUInt32();
14630 uint32 item_id = fields[4].GetUInt32();
14632 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14634 if(!proto)
14636 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14637 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14638 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14639 continue;
14642 Item *item = NewItemOrBag(proto);
14644 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14646 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14647 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14648 item->FSetState(ITEM_REMOVED);
14649 item->SaveToDB(); // it also deletes item object !
14650 continue;
14653 // not allow have in alive state item limited to another map/zone
14654 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14656 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14657 item->FSetState(ITEM_REMOVED);
14658 item->SaveToDB(); // it also deletes item object !
14659 continue;
14662 // "Conjured items disappear if you are logged out for more than 15 minutes"
14663 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14665 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14666 item->FSetState(ITEM_REMOVED);
14667 item->SaveToDB(); // it also deletes item object !
14668 continue;
14671 bool success = true;
14673 if (!bag_guid)
14675 // the item is not in a bag
14676 item->SetContainer( NULL );
14677 item->SetSlot(slot);
14679 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14681 ItemPosCountVec dest;
14682 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14683 item = StoreItem(dest, item, true);
14684 else
14685 success = false;
14687 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14689 uint16 dest;
14690 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14691 QuickEquipItem(dest, item);
14692 else
14693 success = false;
14695 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14697 ItemPosCountVec dest;
14698 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14699 item = BankItem(dest, item, true);
14700 else
14701 success = false;
14704 if(success)
14706 // store bags that may contain items in them
14707 if(item->IsBag() && IsBagPos(item->GetPos()))
14708 bagMap[item_guid] = (Bag*)item;
14711 else
14713 item->SetSlot(NULL_SLOT);
14714 // the item is in a bag, find the bag
14715 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14716 if(itr != bagMap.end())
14717 itr->second->StoreItem(slot, item, true );
14718 else
14719 success = false;
14722 // item's state may have changed after stored
14723 if (success)
14724 item->SetState(ITEM_UNCHANGED, this);
14725 else
14727 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);
14728 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14729 problematicItems.push_back(item);
14731 } while (result->NextRow());
14733 delete result;
14734 m_itemUpdateQueueBlocked = false;
14736 // send by mail problematic items
14737 while(!problematicItems.empty())
14739 // fill mail
14740 MailItemsInfo mi; // item list preparing
14742 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14744 Item* item = problematicItems.front();
14745 problematicItems.pop_front();
14747 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14750 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14752 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14755 //if(isAlive())
14756 _ApplyAllItemMods();
14759 // load mailed item which should receive current player
14760 void Player::_LoadMailedItems(Mail *mail)
14762 // data needs to be at first place for Item::LoadFromDB
14763 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);
14764 if(!result)
14765 return;
14769 Field *fields = result->Fetch();
14770 uint32 item_guid_low = fields[1].GetUInt32();
14771 uint32 item_template = fields[2].GetUInt32();
14773 mail->AddItem(item_guid_low, item_template);
14775 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14777 if(!proto)
14779 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);
14780 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14781 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14782 continue;
14785 Item *item = NewItemOrBag(proto);
14787 if(!item->LoadFromDB(item_guid_low, 0, result))
14789 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14790 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14791 item->FSetState(ITEM_REMOVED);
14792 item->SaveToDB(); // it also deletes item object !
14793 continue;
14796 AddMItem(item);
14797 } while (result->NextRow());
14799 delete result;
14802 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14804 //set a count of unread mails
14805 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14806 if (resultUnread)
14808 Field *fieldMail = resultUnread->Fetch();
14809 unReadMails = fieldMail[0].GetUInt8();
14810 delete resultUnread;
14813 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14814 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14815 if (resultDelivery)
14817 Field *fieldMail = resultDelivery->Fetch();
14818 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14819 delete resultDelivery;
14823 void Player::_LoadMail()
14825 m_mail.clear();
14826 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14827 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());
14828 if(result)
14832 Field *fields = result->Fetch();
14833 Mail *m = new Mail;
14834 m->messageID = fields[0].GetUInt32();
14835 m->messageType = fields[1].GetUInt8();
14836 m->sender = fields[2].GetUInt32();
14837 m->receiver = fields[3].GetUInt32();
14838 m->subject = fields[4].GetCppString();
14839 m->itemTextId = fields[5].GetUInt32();
14840 bool has_items = fields[6].GetBool();
14841 m->expire_time = (time_t)fields[7].GetUInt64();
14842 m->deliver_time = (time_t)fields[8].GetUInt64();
14843 m->money = fields[9].GetUInt32();
14844 m->COD = fields[10].GetUInt32();
14845 m->checked = fields[11].GetUInt32();
14846 m->stationery = fields[12].GetUInt8();
14847 m->mailTemplateId = fields[13].GetInt16();
14849 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14851 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14852 m->mailTemplateId = 0;
14855 m->state = MAIL_STATE_UNCHANGED;
14857 if (has_items)
14858 _LoadMailedItems(m);
14860 m_mail.push_back(m);
14861 } while( result->NextRow() );
14862 delete result;
14864 m_mailsLoaded = true;
14867 void Player::LoadPet()
14869 //fixme: the pet should still be loaded if the player is not in world
14870 // just not added to the map
14871 if(IsInWorld())
14873 Pet *pet = new Pet;
14874 if(!pet->LoadPetFromDB(this,0,0,true))
14875 delete pet;
14879 void Player::_LoadQuestStatus(QueryResult *result)
14881 mQuestStatus.clear();
14883 uint32 slot = 0;
14885 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14886 //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());
14888 if(result)
14892 Field *fields = result->Fetch();
14894 uint32 quest_id = fields[0].GetUInt32();
14895 // used to be new, no delete?
14896 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14897 if( pQuest )
14899 // find or create
14900 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14902 uint32 qstatus = fields[1].GetUInt32();
14903 if(qstatus < MAX_QUEST_STATUS)
14904 questStatusData.m_status = QuestStatus(qstatus);
14905 else
14907 questStatusData.m_status = QUEST_STATUS_NONE;
14908 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14911 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14912 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14914 time_t quest_time = time_t(fields[4].GetUInt64());
14916 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14918 AddTimedQuest( quest_id );
14920 if (quest_time <= sWorld.GetGameTime())
14921 questStatusData.m_timer = 1;
14922 else
14923 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14925 else
14926 quest_time = 0;
14928 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14929 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14930 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14931 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14932 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14933 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14934 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14935 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14937 questStatusData.uState = QUEST_UNCHANGED;
14939 // add to quest log
14940 if( slot < MAX_QUEST_LOG_SIZE &&
14941 ( questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
14942 questStatusData.m_status == QUEST_STATUS_COMPLETE &&
14943 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14945 SetQuestSlot(slot, quest_id, quest_time);
14947 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14948 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
14950 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14951 if(questStatusData.m_creatureOrGOcount[idx])
14952 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
14954 ++slot;
14957 if(questStatusData.m_rewarded)
14959 // learn rewarded spell if unknown
14960 learnQuestRewardedSpells(pQuest);
14962 // set rewarded title if any
14963 if(pQuest->GetCharTitleId())
14965 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14966 SetTitle(titleEntry);
14969 if(pQuest->GetBonusTalents())
14970 m_questRewardTalentCount += pQuest->GetBonusTalents();
14973 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14976 while( result->NextRow() );
14978 delete result;
14981 // clear quest log tail
14982 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14983 SetQuestSlot(i, 0);
14986 void Player::_LoadDailyQuestStatus(QueryResult *result)
14988 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14989 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14991 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14993 if(result)
14995 uint32 quest_daily_idx = 0;
14999 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15001 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15002 break;
15005 Field *fields = result->Fetch();
15007 uint32 quest_id = fields[0].GetUInt32();
15009 // save _any_ from daily quest times (it must be after last reset anyway)
15010 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15012 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15013 if( !pQuest )
15014 continue;
15016 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15017 ++quest_daily_idx;
15019 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15021 while( result->NextRow() );
15023 delete result;
15026 m_DailyQuestChanged = false;
15029 void Player::_LoadSpells(QueryResult *result)
15031 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15033 if(result)
15037 Field *fields = result->Fetch();
15039 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15041 while( result->NextRow() );
15043 delete result;
15047 void Player::_LoadGroup(QueryResult *result)
15049 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15050 if(result)
15052 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15053 delete result;
15054 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15055 if(group)
15057 uint8 subgroup = group->GetMemberGroup(GetGUID());
15058 SetGroup(group, subgroup);
15059 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15061 // the group leader may change the instance difficulty while the player is offline
15062 SetDifficulty(group->GetDifficulty());
15068 void Player::_LoadBoundInstances(QueryResult *result)
15070 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15071 m_boundInstances[i].clear();
15073 Group *group = GetGroup();
15075 //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));
15076 if(result)
15080 Field *fields = result->Fetch();
15081 bool perm = fields[1].GetBool();
15082 uint32 mapId = fields[2].GetUInt32();
15083 uint32 instanceId = fields[0].GetUInt32();
15084 uint8 difficulty = fields[3].GetUInt8();
15085 time_t resetTime = (time_t)fields[4].GetUInt64();
15086 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15087 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15088 // and in that case it is not used
15090 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15091 if(!mapEntry || !mapEntry->IsDungeon())
15093 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15094 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15095 continue;
15098 if(!perm && group)
15100 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);
15101 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15102 continue;
15105 // since non permanent binds are always solo bind, they can always be reset
15106 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15107 if(save) BindToInstance(save, perm, true);
15108 } while(result->NextRow());
15109 delete result;
15113 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15115 // some instances only have one difficulty
15116 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15117 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15119 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15120 if(itr != m_boundInstances[difficulty].end())
15121 return &itr->second;
15122 else
15123 return NULL;
15126 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15128 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15129 UnbindInstance(itr, difficulty, unload);
15132 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15134 if(itr != m_boundInstances[difficulty].end())
15136 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15137 itr->second.save->RemovePlayer(this); // save can become invalid
15138 m_boundInstances[difficulty].erase(itr++);
15142 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15144 if(save)
15146 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15147 if(bind.save)
15149 // update the save when the group kills a boss
15150 if(permanent != bind.perm || save != bind.save)
15151 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());
15153 else
15154 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15156 if(bind.save != save)
15158 if(bind.save) bind.save->RemovePlayer(this);
15159 save->AddPlayer(this);
15162 if(permanent) save->SetCanReset(false);
15164 bind.save = save;
15165 bind.perm = permanent;
15166 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());
15167 return &bind;
15169 else
15170 return NULL;
15173 void Player::SendRaidInfo()
15175 uint32 counter = 0;
15177 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15179 size_t p_counter = data.wpos();
15180 data << uint32(counter); // placeholder
15182 time_t now = time(NULL);
15184 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15186 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15188 if(itr->second.perm)
15190 InstanceSave *save = itr->second.save;
15191 data << uint32(save->GetMapId()); // map id
15192 data << uint32(save->GetDifficulty()); // difficulty
15193 data << uint64(save->GetInstanceId()); // instance id
15194 data << uint32(save->GetResetTime() - now); // reset time
15195 data << uint32(0); // is extended
15196 ++counter;
15200 data.put<uint32>(p_counter, counter);
15201 GetSession()->SendPacket(&data);
15205 - called on every successful teleportation to a map
15207 void Player::SendSavedInstances()
15209 bool hasBeenSaved = false;
15210 WorldPacket data;
15212 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15214 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15216 if(itr->second.perm) // only permanent binds are sent
15218 hasBeenSaved = true;
15219 break;
15224 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15225 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15226 data << uint32(hasBeenSaved);
15227 GetSession()->SendPacket(&data);
15229 if(!hasBeenSaved)
15230 return;
15232 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15234 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15236 if(itr->second.perm)
15238 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15239 data << uint32(itr->second.save->GetMapId());
15240 GetSession()->SendPacket(&data);
15246 /// convert the player's binds to the group
15247 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15249 bool has_binds = false;
15250 bool has_solo = false;
15252 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15253 assert(player_guid);
15255 // copy all binds to the group, when changing leader it's assumed the character
15256 // will not have any solo binds
15258 if(player)
15260 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15262 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15264 has_binds = true;
15265 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15266 // permanent binds are not removed
15267 if(!itr->second.perm)
15269 player->UnbindInstance(itr, i, true); // increments itr
15270 has_solo = true;
15272 else
15273 ++itr;
15278 // if the player's not online we don't know what binds it has
15279 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));
15280 // the following should not get executed when changing leaders
15281 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15284 bool Player::_LoadHomeBind(QueryResult *result)
15286 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15287 if(!info)
15289 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15290 return false;
15293 bool ok = false;
15294 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15295 if (result)
15297 Field *fields = result->Fetch();
15298 m_homebindMapId = fields[0].GetUInt32();
15299 m_homebindZoneId = fields[1].GetUInt16();
15300 m_homebindX = fields[2].GetFloat();
15301 m_homebindY = fields[3].GetFloat();
15302 m_homebindZ = fields[4].GetFloat();
15303 delete result;
15305 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15307 // accept saved data only for valid position (and non instanceable), and accessable
15308 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15309 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15311 ok = true;
15313 else
15314 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15317 if(!ok)
15319 m_homebindMapId = info->mapId;
15320 m_homebindZoneId = info->zoneId;
15321 m_homebindX = info->positionX;
15322 m_homebindY = info->positionY;
15323 m_homebindZ = info->positionZ;
15325 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);
15328 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15329 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15331 return true;
15334 /*********************************************************/
15335 /*** SAVE SYSTEM ***/
15336 /*********************************************************/
15338 void Player::SaveToDB()
15340 // delay auto save at any saves (manual, in code, or autosave)
15341 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15343 // first save/honor gain after midnight will also update the player's honor fields
15344 UpdateHonorFields();
15346 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15347 //save, far from tavern/city
15348 //save, but in tavern/city
15349 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15350 outDebugValues();
15352 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15353 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15354 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15355 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15356 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15357 uint32 tmp_displayid = GetDisplayId();
15359 // Set player sit state to standing on save, also stealth and shifted form
15360 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15361 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15362 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15363 SetDisplayId(GetNativeDisplayId());
15365 bool inworld = IsInWorld();
15367 CharacterDatabase.BeginTransaction();
15369 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15371 std::string sql_name = m_name;
15372 CharacterDatabase.escape_string(sql_name);
15374 std::ostringstream ss;
15375 ss << "INSERT INTO characters (guid,account,name,race,class,"
15376 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15377 "taximask, online, cinematic, "
15378 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15379 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15380 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15381 << GetGUIDLow() << ", "
15382 << GetSession()->GetAccountId() << ", '"
15383 << sql_name << "', "
15384 << m_race << ", "
15385 << m_class << ", ";
15387 if(!IsBeingTeleported())
15389 ss << GetMapId() << ", "
15390 << (uint32)GetDifficulty() << ", "
15391 << finiteAlways(GetPositionX()) << ", "
15392 << finiteAlways(GetPositionY()) << ", "
15393 << finiteAlways(GetPositionZ()) << ", "
15394 << finiteAlways(GetOrientation()) << ", '";
15396 else
15398 ss << GetTeleportDest().mapid << ", "
15399 << (uint32)GetDifficulty() << ", "
15400 << finiteAlways(GetTeleportDest().coord_x) << ", "
15401 << finiteAlways(GetTeleportDest().coord_y) << ", "
15402 << finiteAlways(GetTeleportDest().coord_z) << ", "
15403 << finiteAlways(GetTeleportDest().orientation) << ", '";
15406 uint16 i;
15407 for( i = 0; i < m_valuesCount; ++i )
15409 ss << GetUInt32Value(i) << " ";
15412 ss << "', ";
15414 ss << m_taxi; // string with TaxiMaskSize numbers
15416 ss << ", ";
15417 ss << (inworld ? 1 : 0);
15419 ss << ", ";
15420 ss << m_cinematic;
15422 ss << ", ";
15423 ss << m_Played_time[0];
15424 ss << ", ";
15425 ss << m_Played_time[1];
15427 ss << ", ";
15428 ss << finiteAlways(m_rest_bonus);
15429 ss << ", ";
15430 ss << (uint64)time(NULL);
15431 ss << ", ";
15432 ss << is_save_resting;
15433 ss << ", ";
15434 ss << m_resetTalentsCost;
15435 ss << ", ";
15436 ss << (uint64)m_resetTalentsTime;
15438 ss << ", ";
15439 ss << finiteAlways(m_movementInfo.t_x);
15440 ss << ", ";
15441 ss << finiteAlways(m_movementInfo.t_y);
15442 ss << ", ";
15443 ss << finiteAlways(m_movementInfo.t_z);
15444 ss << ", ";
15445 ss << finiteAlways(m_movementInfo.t_o);
15446 ss << ", ";
15447 if (m_transport)
15448 ss << m_transport->GetGUIDLow();
15449 else
15450 ss << "0";
15452 ss << ", ";
15453 ss << m_ExtraFlags;
15455 ss << ", ";
15456 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15458 ss << ", ";
15459 ss << uint32(m_atLoginFlags);
15461 ss << ", ";
15462 ss << GetZoneId();
15464 ss << ", ";
15465 ss << (uint64)m_deathExpireTime;
15467 ss << ", '";
15468 ss << m_taxi.SaveTaxiDestinationsToString();
15469 ss << "', '0', ";
15470 ss << GetBattleGroundId();
15471 ss << ", ";
15472 ss << GetBGTeam();
15473 ss << ", ";
15474 ss << m_bgEntryPoint.mapid << ", "
15475 << finiteAlways(m_bgEntryPoint.coord_x) << ", "
15476 << finiteAlways(m_bgEntryPoint.coord_y) << ", "
15477 << finiteAlways(m_bgEntryPoint.coord_z) << ", "
15478 << finiteAlways(m_bgEntryPoint.orientation);
15479 ss << ")";
15481 CharacterDatabase.Execute( ss.str().c_str() );
15483 if(m_mailsUpdated) //save mails only when needed
15484 _SaveMail();
15486 _SaveInventory();
15487 _SaveQuestStatus();
15488 _SaveDailyQuestStatus();
15489 _SaveSpells();
15490 _SaveSpellCooldowns();
15491 _SaveActions();
15492 _SaveAuras();
15493 m_achievementMgr.SaveToDB();
15494 m_reputationMgr.SaveToDB();
15495 _SaveEquipmentSets();
15496 GetSession()->SaveTutorialsData(); // changed only while character in game
15498 CharacterDatabase.CommitTransaction();
15500 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15501 SetDisplayId(tmp_displayid);
15502 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15503 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15504 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15505 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15507 // save pet (hunter pet level and experience and all type pets health/mana).
15508 if(Pet* pet = GetPet())
15509 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15512 // fast save function for item/money cheating preventing - save only inventory and money state
15513 void Player::SaveInventoryAndGoldToDB()
15515 _SaveInventory();
15516 //money is in data field
15517 SaveDataFieldToDB();
15520 void Player::_SaveActions()
15522 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15524 switch (itr->second.uState)
15526 case ACTIONBUTTON_NEW:
15527 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15528 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15529 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15530 ++itr;
15531 break;
15532 case ACTIONBUTTON_CHANGED:
15533 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15534 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15535 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15536 ++itr;
15537 break;
15538 case ACTIONBUTTON_DELETED:
15539 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15540 m_actionButtons.erase(itr++);
15541 break;
15542 default:
15543 ++itr;
15544 break;
15549 void Player::_SaveAuras()
15551 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15553 AuraMap const& auras = GetAuras();
15555 if (auras.empty())
15556 return;
15558 spellEffectPair lastEffectPair = auras.begin()->first;
15559 uint32 stackCounter = 1;
15561 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15563 if(itr == auras.end() || lastEffectPair != itr->first)
15565 AuraMap::const_iterator itr2 = itr;
15566 // save previous spellEffectPair to db
15567 itr2--;
15569 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15571 //skip all auras from spells that are passive or need a shapeshift
15572 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15574 //do not save single target auras (unless they were cast by the player)
15575 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15577 uint8 i;
15578 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15579 for (i = 0; i < 3; ++i)
15580 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15581 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15582 break;
15584 if (i == 3)
15586 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15587 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15588 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()));
15593 if(itr == auras.end())
15594 break;
15597 if (lastEffectPair == itr->first)
15598 stackCounter++;
15599 else
15601 lastEffectPair = itr->first;
15602 stackCounter = 1;
15607 void Player::_SaveInventory()
15609 // force items in buyback slots to new state
15610 // and remove those that aren't already
15611 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15613 Item *item = m_items[i];
15614 if (!item || item->GetState() == ITEM_NEW) continue;
15615 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15616 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15617 m_items[i]->FSetState(ITEM_NEW);
15620 // update enchantment durations
15621 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15623 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15626 // if no changes
15627 if (m_itemUpdateQueue.empty()) return;
15629 // do not save if the update queue is corrupt
15630 bool error = false;
15631 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15633 Item *item = m_itemUpdateQueue[i];
15634 if(!item || item->GetState() == ITEM_REMOVED) continue;
15635 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15637 if (test == NULL)
15639 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());
15640 error = true;
15642 else if (test != item)
15644 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());
15645 error = true;
15649 if (error)
15651 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15652 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15653 return;
15656 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15658 Item *item = m_itemUpdateQueue[i];
15659 if(!item) continue;
15661 Bag *container = item->GetContainer();
15662 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15664 switch(item->GetState())
15666 case ITEM_NEW:
15667 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());
15668 break;
15669 case ITEM_CHANGED:
15670 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());
15671 break;
15672 case ITEM_REMOVED:
15673 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15674 break;
15675 case ITEM_UNCHANGED:
15676 break;
15679 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15681 m_itemUpdateQueue.clear();
15684 void Player::_SaveMail()
15686 if (!m_mailsLoaded)
15687 return;
15689 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15691 Mail *m = (*itr);
15692 if (m->state == MAIL_STATE_CHANGED)
15694 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15695 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15696 if(m->removedItems.size())
15698 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15699 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15700 m->removedItems.clear();
15702 m->state = MAIL_STATE_UNCHANGED;
15704 else if (m->state == MAIL_STATE_DELETED)
15706 if (m->HasItems())
15707 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15708 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15709 if (m->itemTextId)
15710 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15711 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15712 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15716 //deallocate deleted mails...
15717 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15719 if ((*itr)->state == MAIL_STATE_DELETED)
15721 Mail* m = *itr;
15722 m_mail.erase(itr);
15723 delete m;
15724 itr = m_mail.begin();
15726 else
15727 ++itr;
15730 m_mailsUpdated = false;
15733 void Player::_SaveQuestStatus()
15735 // we don't need transactions here.
15736 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15738 switch (i->second.uState)
15740 case QUEST_NEW :
15741 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15742 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15743 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]);
15744 break;
15745 case QUEST_CHANGED :
15746 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15747 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 );
15748 break;
15749 case QUEST_UNCHANGED:
15750 break;
15752 i->second.uState = QUEST_UNCHANGED;
15756 void Player::_SaveDailyQuestStatus()
15758 if(!m_DailyQuestChanged)
15759 return;
15761 m_DailyQuestChanged = false;
15763 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15765 // we don't need transactions here.
15766 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15767 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15768 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15769 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15770 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15773 void Player::_SaveSpells()
15775 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15777 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15778 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15780 // add only changed/new not dependent spells
15781 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15782 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);
15784 if (itr->second->state == PLAYERSPELL_REMOVED)
15786 delete itr->second;
15787 m_spells.erase(itr++);
15789 else
15791 itr->second->state = PLAYERSPELL_UNCHANGED;
15792 ++itr;
15798 void Player::outDebugValues() const
15800 if(!sLog.IsOutDebug()) // optimize disabled debug output
15801 return;
15803 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15804 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15805 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15806 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15807 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15808 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15809 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15810 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15811 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15812 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15813 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15814 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15817 /*********************************************************/
15818 /*** FLOOD FILTER SYSTEM ***/
15819 /*********************************************************/
15821 void Player::UpdateSpeakTime()
15823 // ignore chat spam protection for GMs in any mode
15824 if(GetSession()->GetSecurity() > SEC_PLAYER)
15825 return;
15827 time_t current = time (NULL);
15828 if(m_speakTime > current)
15830 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15831 if(!max_count)
15832 return;
15834 ++m_speakCount;
15835 if(m_speakCount >= max_count)
15837 // prevent overwrite mute time, if message send just before mutes set, for example.
15838 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15839 if(GetSession()->m_muteTime < new_mute)
15840 GetSession()->m_muteTime = new_mute;
15842 m_speakCount = 0;
15845 else
15846 m_speakCount = 0;
15848 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15851 bool Player::CanSpeak() const
15853 return GetSession()->m_muteTime <= time (NULL);
15856 /*********************************************************/
15857 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15858 /*********************************************************/
15860 void Player::SendAttackSwingNotInRange()
15862 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15863 GetSession()->SendPacket( &data );
15866 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15868 std::ostringstream ss;
15869 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15870 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15871 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15872 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15873 sLog.outDebug(ss.str().c_str());
15874 CharacterDatabase.Execute(ss.str().c_str());
15877 void Player::SaveDataFieldToDB()
15879 std::ostringstream ss;
15880 ss<<"UPDATE characters SET data='";
15882 for(uint16 i = 0; i < m_valuesCount; ++i )
15884 ss << GetUInt32Value(i) << " ";
15886 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15888 CharacterDatabase.Execute(ss.str().c_str());
15891 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15893 std::ostringstream ss2;
15894 ss2<<"UPDATE characters SET data='";
15895 int i=0;
15896 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15898 ss2<<tokens[i]<<" ";
15900 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15902 return CharacterDatabase.Execute(ss2.str().c_str());
15905 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15907 char buf[11];
15908 snprintf(buf,11,"%u",value);
15910 if(index >= tokens.size())
15911 return;
15913 tokens[index] = buf;
15916 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15918 Tokens tokens;
15919 if(!LoadValuesArrayFromDB(tokens,guid))
15920 return;
15922 if(index >= tokens.size())
15923 return;
15925 char buf[11];
15926 snprintf(buf,11,"%u",value);
15927 tokens[index] = buf;
15929 SaveValuesArrayInDB(tokens,guid);
15932 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15934 uint32 temp;
15935 memcpy(&temp, &value, sizeof(value));
15936 Player::SetUInt32ValueInDB(index, temp, guid);
15939 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15941 Tokens tokens;
15942 if(!LoadValuesArrayFromDB(tokens, guid))
15943 return;
15945 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15946 uint8 race = unit_bytes0 & 0xFF;
15947 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15949 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15950 if(!info)
15951 return;
15953 unit_bytes0 &= ~(0xFF << 16);
15954 unit_bytes0 |= (gender << 16);
15955 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15957 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15958 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15960 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15962 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15963 player_bytes2 &= ~0xFF;
15964 player_bytes2 |= facialHair;
15965 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15967 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15968 player_bytes3 &= ~0xFF;
15969 player_bytes3 |= gender;
15970 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15972 SaveValuesArrayInDB(tokens, guid);
15975 void Player::SendAttackSwingDeadTarget()
15977 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15978 GetSession()->SendPacket( &data );
15981 void Player::SendAttackSwingCantAttack()
15983 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15984 GetSession()->SendPacket( &data );
15987 void Player::SendAttackSwingCancelAttack()
15989 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15990 GetSession()->SendPacket( &data );
15993 void Player::SendAttackSwingBadFacingAttack()
15995 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15996 GetSession()->SendPacket( &data );
15999 void Player::SendAutoRepeatCancel()
16001 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16002 data.append(GetPackGUID()); // may be it's target guid
16003 GetSession()->SendPacket( &data );
16006 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16008 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16009 data << Area;
16010 data << Experience;
16011 GetSession()->SendPacket(&data);
16014 void Player::SendDungeonDifficulty(bool IsInGroup)
16016 uint8 val = 0x00000001;
16017 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16018 data << (uint32)GetDifficulty();
16019 data << uint32(val);
16020 data << uint32(IsInGroup);
16021 GetSession()->SendPacket(&data);
16024 void Player::SendResetFailedNotify(uint32 mapid)
16026 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16027 data << uint32(mapid);
16028 GetSession()->SendPacket(&data);
16031 /// Reset all solo instances and optionally send a message on success for each
16032 void Player::ResetInstances(uint8 method)
16034 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16036 // we assume that when the difficulty changes, all instances that can be reset will be
16037 uint8 dif = GetDifficulty();
16039 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16041 InstanceSave *p = itr->second.save;
16042 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16043 if(!entry || !p->CanReset())
16045 ++itr;
16046 continue;
16049 if(method == INSTANCE_RESET_ALL)
16051 // the "reset all instances" method can only reset normal maps
16052 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16054 ++itr;
16055 continue;
16059 // if the map is loaded, reset it
16060 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16061 if(map && map->IsDungeon())
16062 ((InstanceMap*)map)->Reset(method);
16064 // since this is a solo instance there should not be any players inside
16065 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16066 SendResetInstanceSuccess(p->GetMapId());
16068 p->DeleteFromDB();
16069 m_boundInstances[dif].erase(itr++);
16071 // the following should remove the instance save from the manager and delete it as well
16072 p->RemovePlayer(this);
16076 void Player::SendResetInstanceSuccess(uint32 MapId)
16078 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16079 data << MapId;
16080 GetSession()->SendPacket(&data);
16083 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16085 // TODO: find what other fail reasons there are besides players in the instance
16086 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16087 data << reason;
16088 data << MapId;
16089 GetSession()->SendPacket(&data);
16092 /*********************************************************/
16093 /*** Update timers ***/
16094 /*********************************************************/
16096 ///checks the 15 afk reports per 5 minutes limit
16097 void Player::UpdateAfkReport(time_t currTime)
16099 if(m_bgAfkReportedTimer <= currTime)
16101 m_bgAfkReportedCount = 0;
16102 m_bgAfkReportedTimer = currTime+5*MINUTE;
16106 void Player::UpdateContestedPvP(uint32 diff)
16108 if(!m_contestedPvPTimer||isInCombat())
16109 return;
16110 if(m_contestedPvPTimer <= diff)
16112 ResetContestedPvP();
16114 else
16115 m_contestedPvPTimer -= diff;
16118 void Player::UpdatePvPFlag(time_t currTime)
16120 if(!IsPvP())
16121 return;
16122 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16123 return;
16125 UpdatePvP(false);
16128 void Player::UpdateDuelFlag(time_t currTime)
16130 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16131 return;
16133 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16134 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16136 duel->startTimer = 0;
16137 duel->startTime = currTime;
16138 duel->opponent->duel->startTimer = 0;
16139 duel->opponent->duel->startTime = currTime;
16142 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16144 if(!pet)
16145 pet = GetPet();
16147 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16149 //returning of reagents only for players, so best done here
16150 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16151 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16153 if(spellInfo)
16155 for(uint32 i = 0; i < 7; ++i)
16157 if(spellInfo->Reagent[i] > 0)
16159 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16160 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16161 if( msg == EQUIP_ERR_OK )
16163 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16164 if(IsInWorld())
16165 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16170 m_temporaryUnsummonedPetNumber = 0;
16173 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16174 return;
16176 // only if current pet in slot
16177 switch(pet->getPetType())
16179 case MINI_PET:
16180 m_miniPet = 0;
16181 break;
16182 case GUARDIAN_PET:
16183 RemoveGuardian(pet);
16184 break;
16185 default:
16186 if(GetPetGUID() == pet->GetGUID())
16187 SetPet(NULL);
16188 break;
16191 pet->CombatStop();
16193 if(returnreagent)
16195 switch(pet->GetEntry())
16197 //warlock pets except imp are removed(?) when logging out
16198 case 1860:
16199 case 1863:
16200 case 417:
16201 case 17252:
16202 mode = PET_SAVE_NOT_IN_SLOT;
16203 break;
16207 pet->SavePetToDB(mode);
16209 pet->CleanupsBeforeDelete();
16210 pet->AddObjectToRemoveList();
16211 pet->m_removed = true;
16213 if(pet->isControlled())
16215 WorldPacket data(SMSG_PET_SPELLS, 8);
16216 data << uint64(0);
16217 GetSession()->SendPacket(&data);
16219 if(GetGroup())
16220 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16224 void Player::RemoveMiniPet()
16226 if(Pet* pet = GetMiniPet())
16228 pet->Remove(PET_SAVE_AS_DELETED);
16229 m_miniPet = 0;
16233 Pet* Player::GetMiniPet()
16235 if(!m_miniPet)
16236 return NULL;
16237 return ObjectAccessor::GetPet(m_miniPet);
16240 void Player::Uncharm()
16242 Unit* charm = GetCharm();
16243 if(!charm)
16244 return;
16246 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16247 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16250 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16252 *data << (uint8)msgtype;
16253 *data << (uint32)language;
16254 *data << (uint64)GetGUID();
16255 *data << (uint32)language; //language 2.1.0 ?
16256 *data << (uint64)GetGUID();
16257 *data << (uint32)(text.length()+1);
16258 *data << text;
16259 *data << (uint8)chatTag();
16262 void Player::Say(const std::string& text, const uint32 language)
16264 WorldPacket data(SMSG_MESSAGECHAT, 200);
16265 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16266 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16269 void Player::Yell(const std::string& text, const uint32 language)
16271 WorldPacket data(SMSG_MESSAGECHAT, 200);
16272 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16273 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16276 void Player::TextEmote(const std::string& text)
16278 WorldPacket data(SMSG_MESSAGECHAT, 200);
16279 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16280 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16283 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16285 if (language != LANG_ADDON) // if not addon data
16286 language = LANG_UNIVERSAL; // whispers should always be readable
16288 Player *rPlayer = objmgr.GetPlayer(receiver);
16290 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16291 if(!rPlayer->isDND() || isGameMaster())
16293 WorldPacket data(SMSG_MESSAGECHAT, 200);
16294 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16295 rPlayer->GetSession()->SendPacket(&data);
16297 data.Initialize(SMSG_MESSAGECHAT, 200);
16298 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16299 GetSession()->SendPacket(&data);
16301 else
16303 // announce to player that player he is whispering to is dnd and cannot receive his message
16304 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16307 if(!isAcceptWhispers())
16309 SetAcceptWhispers(true);
16310 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16313 // announce to player that player he is whispering to is afk
16314 if(rPlayer->isAFK())
16315 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16317 // if player whisper someone, auto turn of dnd to be able to receive an answer
16318 if(isDND() && !rPlayer->isGameMaster())
16319 ToggleDND();
16322 void Player::PetSpellInitialize()
16324 Pet* pet = GetPet();
16326 if(!pet)
16327 return;
16329 sLog.outDebug("Pet Spells Groups");
16331 CharmInfo *charmInfo = pet->GetCharmInfo();
16333 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16334 data << uint64(pet->GetGUID());
16335 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16336 data << uint32(0);
16337 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16339 // action bar loop
16340 charmInfo->BuildActionBar(&data);
16342 size_t spellsCountPos = data.wpos();
16344 // spells count
16345 uint8 addlist = 0;
16346 data << uint8(addlist); // placeholder
16348 if (pet->IsPermanentPetFor(this))
16350 // spells loop
16351 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16353 if(itr->second.state == PETSPELL_REMOVED)
16354 continue;
16356 data << uint16(itr->first);
16357 data << uint16(itr->second.active); // pet spell active state isn't boolean
16358 ++addlist;
16362 data.put<uint8>(spellsCountPos, addlist);
16364 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16365 data << uint8(cooldownsCount);
16367 time_t curTime = time(NULL);
16369 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16371 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16373 data << uint32(itr->first); // spellid
16374 data << uint16(0); // spell category?
16375 data << uint32(cooldown); // cooldown
16376 data << uint32(0); // category cooldown
16379 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16381 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16383 data << uint32(itr->first); // spellid
16384 data << uint16(0); // spell category?
16385 data << uint32(0); // cooldown
16386 data << uint32(cooldown); // category cooldown
16389 GetSession()->SendPacket(&data);
16392 void Player::PossessSpellInitialize()
16394 Unit* charm = GetCharm();
16396 if(!charm)
16397 return;
16399 CharmInfo *charmInfo = charm->GetCharmInfo();
16401 if(!charmInfo)
16403 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16404 return;
16407 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16408 data << uint64(charm->GetGUID());
16409 data << uint16(0);
16410 data << uint32(0);
16411 data << uint32(0);
16413 charmInfo->BuildActionBar(&data);
16415 data << uint8(0); // spells count
16416 data << uint8(0); // cooldowns count
16418 GetSession()->SendPacket(&data);
16421 void Player::CharmSpellInitialize()
16423 Unit* charm = GetCharm();
16425 if(!charm)
16426 return;
16428 CharmInfo *charmInfo = charm->GetCharmInfo();
16429 if(!charmInfo)
16431 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16432 return;
16435 uint8 addlist = 0;
16437 if(charm->GetTypeId() != TYPEID_PLAYER)
16439 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16441 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16443 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16445 if(charmInfo->GetCharmSpell(i)->spellId)
16446 ++addlist;
16451 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16452 data << uint64(charm->GetGUID());
16453 data << uint16(0);
16454 data << uint32(0);
16456 if(charm->GetTypeId() != TYPEID_PLAYER)
16457 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16458 else
16459 data << uint8(0) << uint8(0) << uint16(0);
16461 charmInfo->BuildActionBar(&data);
16463 data << uint8(addlist);
16465 if(addlist)
16467 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16469 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16470 if(cspell->spellId)
16472 data << uint16(cspell->spellId);
16473 data << uint16(cspell->active);
16478 data << uint8(0); // cooldowns count
16480 GetSession()->SendPacket(&data);
16483 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16485 if (!mod || !spellInfo)
16486 return false;
16488 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16490 // prevent apply to any spell except spell that trigger expire
16491 if(spell)
16493 if(mod->lastAffected != spell)
16494 return false;
16496 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16497 return false;
16500 return spellmgr.IsAffectedByMod(spellInfo, mod);
16503 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16505 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16507 for(int eff=0;eff<96;++eff)
16509 uint64 _mask = 0;
16510 uint64 _mask2= 0;
16511 if (eff<64) _mask = uint64(1) << (eff- 0);
16512 else _mask2= uint64(1) << (eff-64);
16513 if ( mod->mask & _mask || mod->mask2 & _mask2)
16515 int32 val = 0;
16516 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16518 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16519 val += (*itr)->value;
16521 val += apply ? mod->value : -(mod->value);
16522 WorldPacket data(Opcode, (1+1+4));
16523 data << uint8(eff);
16524 data << uint8(mod->op);
16525 data << int32(val);
16526 SendDirectMessage(&data);
16530 if (apply)
16531 m_spellMods[mod->op].push_back(mod);
16532 else
16534 if (mod->charges == -1)
16535 --m_SpellModRemoveCount;
16536 m_spellMods[mod->op].remove(mod);
16537 delete mod;
16541 void Player::RemoveSpellMods(Spell const* spell)
16543 if(!spell || (m_SpellModRemoveCount == 0))
16544 return;
16546 for(int i=0;i<MAX_SPELLMOD;++i)
16548 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16550 SpellModifier *mod = *itr;
16551 ++itr;
16553 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16555 RemoveAurasDueToSpell(mod->spellId);
16556 if (m_spellMods[i].empty())
16557 break;
16558 else
16559 itr = m_spellMods[i].begin();
16565 // send Proficiency
16566 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16568 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16569 data << pr1 << pr2;
16570 GetSession()->SendPacket (&data);
16573 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16575 QueryResult *result = NULL;
16576 if(type==10)
16577 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16578 else
16579 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16580 if(result)
16582 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.
16583 { // and SendPetitionQueryOpcode reads data from the DB
16584 Field *fields = result->Fetch();
16585 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16586 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16588 // send update if charter owner in game
16589 Player* owner = objmgr.GetPlayer(ownerguid);
16590 if(owner)
16591 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16593 } while ( result->NextRow() );
16595 delete result;
16597 if(type==10)
16598 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16599 else
16600 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16603 CharacterDatabase.BeginTransaction();
16604 if(type == 10)
16606 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16607 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16609 else
16611 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16612 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16614 CharacterDatabase.CommitTransaction();
16617 void Player::LeaveAllArenaTeams(uint64 guid)
16619 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));
16620 if(!result)
16621 return;
16625 Field *fields = result->Fetch();
16626 uint32 at_id = fields[0].GetUInt32();
16627 if(at_id != 0)
16629 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16630 if(at)
16631 at->DelMember(guid);
16633 } while (result->NextRow());
16635 delete result;
16638 void Player::SetRestBonus (float rest_bonus_new)
16640 // Prevent resting on max level
16641 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16642 rest_bonus_new = 0;
16644 if(rest_bonus_new < 0)
16645 rest_bonus_new = 0;
16647 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16649 if(rest_bonus_new > rest_bonus_max)
16650 m_rest_bonus = rest_bonus_max;
16651 else
16652 m_rest_bonus = rest_bonus_new;
16654 // update data for client
16655 if(m_rest_bonus>10)
16656 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16657 else if(m_rest_bonus<=1)
16658 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16660 //RestTickUpdate
16661 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16664 void Player::HandleStealthedUnitsDetection()
16666 std::list<Unit*> stealthedUnits;
16668 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16669 Cell cell(p);
16670 cell.data.Part.reserved = ALL_DISTRICT;
16671 cell.SetNoCreate();
16673 MaNGOS::AnyStealthedCheck u_check;
16674 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16676 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16677 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16679 CellLock<GridReadGuard> cell_lock(cell, p);
16680 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16681 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16683 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16685 if((*i)==this)
16687 i = stealthedUnits.erase(i);
16688 continue;
16691 if ((*i)->isVisibleForOrDetect(this,true))
16694 (*i)->SendUpdateToPlayer(this);
16695 m_clientGUIDs.insert((*i)->GetGUID());
16697 #ifdef MANGOS_DEBUG
16698 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16699 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16700 #endif
16702 // target aura duration for caster show only if target exist at caster client
16703 // send data at target visibility change (adding to client)
16704 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16705 SendAurasForTarget(*i);
16707 i = stealthedUnits.erase(i);
16708 continue;
16711 ++i;
16715 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16717 if(nodes.size() < 2)
16718 return false;
16720 // 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
16721 if(GetSession()->isLogingOut() || isInCombat())
16723 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16724 data << uint32(ERR_TAXIPLAYERBUSY);
16725 GetSession()->SendPacket(&data);
16726 return false;
16729 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16730 return false;
16732 // taximaster case
16733 if(npc)
16735 // not let cheating with start flight mounted
16736 if(IsMounted())
16738 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16739 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16740 GetSession()->SendPacket(&data);
16741 return false;
16744 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16746 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16747 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16748 GetSession()->SendPacket(&data);
16749 return false;
16752 // 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
16753 if(IsNonMeleeSpellCasted(false))
16755 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16756 data << uint32(ERR_TAXIPLAYERBUSY);
16757 GetSession()->SendPacket(&data);
16758 return false;
16761 // cast case or scripted call case
16762 else
16764 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16766 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16767 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16769 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16770 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16772 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16774 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16775 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16778 uint32 sourcenode = nodes[0];
16780 // starting node too far away (cheat?)
16781 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16782 if (!node)
16784 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16785 data << uint32(ERR_TAXINOSUCHPATH);
16786 GetSession()->SendPacket(&data);
16787 return false;
16790 // check node starting pos data set case if provided
16791 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16793 if (node->map_id != GetMapId() ||
16794 (node->x - GetPositionX())*(node->x - GetPositionX())+
16795 (node->y - GetPositionY())*(node->y - GetPositionY())+
16796 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16797 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16799 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16800 data << uint32(ERR_TAXITOOFARAWAY);
16801 GetSession()->SendPacket(&data);
16802 return false;
16805 // node must have pos if taxi master case (npc != NULL)
16806 else if (npc)
16808 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16809 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16810 GetSession()->SendPacket(&data);
16811 return false;
16814 // Prepare to flight start now
16816 // stop combat at start taxi flight if any
16817 CombatStop();
16819 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16820 TradeCancel(true);
16822 // clean not finished taxi path if any
16823 m_taxi.ClearTaxiDestinations();
16825 // 0 element current node
16826 m_taxi.AddTaxiDestination(sourcenode);
16828 // fill destinations path tail
16829 uint32 sourcepath = 0;
16830 uint32 totalcost = 0;
16832 uint32 prevnode = sourcenode;
16833 uint32 lastnode = 0;
16835 for(uint32 i = 1; i < nodes.size(); ++i)
16837 uint32 path, cost;
16839 lastnode = nodes[i];
16840 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16842 if(!path)
16844 m_taxi.ClearTaxiDestinations();
16845 return false;
16848 totalcost += cost;
16850 if(prevnode == sourcenode)
16851 sourcepath = path;
16853 m_taxi.AddTaxiDestination(lastnode);
16855 prevnode = lastnode;
16858 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16859 uint32 mount_display_id = objmgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
16861 // in spell case allow 0 model
16862 if (mount_display_id == 0 && spellid == 0 || sourcepath == 0)
16864 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16865 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16866 GetSession()->SendPacket(&data);
16867 m_taxi.ClearTaxiDestinations();
16868 return false;
16871 uint32 money = GetMoney();
16873 if (npc)
16874 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16876 if(money < totalcost)
16878 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16879 data << uint32(ERR_TAXINOTENOUGHMONEY);
16880 GetSession()->SendPacket(&data);
16881 m_taxi.ClearTaxiDestinations();
16882 return false;
16885 //Checks and preparations done, DO FLIGHT
16886 ModifyMoney(-(int32)totalcost);
16887 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16888 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16890 // prevent stealth flight
16891 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16893 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16894 data << uint32(ERR_TAXIOK);
16895 GetSession()->SendPacket(&data);
16897 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16899 GetSession()->SendDoFlight(mount_display_id, sourcepath);
16901 return true;
16904 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
16906 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
16907 if(!entry)
16908 return false;
16910 std::vector<uint32> nodes;
16912 nodes.resize(2);
16913 nodes[0] = entry->from;
16914 nodes[1] = entry->to;
16916 return ActivateTaxiPathTo(nodes,NULL,spellid);
16919 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16921 // last check 2.0.10
16922 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16923 data << GetGUID();
16924 data << uint8(0x0); // flags (0x1, 0x2)
16925 time_t curTime = time(NULL);
16926 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16928 if (itr->second->state == PLAYERSPELL_REMOVED)
16929 continue;
16930 uint32 unSpellId = itr->first;
16931 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16932 if (!spellInfo)
16934 ASSERT(spellInfo);
16935 continue;
16938 // Not send cooldown for this spells
16939 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16940 continue;
16942 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16944 data << uint32(unSpellId);
16945 data << uint32(unTimeMs); // in m.secs
16946 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16949 GetSession()->SendPacket(&data);
16952 void Player::InitDataForForm(bool reapplyMods)
16954 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16955 if(ssEntry && ssEntry->attackSpeed)
16957 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16958 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16959 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16961 else
16962 SetRegularAttackTime();
16964 switch(m_form)
16966 case FORM_CAT:
16968 if(getPowerType()!=POWER_ENERGY)
16969 setPowerType(POWER_ENERGY);
16970 break;
16972 case FORM_BEAR:
16973 case FORM_DIREBEAR:
16975 if(getPowerType()!=POWER_RAGE)
16976 setPowerType(POWER_RAGE);
16977 break;
16979 default: // 0, for example
16981 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16982 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16983 setPowerType(Powers(cEntry->powerType));
16984 break;
16988 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16989 if (!reapplyMods)
16990 UpdateEquipSpellsAtFormChange();
16992 UpdateAttackPowerAndDamage();
16993 UpdateAttackPowerAndDamage(true);
16996 // Return true is the bought item has a max count to force refresh of window by caller
16997 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16999 // cheating attempt
17000 if(count < 1) count = 1;
17002 if(!isAlive())
17003 return false;
17005 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17006 if( !pProto )
17008 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17009 return false;
17012 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17013 if (!pCreature)
17015 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17016 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17017 return false;
17020 VendorItemData const* vItems = pCreature->GetVendorItems();
17021 if(!vItems || vItems->Empty())
17023 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17024 return false;
17027 size_t vendor_slot = vItems->FindItemSlot(item);
17028 if(vendor_slot >= vItems->GetItemCount())
17030 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17031 return false;
17034 VendorItem const* crItem = vItems->m_items[vendor_slot];
17036 // check current item amount if it limited
17037 if( crItem->maxcount != 0 )
17039 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17041 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17042 return false;
17046 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17048 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17049 return false;
17052 if(crItem->ExtendedCost)
17054 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17055 if(!iece)
17057 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17058 return false;
17061 // honor points price
17062 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17064 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17065 return false;
17068 // arena points price
17069 if(GetArenaPoints() < (iece->reqarenapoints * count))
17071 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17072 return false;
17075 // item base price
17076 for (uint8 i = 0; i < 5; ++i)
17078 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17080 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17081 return false;
17085 // check for personal arena rating requirement
17086 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17088 // probably not the proper equip err
17089 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17090 return false;
17094 uint32 price = pProto->BuyPrice * count;
17096 // reputation discount
17097 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17099 if( GetMoney() < price )
17101 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17102 return false;
17105 uint8 bag = 0; // init for case invalid bagGUID
17107 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17109 if( bagguid == GetGUID() )
17111 bag = INVENTORY_SLOT_BAG_0;
17113 else
17115 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17117 if( Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i) )
17119 if( bagguid == pBag->GetGUID() )
17121 bag = i;
17122 break;
17129 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17131 ItemPosCountVec dest;
17132 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17133 if( msg != EQUIP_ERR_OK )
17135 SendEquipError( msg, NULL, NULL );
17136 return false;
17139 ModifyMoney( -(int32)price );
17140 if(crItem->ExtendedCost) // case for new honor system
17142 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17143 if(iece->reqhonorpoints)
17144 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17145 if(iece->reqarenapoints)
17146 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17147 for (uint8 i = 0; i < 5; ++i)
17149 if(iece->reqitem[i])
17150 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17154 if(Item *it = StoreNewItem( dest, item, true ))
17156 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17158 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17159 data << pCreature->GetGUID();
17160 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17161 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17162 data << (uint32)count;
17163 GetSession()->SendPacket(&data);
17165 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17168 else if( IsEquipmentPos( bag, slot ) )
17170 if(pProto->BuyCount * count != 1)
17172 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17173 return false;
17176 uint16 dest;
17177 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17178 if( msg != EQUIP_ERR_OK )
17180 SendEquipError( msg, NULL, NULL );
17181 return false;
17184 ModifyMoney( -(int32)price );
17185 if(crItem->ExtendedCost) // case for new honor system
17187 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17188 if(iece->reqhonorpoints)
17189 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17190 if(iece->reqarenapoints)
17191 ModifyArenaPoints( - int32(iece->reqarenapoints));
17192 for (uint8 i = 0; i < 5; ++i)
17194 if(iece->reqitem[i])
17195 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17199 if(Item *it = EquipNewItem( dest, item, true ))
17201 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17203 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17204 data << pCreature->GetGUID();
17205 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17206 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17207 data << (uint32)count;
17208 GetSession()->SendPacket(&data);
17210 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17212 AutoUnequipOffhandIfNeed();
17215 else
17217 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17218 return false;
17221 return crItem->maxcount!=0;
17224 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17226 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17227 // the personal rating of the arena team must match the required limit as well
17228 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17229 uint32 max_personal_rating = 0;
17230 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17232 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17234 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17235 uint32 t_rating = at->GetRating();
17236 p_rating = p_rating<t_rating? p_rating : t_rating;
17237 if(max_personal_rating < p_rating)
17238 max_personal_rating = p_rating;
17241 return max_personal_rating;
17244 void Player::UpdateHomebindTime(uint32 time)
17246 // GMs never get homebind timer online
17247 if (m_InstanceValid || isGameMaster())
17249 if(m_HomebindTimer) // instance valid, but timer not reset
17251 // hide reminder
17252 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17253 data << uint32(0);
17254 data << uint32(0);
17255 GetSession()->SendPacket(&data);
17257 // instance is valid, reset homebind timer
17258 m_HomebindTimer = 0;
17260 else if (m_HomebindTimer > 0)
17262 if (time >= m_HomebindTimer)
17264 // teleport to nearest graveyard
17265 RepopAtGraveyard();
17267 else
17268 m_HomebindTimer -= time;
17270 else
17272 // instance is invalid, start homebind timer
17273 m_HomebindTimer = 60000;
17274 // send message to player
17275 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17276 data << m_HomebindTimer;
17277 data << uint32(1);
17278 GetSession()->SendPacket(&data);
17279 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17283 void Player::UpdatePvP(bool state, bool ovrride)
17285 if(!state || ovrride)
17287 SetPvP(state);
17288 pvpInfo.endTimer = 0;
17290 else
17292 if(pvpInfo.endTimer != 0)
17293 pvpInfo.endTimer = time(NULL);
17294 else
17295 SetPvP(state);
17299 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17301 // init cooldown values
17302 uint32 cat = 0;
17303 int32 rec = -1;
17304 int32 catrec = -1;
17306 // some special item spells without correct cooldown in SpellInfo
17307 // cooldown information stored in item prototype
17308 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17310 if(itemId)
17312 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17314 for(int idx = 0; idx < 5; ++idx)
17316 if(proto->Spells[idx].SpellId == spellInfo->Id)
17318 cat = proto->Spells[idx].SpellCategory;
17319 rec = proto->Spells[idx].SpellCooldown;
17320 catrec = proto->Spells[idx].SpellCategoryCooldown;
17321 break;
17327 // if no cooldown found above then base at DBC data
17328 if(rec < 0 && catrec < 0)
17330 cat = spellInfo->Category;
17331 rec = spellInfo->RecoveryTime;
17332 catrec = spellInfo->CategoryRecoveryTime;
17335 time_t curTime = time(NULL);
17337 time_t catrecTime;
17338 time_t recTime;
17340 // overwrite time for selected category
17341 if(infinityCooldown)
17343 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17344 // but not allow ignore until reset or re-login
17345 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17346 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17348 else
17350 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17351 // prevent 0 cooldowns set by another way
17352 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17353 rec = GetAttackTime(RANGED_ATTACK);
17355 // Now we have cooldown data (if found any), time to apply mods
17356 if(rec > 0)
17357 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17359 if(catrec > 0)
17360 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17362 // replace negative cooldowns by 0
17363 if (rec < 0) rec = 0;
17364 if (catrec < 0) catrec = 0;
17366 // no cooldown after applying spell mods
17367 if( rec == 0 && catrec == 0)
17368 return;
17370 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17371 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17374 // self spell cooldown
17375 if(recTime > 0)
17376 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17378 // category spells
17379 if (cat && catrec > 0)
17381 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17382 if(i_scstore != sSpellCategoryStore.end())
17384 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17386 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17387 continue;
17389 AddSpellCooldown(*i_scset, itemId, catrecTime);
17395 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17397 SpellCooldown sc;
17398 sc.end = end_time;
17399 sc.itemid = itemid;
17400 m_spellCooldowns[spellid] = sc;
17403 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17405 // start cooldowns at server side, if any
17406 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17408 // Send activate cooldown timer (possible 0) at client side
17409 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17410 data << spellInfo->Id;
17411 data << GetGUID();
17412 SendDirectMessage(&data);
17415 void Player::UpdatePotionCooldown(Spell* spell)
17417 // no potion used i combat or still in combat
17418 if(!m_lastPotionId || isInCombat())
17419 return;
17421 // Call not from spell cast, send cooldown event for item spells if no in combat
17422 if(!spell)
17424 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17425 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17426 for(int idx = 0; idx < 5; ++idx)
17427 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17428 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17429 SendCooldownEvent(spellInfo,m_lastPotionId);
17431 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17432 else
17433 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17435 m_lastPotionId = 0;
17438 //slot to be excluded while counting
17439 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17441 if(!enchantmentcondition)
17442 return true;
17444 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17446 if(!Condition)
17447 return true;
17449 uint8 curcount[4] = {0, 0, 0, 0};
17451 //counting current equipped gem colors
17452 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17454 if(i == slot)
17455 continue;
17456 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17457 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17459 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17461 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17462 if(!enchant_id)
17463 continue;
17465 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17466 if(!enchantEntry)
17467 continue;
17469 uint32 gemid = enchantEntry->GemID;
17470 if(!gemid)
17471 continue;
17473 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17474 if(!gemProto)
17475 continue;
17477 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17478 if(!gemProperty)
17479 continue;
17481 uint8 GemColor = gemProperty->color;
17483 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17485 if(tmpcolormask & GemColor)
17486 ++curcount[b];
17492 bool activate = true;
17494 for(int i = 0; i < 5; ++i)
17496 if(!Condition->Color[i])
17497 continue;
17499 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17501 // if have <CompareColor> use them as count, else use <value> from Condition
17502 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17504 switch(Condition->Comparator[i])
17506 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17507 activate &= (_cur_gem < _cmp_gem) ? true : false;
17508 break;
17509 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17510 activate &= (_cur_gem > _cmp_gem) ? true : false;
17511 break;
17512 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17513 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17514 break;
17518 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");
17520 return activate;
17523 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17525 //cycle all equipped items
17526 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17528 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17529 if(slot == exceptslot)
17530 continue;
17532 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17534 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17535 continue;
17537 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17539 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17540 if(!enchant_id)
17541 continue;
17543 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17544 if(!enchantEntry)
17545 continue;
17547 uint32 condition = enchantEntry->EnchantmentCondition;
17548 if(condition)
17550 //was enchant active with/without item?
17551 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17552 //should it now be?
17553 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17555 // ignore item gem conditions
17556 //if state changed, (dis)apply enchant
17557 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17564 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17565 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17567 //cycle all equipped items
17568 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17570 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17571 if(slot == exceptslot)
17572 continue;
17574 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17576 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17577 continue;
17579 //cycle all (gem)enchants
17580 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17582 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17583 if(!enchant_id) //if no enchant go to next enchant(slot)
17584 continue;
17586 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17587 if(!enchantEntry)
17588 continue;
17590 //only metagems to be (de)activated, so only enchants with condition
17591 uint32 condition = enchantEntry->EnchantmentCondition;
17592 if(condition)
17593 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17598 void Player::LeaveBattleground(bool teleportToEntryPoint)
17600 if(BattleGround *bg = GetBattleGround())
17602 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17604 // call after remove to be sure that player resurrected for correct cast
17605 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17607 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17608 CastSpell(this, 26013, true); // Deserter
17613 bool Player::CanJoinToBattleground() const
17615 // check Deserter debuff
17616 if(GetDummyAura(26013))
17617 return false;
17619 return true;
17622 bool Player::CanReportAfkDueToLimit()
17624 // a player can complain about 15 people per 5 minutes
17625 if(m_bgAfkReportedCount >= 15)
17626 return false;
17627 ++m_bgAfkReportedCount;
17628 return true;
17631 ///This player has been blamed to be inactive in a battleground
17632 void Player::ReportedAfkBy(Player* reporter)
17634 BattleGround *bg = GetBattleGround();
17635 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17636 return;
17638 // check if player has 'Idle' or 'Inactive' debuff
17639 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17641 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17642 // 3 players have to complain to apply debuff
17643 if(m_bgAfkReporter.size() >= 3)
17645 // cast 'Idle' spell
17646 CastSpell(this, 43680, true);
17647 m_bgAfkReporter.clear();
17652 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17654 // gamemaster in GM mode see all, including ghosts
17655 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17656 return true;
17658 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17659 if (InBattleGround())
17661 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17662 return false;
17663 return true;
17666 // Live player see live player or dead player with not realized corpse
17667 if(pl->isAlive() || pl->m_deathTimer > 0)
17669 return isAlive() || m_deathTimer > 0;
17672 // Ghost see other friendly ghosts, that's for sure
17673 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17674 return true;
17676 // Dead player see live players near own corpse
17677 if(isAlive())
17679 Corpse *corpse = pl->GetCorpse();
17680 if(corpse)
17682 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17683 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17684 return true;
17688 // and not see any other
17689 return false;
17692 bool Player::IsVisibleGloballyFor( Player* u ) const
17694 if(!u)
17695 return false;
17697 // Always can see self
17698 if (u==this)
17699 return true;
17701 // Visible units, always are visible for all players
17702 if (GetVisibility() == VISIBILITY_ON)
17703 return true;
17705 // GMs are visible for higher gms (or players are visible for gms)
17706 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17707 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17709 // non faction visibility non-breakable for non-GMs
17710 if (GetVisibility() == VISIBILITY_OFF)
17711 return false;
17713 // non-gm stealth/invisibility not hide from global player lists
17714 return true;
17717 void Player::UpdateVisibilityOf(WorldObject* target)
17719 if(HaveAtClient(target))
17721 if(!target->isVisibleForInState(this,true))
17723 target->DestroyForPlayer(this);
17724 m_clientGUIDs.erase(target->GetGUID());
17726 #ifdef MANGOS_DEBUG
17727 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17728 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17729 #endif
17732 else
17734 if(target->isVisibleForInState(this,false))
17736 target->SendUpdateToPlayer(this);
17737 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17738 m_clientGUIDs.insert(target->GetGUID());
17740 #ifdef MANGOS_DEBUG
17741 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17742 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17743 #endif
17745 // target aura duration for caster show only if target exist at caster client
17746 // send data at target visibility change (adding to client)
17747 if(target!=this && target->isType(TYPEMASK_UNIT))
17748 SendAurasForTarget((Unit*)target);
17750 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17751 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17756 template<class T>
17757 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17759 s64.insert(target->GetGUID());
17762 template<>
17763 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17765 if(!target->IsTransport())
17766 s64.insert(target->GetGUID());
17769 template<class T>
17770 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17772 if(HaveAtClient(target))
17774 if(!target->isVisibleForInState(this,true))
17776 target->BuildOutOfRangeUpdateBlock(&data);
17777 m_clientGUIDs.erase(target->GetGUID());
17779 #ifdef MANGOS_DEBUG
17780 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17781 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));
17782 #endif
17785 else
17787 if(target->isVisibleForInState(this,false))
17789 visibleNow.insert(target);
17790 target->BuildUpdate(data_updates);
17791 target->BuildCreateUpdateBlockForPlayer(&data, this);
17792 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17794 #ifdef MANGOS_DEBUG
17795 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17796 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));
17797 #endif
17802 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17803 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17804 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17805 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17806 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17808 void Player::InitPrimaryProfessions()
17810 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17813 void Player::SendComboPoints()
17815 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17816 if (combotarget)
17818 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17819 data.append(combotarget->GetPackGUID());
17820 data << uint8(m_comboPoints);
17821 GetSession()->SendPacket(&data);
17825 void Player::AddComboPoints(Unit* target, int8 count)
17827 if(!count)
17828 return;
17830 // without combo points lost (duration checked in aura)
17831 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17833 if(target->GetGUID() == m_comboTarget)
17835 m_comboPoints += count;
17837 else
17839 if(m_comboTarget)
17840 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17841 target2->RemoveComboPointHolder(GetGUIDLow());
17843 m_comboTarget = target->GetGUID();
17844 m_comboPoints = count;
17846 target->AddComboPointHolder(GetGUIDLow());
17849 if (m_comboPoints > 5) m_comboPoints = 5;
17850 if (m_comboPoints < 0) m_comboPoints = 0;
17852 SendComboPoints();
17855 void Player::ClearComboPoints()
17857 if(!m_comboTarget)
17858 return;
17860 // without combopoints lost (duration checked in aura)
17861 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17863 m_comboPoints = 0;
17865 SendComboPoints();
17867 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17868 target->RemoveComboPointHolder(GetGUIDLow());
17870 m_comboTarget = 0;
17873 void Player::SetGroup(Group *group, int8 subgroup)
17875 if(group == NULL)
17876 m_group.unlink();
17877 else
17879 // never use SetGroup without a subgroup unless you specify NULL for group
17880 assert(subgroup >= 0);
17881 m_group.link(group, this);
17882 m_group.setSubGroup((uint8)subgroup);
17886 void Player::SendInitialPacketsBeforeAddToMap()
17888 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17889 data << uint32(0); // unknown, may be rest state time or experience
17890 GetSession()->SendPacket(&data);
17892 GetSocial()->SendSocialList();
17894 // Homebind
17895 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17896 data << m_homebindX << m_homebindY << m_homebindZ;
17897 data << (uint32) m_homebindMapId;
17898 data << (uint32) m_homebindZoneId;
17899 GetSession()->SendPacket(&data);
17901 // SMSG_SET_PROFICIENCY
17902 // SMSG_UPDATE_AURA_DURATION
17904 SendTalentsInfoData(false);
17905 SendInitialSpells();
17907 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17908 data << uint32(0); // count, for(count) uint32;
17909 GetSession()->SendPacket(&data);
17911 SendInitialActionButtons();
17912 m_reputationMgr.SendInitialReputations();
17913 m_achievementMgr.SendAllAchievementData();
17915 // update zone
17916 uint32 newzone, newarea;
17917 GetZoneAndAreaId(newzone,newarea);
17918 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17920 SendEquipmentSetList();
17922 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
17923 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17924 data << (float)0.01666667f; // game speed
17925 data << uint32(0); // added in 3.1.2
17926 GetSession()->SendPacket( &data );
17928 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17929 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17930 m_movementInfo.flags |= MOVEMENTFLAG_FLYING2;
17932 m_mover = this;
17935 void Player::SendInitialPacketsAfterAddToMap()
17937 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17938 data << uint32(0x00000000); // on blizz it increments periodically
17939 GetSession()->SendPacket(&data);
17941 CastSpell(this, 836, true); // LOGINEFFECT
17943 // set some aura effects that send packet to player client after add player to map
17944 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17945 // same auras state lost at far teleport, send it one more time in this case also
17946 static const AuraType auratypes[] =
17948 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17949 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17950 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17952 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17954 Unit::AuraList const& auraList = GetAurasByType(*itr);
17955 if(!auraList.empty())
17956 auraList.front()->ApplyModifier(true,true);
17959 if(HasAuraType(SPELL_AURA_MOD_STUN))
17960 SetMovement(MOVE_ROOT);
17962 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17963 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17965 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17966 data2.append(GetPackGUID());
17967 data2 << (uint32)2;
17968 SendMessageToSet(&data2,true);
17971 SendAurasForTarget(this);
17972 SendEnchantmentDurations(); // must be after add to map
17973 SendItemDurations(); // must be after add to map
17976 void Player::SendUpdateToOutOfRangeGroupMembers()
17978 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17979 return;
17980 if(Group* group = GetGroup())
17981 group->UpdatePlayerOutOfRange(this);
17983 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17984 m_auraUpdateMask = 0;
17985 if(Pet *pet = GetPet())
17986 pet->ResetAuraUpdateMask();
17989 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17991 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17992 data << uint32(mapid);
17993 data << uint8(reason); // transfer abort reason
17994 switch(reason)
17996 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17997 case TRANSFER_ABORT_DIFFICULTY:
17998 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17999 data << uint8(arg);
18000 break;
18002 GetSession()->SendPacket(&data);
18005 void Player::SendInstanceResetWarning( uint32 mapid, uint32 difficulty, uint32 time )
18007 // type of warning, based on the time remaining until reset
18008 uint32 type;
18009 if(time > 3600)
18010 type = RAID_INSTANCE_WELCOME;
18011 else if(time > 900 && time <= 3600)
18012 type = RAID_INSTANCE_WARNING_HOURS;
18013 else if(time > 300 && time <= 900)
18014 type = RAID_INSTANCE_WARNING_MIN;
18015 else
18016 type = RAID_INSTANCE_WARNING_MIN_SOON;
18018 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18019 data << uint32(type);
18020 data << uint32(mapid);
18021 data << uint32(difficulty); // difficulty
18022 data << uint32(time);
18023 if(type == RAID_INSTANCE_WELCOME)
18025 data << uint8(0); // is your (1)
18026 data << uint8(0); // is extended (1), ignored if prev field is 0
18028 GetSession()->SendPacket(&data);
18031 void Player::ApplyEquipCooldown( Item * pItem )
18033 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18035 _Spell const& spellData = pItem->GetProto()->Spells[i];
18037 // no spell
18038 if( !spellData.SpellId )
18039 continue;
18041 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18042 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18043 continue;
18045 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18047 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18048 data << pItem->GetGUID();
18049 data << uint32(spellData.SpellId);
18050 GetSession()->SendPacket(&data);
18054 void Player::resetSpells()
18056 // not need after this call
18057 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18058 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
18060 // make full copy of map (spells removed and marked as deleted at another spell remove
18061 // and we can't use original map for safe iterative with visit each spell at loop end
18062 PlayerSpellMap smap = GetSpellMap();
18064 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18065 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18067 learnDefaultSpells();
18068 learnQuestRewardedSpells();
18071 void Player::learnDefaultSpells()
18073 // learn default race/class spells
18074 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18075 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18077 uint32 tspell = *itr;
18078 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18079 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18080 addSpell(tspell,true,true,true,false);
18081 else // but send in normal spell in game learn case
18082 learnSpell(tspell,true);
18086 void Player::learnQuestRewardedSpells(Quest const* quest)
18088 uint32 spell_id = quest->GetRewSpellCast();
18090 // skip quests without rewarded spell
18091 if( !spell_id )
18092 return;
18094 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18095 if(!spellInfo)
18096 return;
18098 // check learned spells state
18099 bool found = false;
18100 for(int i=0; i < 3; ++i)
18102 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18104 found = true;
18105 break;
18109 // skip quests with not teaching spell or already known spell
18110 if(!found)
18111 return;
18113 // prevent learn non first rank unknown profession and second specialization for same profession)
18114 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18115 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18117 // not have first rank learned (unlearned prof?)
18118 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18119 if( !HasSpell(first_spell) )
18120 return;
18122 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18123 if(!learnedInfo)
18124 return;
18126 // specialization
18127 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18129 // search other specialization for same prof
18130 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18132 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18133 continue;
18135 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18136 if(!itrInfo)
18137 return;
18139 // compare only specializations
18140 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18141 continue;
18143 // compare same chain spells
18144 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18145 continue;
18147 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18148 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18149 return;
18154 CastSpell( this, spell_id, true);
18157 void Player::learnQuestRewardedSpells()
18159 // learn spells received from quest completing
18160 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18162 // skip no rewarded quests
18163 if(!itr->second.m_rewarded)
18164 continue;
18166 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18167 if( !quest )
18168 continue;
18170 learnQuestRewardedSpells(quest);
18174 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18176 uint32 raceMask = getRaceMask();
18177 uint32 classMask = getClassMask();
18178 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18180 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18181 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18182 continue;
18183 // Check race if set
18184 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18185 continue;
18186 // Check class if set
18187 if (pAbility->classmask && !(pAbility->classmask & classMask))
18188 continue;
18190 if (sSpellStore.LookupEntry(pAbility->spellId))
18192 // need unlearn spell
18193 if (skill_value < pAbility->req_skill_value)
18194 removeSpell(pAbility->spellId);
18195 // need learn
18196 else if (!IsInWorld())
18197 addSpell(pAbility->spellId,true,true,true,false);
18198 else
18199 learnSpell(pAbility->spellId,true);
18204 void Player::SendAurasForTarget(Unit *target)
18206 if(target->GetVisibleAuras()->empty()) // speedup things
18207 return;
18209 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18210 data.append(target->GetPackGUID());
18212 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18213 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18215 for(uint32 j = 0; j < 3; ++j)
18217 if(Aura *aura = target->GetAura(itr->second, j))
18219 data << uint8(aura->GetAuraSlot());
18220 data << uint32(aura->GetId());
18222 if(aura->GetId())
18224 uint8 auraFlags = aura->GetAuraFlags();
18225 // flags
18226 data << uint8(auraFlags);
18227 // level
18228 data << uint8(aura->GetAuraLevel());
18229 // charges
18230 data << uint8(aura->GetAuraCharges());
18232 if(!(auraFlags & AFLAG_NOT_CASTER))
18234 data << uint8(0); // packed GUID of someone (caster?)
18237 if(auraFlags & AFLAG_DURATION) // include aura duration
18239 data << uint32(aura->GetAuraMaxDuration());
18240 data << uint32(aura->GetAuraDuration());
18243 break;
18248 GetSession()->SendPacket(&data);
18251 void Player::SetDailyQuestStatus( uint32 quest_id )
18253 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18255 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18257 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18258 m_lastDailyQuestTime = time(NULL); // last daily quest time
18259 m_DailyQuestChanged = true;
18260 break;
18265 void Player::ResetDailyQuestStatus()
18267 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18268 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18270 // DB data deleted in caller
18271 m_DailyQuestChanged = false;
18272 m_lastDailyQuestTime = 0;
18275 BattleGround* Player::GetBattleGround() const
18277 if(GetBattleGroundId()==0)
18278 return NULL;
18280 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18283 bool Player::InArena() const
18285 BattleGround *bg = GetBattleGround();
18286 if(!bg || !bg->isArena())
18287 return false;
18289 return true;
18292 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18294 // get a template bg instead of running one
18295 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18296 if(!bg)
18297 return false;
18299 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18300 return false;
18302 return true;
18305 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18307 //returned to hardcoded version of this function, because there is no way to code it dynamic
18308 uint32 level = getLevel();
18309 if( bgTypeId == BATTLEGROUND_AV )
18310 level--;
18312 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18313 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18315 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18316 return QUEUE_ID_MAX_LEVEL_80;
18318 return BGQueueIdBasedOnLevel(queue_id);
18321 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18323 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18324 if(!vendor_faction || !vendor_faction->faction)
18325 return 1.0f;
18327 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18328 if(rank <= REP_NEUTRAL)
18329 return 1.0f;
18331 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18334 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18336 uint32 racemask = getRaceMask();
18337 uint32 classmask = getClassMask();
18339 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18340 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18341 if(lower==upper)
18342 return true;
18344 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18346 // skip wrong race skills
18347 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18348 continue;
18350 // skip wrong class skills
18351 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18352 continue;
18354 return true;
18357 return false;
18360 bool Player::HasQuestForGO(int32 GOId) const
18362 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18364 uint32 questid = GetQuestSlotQuestId(i);
18365 if ( questid == 0 )
18366 continue;
18368 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18369 if(qs_itr == mQuestStatus.end())
18370 continue;
18372 QuestStatusData const& qs = qs_itr->second;
18374 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18376 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18377 if(!qinfo)
18378 continue;
18380 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18381 continue;
18383 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18385 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18386 continue;
18388 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18389 return true;
18393 return false;
18396 void Player::UpdateForQuestWorldObjects()
18398 if(m_clientGUIDs.empty())
18399 return;
18401 UpdateData udata;
18402 WorldPacket packet;
18403 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18405 if(IS_GAMEOBJECT_GUID(*itr))
18407 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18408 if(obj)
18409 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18411 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18413 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18414 if(!obj)
18415 continue;
18417 // check if this unit requires quest specific flags
18418 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
18419 continue;
18421 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(obj->GetEntry());
18422 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
18424 if(itr->second.questStart || itr->second.questEnd)
18426 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18427 break;
18432 udata.BuildPacket(&packet);
18433 GetSession()->SendPacket(&packet);
18436 void Player::SummonIfPossible(bool agree)
18438 if(!agree)
18440 m_summon_expire = 0;
18441 return;
18444 // expire and auto declined
18445 if(m_summon_expire < time(NULL))
18446 return;
18448 // stop taxi flight at summon
18449 if(isInFlight())
18451 GetMotionMaster()->MovementExpired();
18452 m_taxi.ClearTaxiDestinations();
18455 // drop flag at summon
18456 // 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
18457 if(BattleGround *bg = GetBattleGround())
18458 bg->EventPlayerDroppedFlag(this);
18460 m_summon_expire = 0;
18462 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18464 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18467 void Player::RemoveItemDurations( Item *item )
18469 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18471 if(*itr==item)
18473 m_itemDuration.erase(itr);
18474 break;
18479 void Player::AddItemDurations( Item *item )
18481 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18483 m_itemDuration.push_back(item);
18484 item->SendTimeUpdate(this);
18488 void Player::AutoUnequipOffhandIfNeed()
18490 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18491 if(!offItem)
18492 return;
18494 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18495 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18496 return;
18498 ItemPosCountVec off_dest;
18499 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18500 if( off_msg == EQUIP_ERR_OK )
18502 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18503 StoreItem( off_dest, offItem, true );
18505 else
18507 MailItemsInfo mi;
18508 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18509 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18510 CharacterDatabase.BeginTransaction();
18511 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18512 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18513 CharacterDatabase.CommitTransaction();
18515 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18516 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18520 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18522 if(spellInfo->EquippedItemClass < 0)
18523 return true;
18525 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18526 // for optimize check 2 used cases only
18527 switch(spellInfo->EquippedItemClass)
18529 case ITEM_CLASS_WEAPON:
18531 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18532 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18533 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18534 return true;
18535 break;
18537 case ITEM_CLASS_ARMOR:
18539 // tabard not have dependent spells
18540 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18541 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18542 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18543 return true;
18545 // shields can be equipped to offhand slot
18546 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18547 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18548 return true;
18550 // ranged slot can have some armor subclasses
18551 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18552 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18553 return true;
18555 break;
18557 default:
18558 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18559 break;
18562 return false;
18565 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18567 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18568 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18569 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18570 return true;
18572 // Check no reagent use mask
18573 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18574 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18575 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18576 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18577 return true;
18579 return false;
18582 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18584 AuraMap& auras = GetAuras();
18585 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18587 Aura* aura = itr->second;
18589 // skip passive (passive item dependent spells work in another way) and not self applied auras
18590 SpellEntry const* spellInfo = aura->GetSpellProto();
18591 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18593 ++itr;
18594 continue;
18597 // skip if not item dependent or have alternative item
18598 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18600 ++itr;
18601 continue;
18604 // no alt item, remove aura, restart check
18605 RemoveAurasDueToSpell(aura->GetId());
18606 itr = auras.begin();
18609 // currently casted spells can be dependent from item
18610 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18612 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18613 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18614 InterruptSpell(i);
18618 uint32 Player::GetResurrectionSpellId()
18620 // search priceless resurrection possibilities
18621 uint32 prio = 0;
18622 uint32 spell_id = 0;
18623 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18624 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18626 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18627 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18629 switch((*itr)->GetId())
18631 case 20707: spell_id = 3026; break; // rank 1
18632 case 20762: spell_id = 20758; break; // rank 2
18633 case 20763: spell_id = 20759; break; // rank 3
18634 case 20764: spell_id = 20760; break; // rank 4
18635 case 20765: spell_id = 20761; break; // rank 5
18636 case 27239: spell_id = 27240; break; // rank 6
18637 case 47883: spell_id = 47882; break; // rank 7
18638 default:
18639 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18640 continue;
18643 prio = 3;
18645 // Twisting Nether // prio: 2 (max)
18646 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18648 prio = 2;
18649 spell_id = 23700;
18653 // Reincarnation (passive spell) // prio: 1
18654 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18655 spell_id = 21169;
18657 return spell_id;
18660 // Used in triggers for check "Only to targets that grant experience or honor" req
18661 bool Player::isHonorOrXPTarget(Unit* pVictim)
18663 uint32 v_level = pVictim->getLevel();
18664 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18666 // Victim level less gray level
18667 if(v_level<=k_grey)
18668 return false;
18670 if(pVictim->GetTypeId() == TYPEID_UNIT)
18672 if (((Creature*)pVictim)->isTotem() ||
18673 ((Creature*)pVictim)->isPet() ||
18674 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18675 return false;
18677 return true;
18680 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18682 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18684 // prepare data for near group iteration (PvP and !PvP cases)
18685 uint32 xp = 0;
18686 bool honored_kill = false;
18688 if(Group *pGroup = GetGroup())
18690 uint32 count = 0;
18691 uint32 sum_level = 0;
18692 Player* member_with_max_level = NULL;
18693 Player* not_gray_member_with_max_level = NULL;
18695 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18697 if(member_with_max_level)
18699 /// not get Xp in PvP or no not gray players in group
18700 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18702 /// skip in check PvP case (for speed, not used)
18703 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18704 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18705 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18707 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18709 Player* pGroupGuy = itr->getSource();
18710 if(!pGroupGuy)
18711 continue;
18713 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18714 continue; // member (alive or dead) or his corpse at req. distance
18716 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18717 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18718 honored_kill = true;
18720 // xp and reputation only in !PvP case
18721 if(!PvP)
18723 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18725 // if is in dungeon then all receive full reputation at kill
18726 // rewarded any alive/dead/near_corpse group member
18727 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18729 // XP updated only for alive group member
18730 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18731 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18733 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18735 pGroupGuy->GiveXP(itr_xp, pVictim);
18736 if(Pet* pet = pGroupGuy->GetPet())
18737 pet->GivePetXP(itr_xp/2);
18740 // quest objectives updated only for alive group member or dead but with not released body
18741 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18743 // normal creature (not pet/etc) can be only in !PvP case
18744 if(pVictim->GetTypeId()==TYPEID_UNIT)
18745 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18751 else // if (!pGroup)
18753 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18755 // honor can be in PvP and !PvP (racial leader) cases
18756 if(RewardHonor(pVictim,1))
18757 honored_kill = true;
18759 // xp and reputation only in !PvP case
18760 if(!PvP)
18762 RewardReputation(pVictim,1);
18763 GiveXP(xp, pVictim);
18765 if(Pet* pet = GetPet())
18766 pet->GivePetXP(xp);
18768 // normal creature (not pet/etc) can be only in !PvP case
18769 if(pVictim->GetTypeId()==TYPEID_UNIT)
18770 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18773 return xp || honored_kill;
18776 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18778 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18780 // prepare data for near group iteration
18781 if(Group *pGroup = GetGroup())
18783 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18785 Player* pGroupGuy = itr->getSource();
18786 if(!pGroupGuy)
18787 continue;
18789 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18790 continue; // member (alive or dead) or his corpse at req. distance
18792 // quest objectives updated only for alive group member or dead but with not released body
18793 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18794 pGroupGuy->KilledMonster(creature_id, creature_guid);
18797 else // if (!pGroup)
18798 KilledMonster(creature_id, creature_guid);
18801 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18803 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18804 return true;
18806 if (isAlive())
18807 return false;
18809 Corpse* corpse = GetCorpse();
18810 if (!corpse)
18811 return false;
18813 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18816 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18818 Item* item = GetWeaponForAttack(attType,true);
18820 // unarmed only with base attack
18821 if(attType != BASE_ATTACK && !item)
18822 return 0;
18824 // weapon skill or (unarmed for base attack)
18825 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18826 return GetBaseSkillValue(skill);
18829 void Player::ResurectUsingRequestData()
18831 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
18832 if(IS_PLAYER_GUID(m_resurrectGUID))
18833 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18835 ResurrectPlayer(0.0f,false);
18837 if(GetMaxHealth() > m_resurrectHealth)
18838 SetHealth( m_resurrectHealth );
18839 else
18840 SetHealth( GetMaxHealth() );
18842 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18843 SetPower(POWER_MANA, m_resurrectMana );
18844 else
18845 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18847 SetPower(POWER_RAGE, 0 );
18849 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18851 SpawnCorpseBones();
18854 void Player::SetClientControl(Unit* target, uint8 allowMove)
18856 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18857 data.append(target->GetPackGUID());
18858 data << uint8(allowMove);
18859 GetSession()->SendPacket(&data);
18862 void Player::UpdateZoneDependentAuras( uint32 newZone )
18864 // remove new continent flight forms
18865 if( !IsAllowUseFlyMountsHere() )
18867 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18868 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18871 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18872 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18873 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18874 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18875 if( !HasAura(itr->second->spellId,0) )
18876 CastSpell(this,itr->second->spellId,true);
18879 void Player::UpdateAreaDependentAuras( uint32 newArea )
18881 // remove auras from spells with area limitations
18882 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18884 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18885 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18886 RemoveAura(iter);
18887 else
18888 ++iter;
18891 // some auras applied at subzone enter
18892 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18893 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18894 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18895 if( !HasAura(itr->second->spellId,0) )
18896 CastSpell(this,itr->second->spellId,true);
18899 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18901 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18902 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18904 return copseReclaimDelay[0];
18907 time_t now = time(NULL);
18908 // 0..2 full period
18909 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18910 return copseReclaimDelay[count];
18913 void Player::UpdateCorpseReclaimDelay()
18915 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18917 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18918 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18919 return;
18921 time_t now = time(NULL);
18922 if(now < m_deathExpireTime)
18924 // full and partly periods 1..3
18925 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18926 if(count < MAX_DEATH_COUNT)
18927 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18928 else
18929 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18931 else
18932 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18935 void Player::SendCorpseReclaimDelay(bool load)
18937 Corpse* corpse = GetCorpse();
18938 if(!corpse)
18939 return;
18941 uint32 delay;
18942 if(load)
18944 if(corpse->GetGhostTime() > m_deathExpireTime)
18945 return;
18947 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18949 uint32 count;
18950 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18951 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18953 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18954 if(count>=MAX_DEATH_COUNT)
18955 count = MAX_DEATH_COUNT-1;
18957 else
18958 count=0;
18960 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18962 time_t now = time(NULL);
18963 if(now >= expected_time)
18964 return;
18966 delay = expected_time-now;
18968 else
18969 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18971 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18972 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18973 data << uint32(delay*IN_MILISECONDS);
18974 GetSession()->SendPacket( &data );
18977 Player* Player::GetNextRandomRaidMember(float radius)
18979 Group *pGroup = GetGroup();
18980 if(!pGroup)
18981 return NULL;
18983 std::vector<Player*> nearMembers;
18984 nearMembers.reserve(pGroup->GetMembersCount());
18986 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18988 Player* Target = itr->getSource();
18990 // IsHostileTo check duel and controlled by enemy
18991 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18992 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18993 nearMembers.push_back(Target);
18996 if (nearMembers.empty())
18997 return NULL;
18999 uint32 randTarget = urand(0,nearMembers.size()-1);
19000 return nearMembers[randTarget];
19003 PartyResult Player::CanUninviteFromGroup() const
19005 const Group* grp = GetGroup();
19006 if(!grp)
19007 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19009 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19010 return PARTY_RESULT_YOU_NOT_LEADER;
19012 if(InBattleGround())
19013 return PARTY_RESULT_INVITE_RESTRICTED;
19015 return PARTY_RESULT_OK;
19018 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19020 //we must move references from m_group to m_originalGroup
19021 SetOriginalGroup(GetGroup(), GetSubGroup());
19023 m_group.unlink();
19024 m_group.link(group, this);
19025 m_group.setSubGroup((uint8)subgroup);
19028 void Player::RemoveFromBattleGroundRaid()
19030 //remove existing reference
19031 m_group.unlink();
19032 if( Group* group = GetOriginalGroup() )
19034 m_group.link(group, this);
19035 m_group.setSubGroup(GetOriginalSubGroup());
19037 SetOriginalGroup(NULL);
19040 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19042 if( group == NULL )
19043 m_originalGroup.unlink();
19044 else
19046 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19047 assert(subgroup >= 0);
19048 m_originalGroup.link(group, this);
19049 m_originalGroup.setSubGroup((uint8)subgroup);
19053 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19055 LiquidData liquid_status;
19056 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19057 if (!res)
19059 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19060 // Small hack for enable breath in WMO
19061 if (IsInWater())
19062 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19063 return;
19066 // All liquids type - check under water position
19067 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19069 if ( res & LIQUID_MAP_UNDER_WATER)
19070 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19071 else
19072 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19075 // Allow travel in dark water on taxi or transport
19076 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19077 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19078 else
19079 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19081 // in lava check, anywhere in lava level
19082 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19084 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19085 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19086 else
19087 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19089 // in slime check, anywhere in slime level
19090 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19092 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19093 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19094 else
19095 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19099 void Player::SetCanParry( bool value )
19101 if(m_canParry==value)
19102 return;
19104 m_canParry = value;
19105 UpdateParryPercentage();
19108 void Player::SetCanBlock( bool value )
19110 if(m_canBlock==value)
19111 return;
19113 m_canBlock = value;
19114 UpdateBlockPercentage();
19117 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19119 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19120 if(itr->pos == pos)
19121 return true;
19123 return false;
19126 bool Player::CanUseBattleGroundObject()
19128 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19129 // maybe gameobject code should handle that ForceReaction usage
19130 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19131 return ( //InBattleGround() && // in battleground - not need, check in other cases
19132 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19133 //player cannot use object when he is invulnerable (immune)
19134 !isTotalImmune() && // not totally immune
19135 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19136 !HasStealthAura() && // not stealthed
19137 !HasInvisibilityAura() && // not invisible
19138 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19139 isAlive() // live player
19143 bool Player::CanCaptureTowerPoint()
19145 return ( !HasStealthAura() && // not stealthed
19146 !HasInvisibilityAura() && // not invisible
19147 isAlive() // live player
19151 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19153 uint32 level = getLevel();
19155 if(level > GT_MAX_LEVEL)
19156 level = GT_MAX_LEVEL; // max level in this dbc
19158 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19159 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19160 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19162 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19163 return 0;
19165 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19167 if(!bsc) // shouldn't happen
19168 return 0xFFFFFFFF;
19170 float cost = 0;
19172 if(hairstyle != newhairstyle)
19173 cost += bsc->cost; // full price
19175 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19176 cost += bsc->cost * 0.5f; // +1/2 of price
19178 if(facialhair != newfacialhair)
19179 cost += bsc->cost * 0.75f; // +3/4 of price
19181 return uint32(cost);
19184 void Player::InitGlyphsForLevel()
19186 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19187 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19188 if(gs->Order)
19189 SetGlyphSlot(gs->Order - 1, gs->Id);
19191 uint32 level = getLevel();
19192 uint32 value = 0;
19194 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19195 if(level >= 15)
19196 value |= (0x01 | 0x02);
19197 if(level >= 30)
19198 value |= 0x08;
19199 if(level >= 50)
19200 value |= 0x04;
19201 if(level >= 70)
19202 value |= 0x10;
19203 if(level >= 80)
19204 value |= 0x20;
19206 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19209 void Player::EnterVehicle(Vehicle *vehicle)
19211 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19212 if(!ve)
19213 return;
19215 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19216 if(!veSeat)
19217 return;
19219 vehicle->SetCharmerGUID(GetGUID());
19220 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19221 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19222 vehicle->setFaction(getFaction());
19224 SetCharm(vehicle); // charm
19225 SetFarSightGUID(vehicle->GetGUID()); // set view
19227 SetClientControl(vehicle, 1); // redirect controls to vehicle
19229 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19230 GetSession()->SendPacket(&data);
19232 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19233 data.append(GetPackGUID());
19234 data << uint32(0); // counter?
19235 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19236 data << uint16(0); // special flags
19237 data << uint32(getMSTime()); // time
19238 data << vehicle->GetPositionX(); // x
19239 data << vehicle->GetPositionY(); // y
19240 data << vehicle->GetPositionZ(); // z
19241 data << vehicle->GetOrientation(); // o
19242 // transport part, TODO: load/calculate seat offsets
19243 data << uint64(vehicle->GetGUID()); // transport guid
19244 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19245 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19246 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19247 data << float(0); // transport orientation
19248 data << uint32(getMSTime()); // transport time
19249 data << uint8(0); // seat
19250 // end of transport part
19251 data << uint32(0); // fall time
19252 GetSession()->SendPacket(&data);
19254 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19255 data << uint64(vehicle->GetGUID());
19256 data << uint16(0);
19257 data << uint32(0);
19258 data << uint32(0x00000101);
19260 for(uint32 i = 0; i < 10; ++i)
19261 data << uint16(0) << uint8(0) << uint8(i+8);
19263 data << uint8(0);
19264 data << uint8(0);
19265 GetSession()->SendPacket(&data);
19268 void Player::ExitVehicle(Vehicle *vehicle)
19270 vehicle->SetCharmerGUID(0);
19271 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19272 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19273 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19275 SetCharm(NULL);
19276 SetFarSightGUID(0);
19278 SetClientControl(vehicle, 0);
19280 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19281 data.append(GetPackGUID());
19282 data << uint32(0); // counter?
19283 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19284 data << uint16(0x40); // special flags
19285 data << uint32(getMSTime()); // time
19286 data << vehicle->GetPositionX(); // x
19287 data << vehicle->GetPositionY(); // y
19288 data << vehicle->GetPositionZ(); // z
19289 data << vehicle->GetOrientation(); // o
19290 data << uint32(0); // fall time
19291 GetSession()->SendPacket(&data);
19293 data.Initialize(SMSG_PET_SPELLS, 8);
19294 data << uint64(0);
19295 GetSession()->SendPacket(&data);
19297 // maybe called at dummy aura remove?
19298 // CastSpell(this, 45472, true); // Parachute
19301 bool Player::isTotalImmune()
19303 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19305 uint32 immuneMask = 0;
19306 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19308 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19309 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19310 return true;
19312 return false;
19315 bool Player::HasTitle(uint32 bitIndex)
19317 if (bitIndex > 192)
19318 return false;
19320 uint32 fieldIndexOffset = bitIndex / 32;
19321 uint32 flag = 1 << (bitIndex % 32);
19322 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19325 void Player::SetTitle(CharTitlesEntry const* title)
19327 uint32 fieldIndexOffset = title->bit_index / 32;
19328 uint32 flag = 1 << (title->bit_index % 32);
19329 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19332 void Player::ConvertRune(uint8 index, uint8 newType)
19334 SetCurrentRune(index, newType);
19336 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19337 data << uint8(index);
19338 data << uint8(newType);
19339 GetSession()->SendPacket(&data);
19342 void Player::ResyncRunes(uint8 count)
19344 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19345 for(uint32 i = 0; i < count; ++i)
19347 data << uint8(GetCurrentRune(i)); // rune type
19348 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19350 GetSession()->SendPacket(&data);
19353 void Player::AddRunePower(uint8 index)
19355 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19356 data << uint32(1 << index); // mask (0x00-0x3F probably)
19357 GetSession()->SendPacket(&data);
19360 void Player::InitRunes()
19362 if(getClass() != CLASS_DEATH_KNIGHT)
19363 return;
19365 m_runes = new Runes;
19367 m_runes->runeState = 0;
19369 for(uint32 i = 0; i < MAX_RUNES; ++i)
19371 SetBaseRune(i, i / 2); // init base types
19372 SetCurrentRune(i, i / 2); // init current types
19373 SetRuneCooldown(i, 0); // reset cooldowns
19374 m_runes->SetRuneState(i);
19377 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19378 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19381 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19383 Loot loot;
19384 loot.FillLoot (loot_id,store,this,true);
19386 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19387 for(uint32 i = 0; i < max_slot; ++i)
19389 LootItem* lootItem = loot.LootItemInSlot(i,this);
19391 ItemPosCountVec dest;
19392 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19393 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19394 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19395 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19396 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19397 if(msg != EQUIP_ERR_OK)
19399 SendEquipError( msg, NULL, NULL );
19400 continue;
19403 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19404 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19408 uint32 Player::CalculateTalentsPoints() const
19410 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19412 if(getClass() != CLASS_DEATH_KNIGHT)
19413 return base_talent;
19415 uint32 talentPointsForLevel =
19416 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19417 + m_questRewardTalentCount;
19419 if(talentPointsForLevel > base_talent)
19420 talentPointsForLevel = base_talent;
19422 return talentPointsForLevel;
19425 bool Player::IsAllowUseFlyMountsHere() const
19427 if (isGameMaster())
19428 return true;
19430 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19431 return v_map == 530 || v_map == 571 && HasSpell(54197);
19434 void Player::learnSpellHighRank(uint32 spellid)
19436 learnSpell(spellid,false);
19438 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19439 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19440 learnSpellHighRank(itr->second);
19443 void Player::_LoadSkills()
19445 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19447 // reset skill modifiers and set correct unlearn flags
19448 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19450 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19452 // set correct unlearn bit
19453 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19454 if(!id) continue;
19456 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19457 if(!pSkill) continue;
19459 // enable unlearn button for primary professions only
19460 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19461 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19462 else
19463 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19465 // set fixed skill ranges
19466 switch(GetSkillRangeType(pSkill,false))
19468 case SKILL_RANGE_LANGUAGE: // 300..300
19469 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19470 break;
19471 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19472 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19473 break;
19474 default:
19475 break;
19478 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19479 learnSkillRewardedSpells(id, vskill);
19482 // special settings
19483 if(getClass()==CLASS_DEATH_KNIGHT)
19485 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19486 if(base_level < 1)
19487 base_level = 1;
19488 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19489 if(base_skill < 1)
19490 base_skill = 1; // skill mast be known and then > 0 in any case
19492 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19493 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19494 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19495 SetSkill(SKILL_AXES, base_skill,base_skill);
19496 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19497 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19498 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19499 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19500 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19501 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19502 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19503 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19504 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19505 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19506 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19507 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19511 uint32 Player::GetPhaseMaskForSpawn() const
19513 uint32 phase = PHASEMASK_NORMAL;
19514 if(!isGameMaster())
19515 phase = GetPhaseMask();
19516 else
19518 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19519 if(!phases.empty())
19520 phase = phases.front()->GetMiscValue();
19523 // some aura phases include 1 normal map in addition to phase itself
19524 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19525 return n_phase;
19527 return PHASEMASK_NORMAL;
19530 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19532 ItemPrototype const* pProto = pItem->GetProto();
19534 // proto based limitations
19535 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19536 return res;
19538 // check unique-equipped on gems
19539 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19541 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19542 if(!enchant_id)
19543 continue;
19544 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19545 if(!enchantEntry)
19546 continue;
19548 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19549 if(!pGem)
19550 continue;
19552 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19553 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19554 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19556 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19557 return res;
19560 return EQUIP_ERR_OK;
19563 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19565 // check unique-equipped on item
19566 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19568 // there is an equip limit on this item
19569 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19570 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19573 // check unique-equipped limit
19574 if (itemProto->ItemLimitCategory)
19576 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19577 if(!limitEntry)
19578 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19580 if(limit_count > limitEntry->maxCount)
19581 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19583 // there is an equip limit on this item
19584 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19585 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19588 return EQUIP_ERR_OK;
19591 void Player::HandleFall(MovementInfo const& movementInfo)
19593 // calculate total z distance of the fall
19594 float z_diff = m_lastFallZ - movementInfo.z;
19595 sLog.outDebug("zDiff = %f", z_diff);
19597 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19598 // 14.57 can be calculated by resolving damageperc formula below to 0
19599 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19600 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19601 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19603 //Safe fall, fall height reduction
19604 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19606 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19608 if(damageperc >0 )
19610 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19612 float height = movementInfo.z;
19613 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19615 if (damage > 0)
19617 //Prevent fall damage from being more than the player maximum health
19618 if (damage > GetMaxHealth())
19619 damage = GetMaxHealth();
19621 // Gust of Wind
19622 if (GetDummyAura(43621))
19623 damage = GetMaxHealth()/2;
19625 EnvironmentalDamage(DAMAGE_FALL, damage);
19627 // recheck alive, might have died of EnvironmentalDamage
19628 if (isAlive())
19629 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19632 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19633 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);
19638 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19640 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19643 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19645 uint32 CurTalentPoints = GetFreeTalentPoints();
19647 if(CurTalentPoints == 0)
19648 return;
19650 if (talentRank >= MAX_TALENT_RANK)
19651 return;
19653 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19655 if(!talentInfo)
19656 return;
19658 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19660 if(!talentTabInfo)
19661 return;
19663 // prevent learn talent for different class (cheating)
19664 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19665 return;
19667 // find current max talent rank
19668 int32 curtalent_maxrank = 0;
19669 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19671 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19673 curtalent_maxrank = k + 1;
19674 break;
19678 // we already have same or higher talent rank learned
19679 if(curtalent_maxrank >= (talentRank + 1))
19680 return;
19682 // check if we have enough talent points
19683 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19684 return;
19686 // Check if it requires another talent
19687 if (talentInfo->DependsOn > 0)
19689 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19691 bool hasEnoughRank = false;
19692 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19694 if (depTalentInfo->RankID[i] != 0)
19695 if (HasSpell(depTalentInfo->RankID[i]))
19696 hasEnoughRank = true;
19698 if (!hasEnoughRank)
19699 return;
19703 // Find out how many points we have in this field
19704 uint32 spentPoints = 0;
19706 uint32 tTab = talentInfo->TalentTab;
19707 if (talentInfo->Row > 0)
19709 unsigned int numRows = sTalentStore.GetNumRows();
19710 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19712 // Someday, someone needs to revamp
19713 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19714 if (tmpTalent) // the way talents are tracked
19716 if (tmpTalent->TalentTab == tTab)
19718 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19720 if (tmpTalent->RankID[j] != 0)
19722 if (HasSpell(tmpTalent->RankID[j]))
19724 spentPoints += j + 1;
19733 // not have required min points spent in talent tree
19734 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19735 return;
19737 // spell not set in talent.dbc
19738 uint32 spellid = talentInfo->RankID[talentRank];
19739 if( spellid == 0 )
19741 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19742 return;
19745 // already known
19746 if(HasSpell(spellid))
19747 return;
19749 // learn! (other talent ranks will unlearned at learning)
19750 learnSpell(spellid, false);
19751 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19753 // update free talent points
19754 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19757 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19759 Pet *pet = GetPet();
19761 if(!pet)
19762 return;
19764 if(petGuid != pet->GetGUID())
19765 return;
19767 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19769 if(CurTalentPoints == 0)
19770 return;
19772 if (talentRank >= MAX_PET_TALENT_RANK)
19773 return;
19775 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19777 if(!talentInfo)
19778 return;
19780 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19782 if(!talentTabInfo)
19783 return;
19785 CreatureInfo const *ci = pet->GetCreatureInfo();
19787 if(!ci)
19788 return;
19790 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19792 if(!pet_family)
19793 return;
19795 if(pet_family->petTalentType < 0) // not hunter pet
19796 return;
19798 // prevent learn talent for different family (cheating)
19799 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19800 return;
19802 // find current max talent rank
19803 int32 curtalent_maxrank = 0;
19804 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19806 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19808 curtalent_maxrank = k + 1;
19809 break;
19813 // we already have same or higher talent rank learned
19814 if(curtalent_maxrank >= (talentRank + 1))
19815 return;
19817 // check if we have enough talent points
19818 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19819 return;
19821 // Check if it requires another talent
19822 if (talentInfo->DependsOn > 0)
19824 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19826 bool hasEnoughRank = false;
19827 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19829 if (depTalentInfo->RankID[i] != 0)
19830 if (pet->HasSpell(depTalentInfo->RankID[i]))
19831 hasEnoughRank = true;
19833 if (!hasEnoughRank)
19834 return;
19838 // Find out how many points we have in this field
19839 uint32 spentPoints = 0;
19841 uint32 tTab = talentInfo->TalentTab;
19842 if (talentInfo->Row > 0)
19844 unsigned int numRows = sTalentStore.GetNumRows();
19845 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19847 // Someday, someone needs to revamp
19848 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19849 if (tmpTalent) // the way talents are tracked
19851 if (tmpTalent->TalentTab == tTab)
19853 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19855 if (tmpTalent->RankID[j] != 0)
19857 if (pet->HasSpell(tmpTalent->RankID[j]))
19859 spentPoints += j + 1;
19868 // not have required min points spent in talent tree
19869 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19870 return;
19872 // spell not set in talent.dbc
19873 uint32 spellid = talentInfo->RankID[talentRank];
19874 if( spellid == 0 )
19876 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19877 return;
19880 // already known
19881 if(pet->HasSpell(spellid))
19882 return;
19884 // learn! (other talent ranks will unlearned at learning)
19885 pet->learnSpell(spellid);
19886 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19888 // update free talent points
19889 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19892 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19894 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19896 if(apply)
19897 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19898 else
19899 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19903 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19905 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19906 SetFallInformation(minfo.fallTime, minfo.z);
19909 void Player::UnsummonPetTemporaryIfAny()
19911 Pet* pet = GetPet();
19912 if(!pet)
19913 return;
19915 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19917 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19918 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19921 RemovePet(pet, PET_SAVE_AS_CURRENT);
19924 void Player::ResummonPetTemporaryUnSummonedIfAny()
19926 if(!m_temporaryUnsummonedPetNumber)
19927 return;
19929 // not resummon in not appropriate state
19930 if(IsPetNeedBeTemporaryUnsummoned())
19931 return;
19933 if(GetPetGUID())
19934 return;
19936 Pet* NewPet = new Pet;
19937 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19938 delete NewPet;
19940 m_temporaryUnsummonedPetNumber = 0;
19943 bool Player::canSeeSpellClickOn(Creature const *c) const
19945 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19946 return false;
19948 SpellClickInfoMapBounds clickPair = objmgr.GetSpellClickInfoMapBounds(c->GetEntry());
19949 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
19950 if(itr->second.IsFitToRequirements(this))
19951 return true;
19953 return false;
19956 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
19958 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
19959 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
19960 *data << uint8(m_activeSpec); // talent group index (0 or 1)
19962 if(m_specsCount)
19964 // loop through all specs (only 1 for now)
19965 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
19967 uint8 talentIdCount = 0;
19968 size_t pos = data->wpos();
19969 *data << uint8(talentIdCount); // [PH], talentIdCount
19971 // find class talent tabs (all players have 3 talent tabs)
19972 uint32 const* talentTabIds = GetTalentTabPages(getClass());
19974 for(uint32 i = 0; i < 3; ++i)
19976 uint32 talentTabId = talentTabIds[i];
19978 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19980 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19981 if(!talentInfo)
19982 continue;
19984 // skip another tab talents
19985 if(talentInfo->TalentTab != talentTabId)
19986 continue;
19988 // find max talent rank
19989 int32 curtalent_maxrank = -1;
19990 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19992 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19994 curtalent_maxrank = k;
19995 break;
19999 // not learned talent
20000 if(curtalent_maxrank < 0)
20001 continue;
20003 *data << uint32(talentInfo->TalentID); // Talent.dbc
20004 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20006 ++talentIdCount;
20010 data->put<uint8>(pos, talentIdCount); // put real count
20012 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
20014 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
20015 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
20020 void Player::BuildPetTalentsInfoData(WorldPacket *data)
20022 uint32 unspentTalentPoints = 0;
20023 size_t pointsPos = data->wpos();
20024 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
20026 uint8 talentIdCount = 0;
20027 size_t countPos = data->wpos();
20028 *data << uint8(talentIdCount); // [PH], talentIdCount
20030 Pet *pet = GetPet();
20031 if(!pet)
20032 return;
20034 unspentTalentPoints = pet->GetFreeTalentPoints();
20036 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
20038 CreatureInfo const *ci = pet->GetCreatureInfo();
20039 if(!ci)
20040 return;
20042 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20043 if(!pet_family || pet_family->petTalentType < 0)
20044 return;
20046 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
20048 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
20049 if(!talentTabInfo)
20050 continue;
20052 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20053 continue;
20055 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20057 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20058 if(!talentInfo)
20059 continue;
20061 // skip another tab talents
20062 if(talentInfo->TalentTab != talentTabId)
20063 continue;
20065 // find max talent rank
20066 int32 curtalent_maxrank = -1;
20067 for(int32 k = 4; k > -1; --k)
20069 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20071 curtalent_maxrank = k;
20072 break;
20076 // not learned talent
20077 if(curtalent_maxrank < 0)
20078 continue;
20080 *data << uint32(talentInfo->TalentID); // Talent.dbc
20081 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
20083 ++talentIdCount;
20086 data->put<uint8>(countPos, talentIdCount); // put real count
20088 break;
20092 void Player::SendTalentsInfoData(bool pet)
20094 WorldPacket data(SMSG_TALENTS_INFO, 50);
20095 data << uint8(pet ? 1 : 0);
20096 if(pet)
20097 BuildPetTalentsInfoData(&data);
20098 else
20099 BuildPlayerTalentsInfoData(&data);
20100 GetSession()->SendPacket(&data);
20103 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20105 uint32 slotUsedMask = 0;
20106 size_t slotUsedMaskPos = data->wpos();
20107 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20109 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20111 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20113 if(!item)
20114 continue;
20116 slotUsedMask |= (1 << i);
20118 *data << uint32(item->GetEntry()); // item entry
20120 uint16 enchantmentMask = 0;
20121 size_t enchantmentMaskPos = data->wpos();
20122 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20124 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20126 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20128 if(!enchId)
20129 continue;
20131 enchantmentMask |= (1 << j);
20133 *data << uint16(enchId); // enchantmentId?
20136 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20138 *data << uint16(0); // ?
20139 *data << uint8(0); // PGUID!
20140 *data << uint32(0); // seed?
20143 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20146 void Player::SendEquipmentSetList()
20148 uint32 count = 0;
20149 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20150 size_t count_pos = data.wpos();
20151 data << uint32(count); // count placeholder
20152 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20154 if(itr->second.state==EQUIPMENT_SET_DELETED)
20155 continue;
20156 data.appendPackGUID(itr->second.Guid);
20157 data << uint32(itr->first);
20158 data << itr->second.Name;
20159 data << itr->second.IconName;
20160 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20161 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20163 ++count; // client have limit but it checked at loading and set
20165 data.put<uint32>(count_pos, count);
20166 GetSession()->SendPacket(&data);
20169 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20171 if(eqset.Guid != 0)
20173 bool found = false;
20175 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20177 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20179 found = true;
20180 break;
20184 if(!found) // something wrong...
20186 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20187 return;
20191 EquipmentSet& eqslot = m_EquipmentSets[index];
20193 EquipmentSetUpdateState old_state = eqslot.state;
20195 eqslot = eqset;
20197 if(eqset.Guid == 0)
20199 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20201 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20202 data << uint32(index);
20203 data.appendPackGUID(eqslot.Guid);
20204 GetSession()->SendPacket(&data);
20207 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20210 void Player::_SaveEquipmentSets()
20212 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20214 uint32 index = itr->first;
20215 EquipmentSet& eqset = itr->second;
20216 switch(eqset.state)
20218 case EQUIPMENT_SET_UNCHANGED:
20219 ++itr;
20220 break; // nothing do
20221 case EQUIPMENT_SET_CHANGED:
20222 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
20223 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20224 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
20225 eqset.state = EQUIPMENT_SET_UNCHANGED;
20226 ++itr;
20227 break;
20228 case EQUIPMENT_SET_NEW:
20229 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20230 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
20231 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
20232 eqset.state = EQUIPMENT_SET_UNCHANGED;
20233 ++itr;
20234 break;
20235 case EQUIPMENT_SET_DELETED:
20236 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
20237 m_EquipmentSets.erase(itr++);
20238 break;
20243 void Player::DeleteEquipmentSet(uint64 setGuid)
20245 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20247 if(itr->second.Guid == setGuid)
20249 if(itr->second.state == EQUIPMENT_SET_NEW)
20250 m_EquipmentSets.erase(itr);
20251 else
20252 itr->second.state = EQUIPMENT_SET_DELETED;
20253 break;
20258 void Player::ActivateSpec(uint32 specNum)
20260 if(GetActiveSpec() == specNum)
20261 return;
20263 resetTalents(true);
20266 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
20268 m_atLoginFlags &= ~f;
20270 if(in_db_also)
20271 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
20274 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
20276 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
20277 data << uint32(spell_id);
20278 data << uint64(target->GetGUID());
20279 SendDirectMessage(&data);