Fixed SMSG_PET_SPELLS opcode.
[AHbot.git] / src / game / Player.cpp
blobf74cf85f35482805cfda4bf7da56731b490feab3
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "Util.h"
51 #include "Transports.h"
52 #include "Weather.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
56 #include "Chat.h"
57 #include "Database/DatabaseImpl.h"
58 #include "Spell.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
80 CHARACTER_FLAG_NONE = 0x00000000,
81 CHARACTER_FLAG_UNK1 = 0x00000001,
82 CHARACTER_FLAG_UNK2 = 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
84 CHARACTER_FLAG_UNK4 = 0x00000008,
85 CHARACTER_FLAG_UNK5 = 0x00000010,
86 CHARACTER_FLAG_UNK6 = 0x00000020,
87 CHARACTER_FLAG_UNK7 = 0x00000040,
88 CHARACTER_FLAG_UNK8 = 0x00000080,
89 CHARACTER_FLAG_UNK9 = 0x00000100,
90 CHARACTER_FLAG_UNK10 = 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
93 CHARACTER_FLAG_UNK13 = 0x00001000,
94 CHARACTER_FLAG_GHOST = 0x00002000,
95 CHARACTER_FLAG_RENAME = 0x00004000,
96 CHARACTER_FLAG_UNK16 = 0x00008000,
97 CHARACTER_FLAG_UNK17 = 0x00010000,
98 CHARACTER_FLAG_UNK18 = 0x00020000,
99 CHARACTER_FLAG_UNK19 = 0x00040000,
100 CHARACTER_FLAG_UNK20 = 0x00080000,
101 CHARACTER_FLAG_UNK21 = 0x00100000,
102 CHARACTER_FLAG_UNK22 = 0x00200000,
103 CHARACTER_FLAG_UNK23 = 0x00400000,
104 CHARACTER_FLAG_UNK24 = 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
106 CHARACTER_FLAG_DECLINED = 0x02000000,
107 CHARACTER_FLAG_UNK27 = 0x04000000,
108 CHARACTER_FLAG_UNK28 = 0x08000000,
109 CHARACTER_FLAG_UNK29 = 0x10000000,
110 CHARACTER_FLAG_UNK30 = 0x20000000,
111 CHARACTER_FLAG_UNK31 = 0x40000000,
112 CHARACTER_FLAG_UNK32 = 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
131 // class specific initial known nodes
132 switch(chrClass)
134 case CLASS_DEATH_KNIGHT:
136 for(int i = 0; i < TaxiMaskSize; ++i)
137 m_taximask[i] |= sOldContinentsNodesMask[i];
138 break;
142 // race specific initial known nodes: capital and taxi hub masks
143 switch(race)
145 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
146 case RACE_ORC: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race))
161 case ALLIANCE: SetTaximaskNode(100); break;
162 case HORDE: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
165 if(level>=68)
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data)
171 Tokens tokens = StrSplit(data, " ");
173 int index;
174 Tokens::iterator iter;
175 for (iter = tokens.begin(), index = 0;
176 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
178 // load and set bits only for existed taxi nodes
179 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
185 if(all)
187 for (uint8 i=0; i<TaxiMaskSize; ++i)
188 data << uint32(sTaxiNodesMask[i]); // all existed nodes
190 else
192 for (uint8 i=0; i<TaxiMaskSize; ++i)
193 data << uint32(m_taximask[i]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
199 ClearTaxiDestinations();
201 Tokens tokens = StrSplit(values," ");
203 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
205 uint32 node = uint32(atol(iter->c_str()));
206 AddTaxiDestination(node);
209 if(m_TaxiDestinations.empty())
210 return true;
212 // Check integrity
213 if(m_TaxiDestinations.size() < 2)
214 return false;
216 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
218 uint32 cost;
219 uint32 path;
220 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
221 if(!path)
222 return false;
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr.GetTaxiMount(GetTaxiSource(),team))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 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 for (int i = 0; i < BASEMOD_END; ++i)
427 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
428 m_auraBaseMod[i][PCT_MOD] = 1.0f;
431 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
432 m_baseRatingValue[i] = 0;
434 m_baseSpellDamage = 0;
435 m_baseSpellHealing = 0;
436 m_baseFeralAP = 0;
437 m_baseManaRegen = 0;
439 // Honor System
440 m_lastHonorUpdateTime = time(NULL);
442 // Player summoning
443 m_summon_expire = 0;
444 m_summon_mapid = 0;
445 m_summon_x = 0.0f;
446 m_summon_y = 0.0f;
447 m_summon_z = 0.0f;
449 //Default movement to run mode
450 m_unit_movement_flags = 0;
452 m_mover = this;
454 m_miniPet = 0;
455 m_bgAfkReportedTimer = 0;
456 m_contestedPvPTimer = 0;
458 m_declinedname = NULL;
459 m_runes = NULL;
461 m_lastFallTime = 0;
462 m_lastFallZ = 0;
465 Player::~Player ()
467 CleanupsBeforeDelete();
469 // it must be unloaded already in PlayerLogout and accessed only for loggined player
470 //m_social = NULL;
472 // Note: buy back item already deleted from DB when player was saved
473 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
475 if(m_items[i])
476 delete m_items[i];
478 CleanupChannels();
480 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
481 delete itr->second;
483 //all mailed items should be deleted, also all mail should be deallocated
484 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
485 delete *itr;
487 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
488 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
490 delete PlayerTalkClass;
492 if (m_transport)
494 m_transport->RemovePassenger(this);
497 for(size_t x = 0; x < ItemSetEff.size(); x++)
498 if(ItemSetEff[x])
499 delete ItemSetEff[x];
501 // clean up player-instance binds, may unload some instance saves
502 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
503 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
504 itr->second.save->RemovePlayer(this);
506 delete m_declinedname;
507 delete m_runes;
510 void Player::CleanupsBeforeDelete()
512 if(m_uint32Values) // only for fully created Object
514 TradeCancel(false);
515 DuelComplete(DUEL_INTERUPTED);
517 Unit::CleanupsBeforeDelete();
520 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 )
522 //FIXME: outfitId not used in player creating
524 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
526 m_name = name;
528 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
529 if(!info)
531 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
532 return false;
535 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
536 m_items[i] = NULL;
538 m_race = race;
539 m_class = class_;
541 SetMapId(info->mapId);
542 Relocate(info->positionX,info->positionY,info->positionZ);
544 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
545 if(!cEntry)
547 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
548 return false;
551 uint8 powertype = cEntry->powerType;
553 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
554 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
556 switch(gender)
558 case GENDER_FEMALE:
559 SetDisplayId(info->displayId_f );
560 SetNativeDisplayId(info->displayId_f );
561 break;
562 case GENDER_MALE:
563 SetDisplayId(info->displayId_m );
564 SetNativeDisplayId(info->displayId_m );
565 break;
566 default:
567 sLog.outError("Invalid gender %u for player",gender);
568 return false;
569 break;
572 setFactionForRace(m_race);
574 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
576 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
577 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
578 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
579 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
580 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
581 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
583 // -1 is default value
584 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
586 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
587 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
588 SetByteValue(PLAYER_BYTES_3, 0, gender);
590 SetUInt32Value( PLAYER_GUILDID, 0 );
591 SetUInt32Value( PLAYER_GUILDRANK, 0 );
592 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
594 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
595 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
596 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
597 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
598 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
599 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
600 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
602 // set starting level
603 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
604 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
605 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
607 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
609 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
610 if(gm_level > start_level)
611 start_level = gm_level;
614 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
616 InitRunes();
618 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
619 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
620 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
622 // Played time
623 m_Last_tick = time(NULL);
624 m_Played_time[0] = 0;
625 m_Played_time[1] = 0;
627 // base stats and related field values
628 InitStatsForLevel();
629 InitTaxiNodesForLevel();
630 InitGlyphsForLevel();
631 InitTalentForLevel();
632 InitPrimaryProffesions(); // to max set before any spell added
634 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
635 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
636 SetHealth(GetMaxHealth());
637 if (getPowerType()==POWER_MANA)
639 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
640 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
643 if(getPowerType() == POWER_RUNIC_POWER)
645 SetPower(POWER_RUNE, 8);
646 SetMaxPower(POWER_RUNE, 8);
647 SetPower(POWER_RUNIC_POWER, 0);
648 SetMaxPower(POWER_RUNIC_POWER, 1000);
651 // original spells
652 learnDefaultSpells();
654 // original action bar
655 std::list<uint16>::const_iterator action_itr[4];
656 for(int i=0; i<4; ++i)
657 action_itr[i] = info->action[i].begin();
659 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
661 uint16 taction[4];
662 for(int i=0; i<4 ;++i)
663 taction[i] = (*action_itr[i]);
665 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
667 for(int i=0; i<4 ;++i)
668 ++action_itr[i];
671 // original items
672 CharStartOutfitEntry const* oEntry = NULL;
673 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
675 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
677 if(entry->RaceClassGender == RaceClassGender)
679 oEntry = entry;
680 break;
685 if(oEntry)
687 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
689 if(oEntry->ItemId[j] <= 0)
690 continue;
692 uint32 item_id = oEntry->ItemId[j];
695 // Hack for not existed item id in dbc 3.0.3
696 if(item_id==40582)
697 continue;
699 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
700 if(!iProto)
702 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
703 continue;
706 // max stack by default (mostly 1), 1 for infinity stackable
707 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
709 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
711 switch(iProto->Spells[0].SpellCategory)
713 case 11: // food
714 if(iProto->Stackable > 4)
715 count = 4;
716 break;
717 case 59: // drink
718 if(iProto->Stackable > 2)
719 count = 2;
720 break;
724 StoreNewItemInBestSlots(item_id, count);
728 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
729 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
731 // bags and main-hand weapon must equipped at this moment
732 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
733 // or ammo not equipped in special bag
734 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
736 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
738 uint16 eDest;
739 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
740 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
741 if( msg == EQUIP_ERR_OK )
743 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
744 EquipItem( eDest, pItem, true);
746 // move other items to more appropriate slots (ammo not equipped in special bag)
747 else
749 ItemPosCountVec sDest;
750 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
751 if( msg == EQUIP_ERR_OK )
753 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
754 pItem = StoreItem( sDest, pItem, true);
757 // if this is ammo then use it
758 msg = CanUseAmmo( pItem->GetEntry() );
759 if( msg == EQUIP_ERR_OK )
760 SetAmmo( pItem->GetEntry() );
764 // all item positions resolved
766 return true;
769 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
771 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
773 // attempt equip by one
774 while(titem_amount > 0)
776 uint16 eDest;
777 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
778 if( msg != EQUIP_ERR_OK )
779 break;
781 EquipNewItem( eDest, titem_id, true);
782 AutoUnequipOffhandIfNeed();
783 --titem_amount;
786 if(titem_amount == 0)
787 return true; // equipped
789 // attempt store
790 ItemPosCountVec sDest;
791 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
792 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
793 if( msg == EQUIP_ERR_OK )
795 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
796 return true; // stored
799 // item can't be added
800 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
801 return false;
804 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
806 if (MaxValue == DISABLED_MIRROR_TIMER)
808 if (CurrentValue!=DISABLED_MIRROR_TIMER)
809 StopMirrorTimer(Type);
810 return;
812 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
813 data << (uint32)Type;
814 data << CurrentValue;
815 data << MaxValue;
816 data << Regen;
817 data << (uint8)0;
818 data << (uint32)0; // spell id
819 GetSession()->SendPacket( &data );
822 void Player::StopMirrorTimer(MirrorTimerType Type)
824 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
825 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
826 data << (uint32)Type;
827 GetSession()->SendPacket( &data );
830 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
832 if(!isAlive() || isGameMaster())
833 return;
835 // Absorb, resist some environmental damage type
836 uint32 absorb = 0;
837 uint32 resist = 0;
838 if (type == DAMAGE_LAVA)
839 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
840 else if (type == DAMAGE_SLIME)
841 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
843 damage-=absorb+resist;
845 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
846 data << uint64(GetGUID());
847 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
848 data << uint32(damage);
849 data << uint32(absorb);
850 data << uint32(resist);
851 SendMessageToSet(&data, true);
853 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
855 if(!isAlive())
857 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
859 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
860 DurabilityLossAll(0.10f,false);
861 // durability lost message
862 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
863 GetSession()->SendPacket(&data2);
866 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
870 int32 Player::getMaxTimer(MirrorTimerType timer)
872 switch (timer)
874 case FATIGUE_TIMER:
875 return MINUTE*IN_MILISECONDS;
876 case BREATH_TIMER:
878 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
879 return DISABLED_MIRROR_TIMER;
880 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
881 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
882 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
883 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
884 return UnderWaterTime;
886 case FIRE_TIMER:
888 if (!isAlive())
889 return DISABLED_MIRROR_TIMER;
890 return 1*IN_MILISECONDS;
892 default:
893 return 0;
895 return 0;
898 void Player::UpdateMirrorTimers()
900 // Desync flags for update on next HandleDrowning
901 if (m_MirrorTimerFlags)
902 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
905 void Player::HandleDrowning(uint32 time_diff)
907 if (!m_MirrorTimerFlags)
908 return;
910 // In water
911 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
913 // Breath timer not activated - activate it
914 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
916 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
917 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
919 else // If activated - do tick
921 m_MirrorTimer[BREATH_TIMER]-=time_diff;
922 // Timer limit - need deal damage
923 if (m_MirrorTimer[BREATH_TIMER] < 0)
925 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
926 // Calculate and deal damage
927 // TODO: Check this formula
928 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
929 EnvironmentalDamage(DAMAGE_DROWNING, damage);
931 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
932 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
935 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
937 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
938 // Need breath regen
939 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
940 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
941 StopMirrorTimer(BREATH_TIMER);
942 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
943 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
946 // In dark water
947 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
949 // Fatigue timer not activated - activate it
950 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
952 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
953 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
955 else
957 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
958 // Timer limit - need deal damage or teleport ghost to graveyard
959 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
961 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
962 if (isAlive()) // Calculate and deal damage
964 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
965 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
967 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
968 RepopAtGraveyard();
970 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
971 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
974 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
976 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
977 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
978 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
979 StopMirrorTimer(FATIGUE_TIMER);
980 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
981 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
984 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
986 // Breath timer not activated - activate it
987 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
988 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
989 else
991 m_MirrorTimer[FIRE_TIMER]-=time_diff;
992 if (m_MirrorTimer[FIRE_TIMER] < 0)
994 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
995 // Calculate and deal damage
996 // TODO: Check this formula
997 uint32 damage = urand(600, 700);
998 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
999 EnvironmentalDamage(DAMAGE_LAVA, damage);
1000 else
1001 EnvironmentalDamage(DAMAGE_SLIME, damage);
1005 else
1006 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1008 // Recheck timers flag
1009 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1010 for (int i = 0; i< MAX_TIMERS; ++i)
1011 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1013 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1014 break;
1016 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1019 ///The player sobers by 256 every 10 seconds
1020 void Player::HandleSobering()
1022 m_drunkTimer = 0;
1024 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1025 SetDrunkValue(drunk);
1028 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1030 if(value >= 23000)
1031 return DRUNKEN_SMASHED;
1032 if(value >= 12800)
1033 return DRUNKEN_DRUNK;
1034 if(value & 0xFFFE)
1035 return DRUNKEN_TIPSY;
1036 return DRUNKEN_SOBER;
1039 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1041 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1043 m_drunk = newDrunkenValue;
1044 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1046 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1048 // special drunk invisibility detection
1049 if(newDrunkenState >= DRUNKEN_DRUNK)
1050 m_detectInvisibilityMask |= (1<<6);
1051 else
1052 m_detectInvisibilityMask &= ~(1<<6);
1054 if(newDrunkenState == oldDrunkenState)
1055 return;
1057 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1058 data << uint64(GetGUID());
1059 data << uint32(newDrunkenState);
1060 data << uint32(itemId);
1062 SendMessageToSet(&data, true);
1065 void Player::Update( uint32 p_time )
1067 if(!IsInWorld())
1068 return;
1070 // undelivered mail
1071 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1073 SendNewMail();
1074 ++unReadMails;
1076 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1077 m_nextMailDelivereTime = 0;
1080 Unit::Update( p_time );
1082 // update player only attacks
1083 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1085 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1088 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1090 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1093 time_t now = time (NULL);
1095 UpdatePvPFlag(now);
1097 UpdateContestedPvP(p_time);
1099 UpdateDuelFlag(now);
1101 CheckDuelDistance(now);
1103 UpdateAfkReport(now);
1105 // Update items that have just a limited lifetime
1106 if (now>m_Last_tick)
1107 UpdateItemDuration(uint32(now- m_Last_tick));
1109 if (!m_timedquests.empty())
1111 std::set<uint32>::iterator iter = m_timedquests.begin();
1112 while (iter != m_timedquests.end())
1114 QuestStatusData& q_status = mQuestStatus[*iter];
1115 if( q_status.m_timer <= p_time )
1117 uint32 quest_id = *iter;
1118 ++iter; // current iter will be removed in FailTimedQuest
1119 FailTimedQuest( quest_id );
1121 else
1123 q_status.m_timer -= p_time;
1124 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1125 ++iter;
1130 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1132 Unit *pVictim = getVictim();
1133 if (pVictim && !IsNonMeleeSpellCasted(false))
1135 // default combat reach 10
1136 // TODO add weapon,skill check
1138 float pldistance = ATTACK_DISTANCE;
1140 if (isAttackReady(BASE_ATTACK))
1142 if(!IsWithinDistInMap(pVictim, pldistance))
1144 setAttackTimer(BASE_ATTACK,100);
1145 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1147 SendAttackSwingNotInRange();
1148 m_swingErrorMsg = 1;
1151 //120 degrees of radiant range
1152 else if( !HasInArc( 2*M_PI/3, pVictim ))
1154 setAttackTimer(BASE_ATTACK,100);
1155 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1157 SendAttackSwingBadFacingAttack();
1158 m_swingErrorMsg = 2;
1161 else
1163 m_swingErrorMsg = 0; // reset swing error state
1165 // prevent base and off attack in same time, delay attack at 0.2 sec
1166 if(haveOffhandWeapon())
1168 uint32 off_att = getAttackTimer(OFF_ATTACK);
1169 if(off_att < ATTACK_DISPLAY_DELAY)
1170 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1172 AttackerStateUpdate(pVictim, BASE_ATTACK);
1173 resetAttackTimer(BASE_ATTACK);
1177 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1179 if(!IsWithinDistInMap(pVictim, pldistance))
1181 setAttackTimer(OFF_ATTACK,100);
1183 else if( !HasInArc( 2*M_PI/3, pVictim ))
1185 setAttackTimer(OFF_ATTACK,100);
1187 else
1189 // prevent base and off attack in same time, delay attack at 0.2 sec
1190 uint32 base_att = getAttackTimer(BASE_ATTACK);
1191 if(base_att < ATTACK_DISPLAY_DELAY)
1192 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1193 // do attack
1194 AttackerStateUpdate(pVictim, OFF_ATTACK);
1195 resetAttackTimer(OFF_ATTACK);
1199 Unit *owner = pVictim->GetOwner();
1200 Unit *u = owner ? owner : pVictim;
1201 if(u->IsPvP() && (!duel || duel->opponent != u))
1203 UpdatePvP(true);
1204 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1209 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1211 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1213 int time_inn = time(NULL)-GetTimeInnEnter();
1214 if (time_inn >= 10) //freeze update
1216 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1217 //speed collect rest bonus (section/in hour)
1218 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1219 UpdateInnerTime(time(NULL));
1224 if(m_regenTimer > 0)
1226 if(p_time >= m_regenTimer)
1227 m_regenTimer = 0;
1228 else
1229 m_regenTimer -= p_time;
1232 if (m_weaponChangeTimer > 0)
1234 if(p_time >= m_weaponChangeTimer)
1235 m_weaponChangeTimer = 0;
1236 else
1237 m_weaponChangeTimer -= p_time;
1240 if (m_zoneUpdateTimer > 0)
1242 if(p_time >= m_zoneUpdateTimer)
1244 uint32 newzone, newarea;
1245 GetZoneAndAreaId(newzone,newarea);
1247 if( m_zoneUpdateId != newzone )
1248 UpdateZone(newzone,newarea); // also update area
1249 else
1251 // use area updates as well
1252 // needed for free far all arenas for example
1253 if( m_areaUpdateId != newarea )
1254 UpdateArea(newarea);
1256 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1259 else
1260 m_zoneUpdateTimer -= p_time;
1263 if (isAlive())
1265 RegenerateAll();
1268 if (m_deathState == JUST_DIED)
1270 KillPlayer();
1273 if(m_nextSave > 0)
1275 if(p_time >= m_nextSave)
1277 // m_nextSave reseted in SaveToDB call
1278 SaveToDB();
1279 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1281 else
1283 m_nextSave -= p_time;
1287 //Handle Water/drowning
1288 HandleDrowning(p_time);
1290 //Handle detect stealth players
1291 if (m_DetectInvTimer > 0)
1293 if (p_time >= m_DetectInvTimer)
1295 m_DetectInvTimer = 3000;
1296 HandleStealthedUnitsDetection();
1298 else
1299 m_DetectInvTimer -= p_time;
1302 // Played time
1303 if (now > m_Last_tick)
1305 uint32 elapsed = uint32(now - m_Last_tick);
1306 m_Played_time[0] += elapsed; // Total played time
1307 m_Played_time[1] += elapsed; // Level played time
1308 m_Last_tick = now;
1311 if (m_drunk)
1313 m_drunkTimer += p_time;
1315 if (m_drunkTimer > 10*IN_MILISECONDS)
1316 HandleSobering();
1319 // not auto-free ghost from body in instances
1320 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1322 if(p_time >= m_deathTimer)
1324 m_deathTimer = 0;
1325 BuildPlayerRepop();
1326 RepopAtGraveyard();
1328 else
1329 m_deathTimer -= p_time;
1332 UpdateEnchantTime(p_time);
1333 UpdateHomebindTime(p_time);
1335 // group update
1336 SendUpdateToOutOfRangeGroupMembers();
1338 Pet* pet = GetPet();
1339 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1341 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1342 return;
1346 void Player::setDeathState(DeathState s)
1348 uint32 ressSpellId = 0;
1350 bool cur = isAlive();
1352 if(s == JUST_DIED && cur)
1354 // drunken state is cleared on death
1355 SetDrunkValue(0);
1356 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1357 ClearComboPoints();
1359 clearResurrectRequestData();
1361 // remove form before other mods to prevent incorrect stats calculation
1362 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1364 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1365 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1367 // remove uncontrolled pets
1368 RemoveMiniPet();
1369 RemoveGuardians();
1371 // save value before aura remove in Unit::setDeathState
1372 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1374 // passive spell
1375 if(!ressSpellId)
1376 ressSpellId = GetResurrectionSpellId();
1377 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1378 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1381 Unit::setDeathState(s);
1383 // restore resurrection spell id for player after aura remove
1384 if(s == JUST_DIED && cur && ressSpellId)
1385 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1387 if(isAlive() && !cur)
1389 //clear aura case after resurrection by another way (spells will be applied before next death)
1390 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1392 // restore default warrior stance
1393 if(getClass()== CLASS_WARRIOR)
1394 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1398 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1400 Field *fields = result->Fetch();
1402 *p_data << uint64(GetGUID());
1403 *p_data << m_name;
1405 *p_data << uint8(getRace());
1406 uint8 pClass = getClass();
1407 *p_data << uint8(pClass);
1408 *p_data << uint8(getGender());
1410 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1411 *p_data << uint8(bytes);
1412 *p_data << uint8(bytes >> 8);
1413 *p_data << uint8(bytes >> 16);
1414 *p_data << uint8(bytes >> 24);
1416 bytes = GetUInt32Value(PLAYER_BYTES_2);
1417 *p_data << uint8(bytes);
1419 *p_data << uint8(getLevel()); // player level
1420 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1421 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1422 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1423 *p_data << uint32(zoneId);
1424 *p_data << uint32(GetMapId());
1426 *p_data << GetPositionX();
1427 *p_data << GetPositionY();
1428 *p_data << GetPositionZ();
1430 // guild id
1431 *p_data << (result ? fields[13].GetUInt32() : 0);
1433 uint32 char_flags = 0;
1434 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1435 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1436 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1437 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1438 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1439 char_flags |= CHARACTER_FLAG_GHOST;
1440 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1441 char_flags |= CHARACTER_FLAG_RENAME;
1442 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1443 char_flags |= CHARACTER_FLAG_DECLINED;
1445 *p_data << uint32(char_flags); // character flags
1446 // character customize (flags?)
1447 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1448 *p_data << uint8(1); // unknown
1450 // Pets info
1452 uint32 petDisplayId = 0;
1453 uint32 petLevel = 0;
1454 uint32 petFamily = 0;
1456 // show pet at selection character in character list only for non-ghost character
1457 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1459 uint32 entry = fields[10].GetUInt32();
1460 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1461 if(cInfo)
1463 petDisplayId = fields[11].GetUInt32();
1464 petLevel = fields[12].GetUInt32();
1465 petFamily = cInfo->family;
1469 *p_data << uint32(petDisplayId);
1470 *p_data << uint32(petLevel);
1471 *p_data << uint32(petFamily);
1474 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1476 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1477 uint32 item_id = GetUInt32Value(visualbase);
1478 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1479 SpellItemEnchantmentEntry const *enchant = NULL;
1481 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1483 uint32 enchantId = GetUInt16Value(visualbase + 1, enchantSlot);
1484 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1485 break;
1488 if (proto != NULL)
1490 *p_data << uint32(proto->DisplayInfoID);
1491 *p_data << uint8(proto->InventoryType);
1492 *p_data << uint32(enchant ? enchant->aura_id : 0);
1494 else
1496 *p_data << uint32(0);
1497 *p_data << uint8(0);
1498 *p_data << uint32(0); // enchant?
1501 *p_data << uint32(0); // first bag display id
1502 *p_data << uint8(0); // first bag inventory type
1503 *p_data << uint32(0); // enchant?
1506 bool Player::ToggleAFK()
1508 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1510 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1512 // afk player not allowed in battleground
1513 if(state && InBattleGround())
1514 LeaveBattleground();
1516 return state;
1519 bool Player::ToggleDND()
1521 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1523 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1526 uint8 Player::chatTag() const
1528 // it's bitmask
1529 // 0x8 - ??
1530 // 0x4 - gm
1531 // 0x2 - dnd
1532 // 0x1 - afk
1533 if(isGMChat())
1534 return 4;
1535 else if(isDND())
1536 return 3;
1537 if(isAFK())
1538 return 1;
1539 else
1540 return 0;
1543 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1545 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1547 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1548 return false;
1551 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1552 Pet* pet = GetPet();
1554 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1556 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1557 // don't let gm level > 1 either
1558 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1559 return false;
1561 // client without expansion support
1562 if(GetSession()->Expansion() < mEntry->Expansion())
1564 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1566 if(GetTransport())
1567 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1569 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1571 return false; // normal client can't teleport to this map...
1573 else
1575 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1578 // if we were on a transport, leave
1579 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1581 m_transport->RemovePassenger(this);
1582 m_transport = NULL;
1583 m_movementInfo.t_x = 0.0f;
1584 m_movementInfo.t_y = 0.0f;
1585 m_movementInfo.t_z = 0.0f;
1586 m_movementInfo.t_o = 0.0f;
1587 m_movementInfo.t_time = 0;
1590 // The player was ported to another map and looses the duel immediately.
1591 // We have to perform this check before the teleport, otherwise the
1592 // ObjectAccessor won't find the flag.
1593 if (duel && GetMapId()!=mapid)
1595 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1596 if (obj)
1597 DuelComplete(DUEL_FLED);
1600 // reset movement flags at teleport, because player will continue move with these flags after teleport
1601 m_movementInfo.flags = 0;
1603 if ((GetMapId() == mapid) && (!m_transport))
1605 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1607 //same map, only remove pet if out of range for new position
1608 if(pet && pet->GetDistance(x,y,z) >= OWNER_MAX_DISTANCE)
1609 UnsummonPetTemporaryIfAny();
1612 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1613 CombatStop();
1615 // this will be used instead of the current location in SaveToDB
1616 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1617 SetFallInformation(0, z);
1619 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1620 // at client packet MSG_MOVE_TELEPORT_ACK
1621 SetSemaphoreTeleportNear(true);
1622 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1623 if(!GetSession()->PlayerLogout())
1625 WorldPacket data;
1626 BuildTeleportAckMsg(&data, x, y, z, orientation);
1627 GetSession()->SendPacket(&data);
1630 else
1632 // far teleport to another map
1633 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1634 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1636 // Check enter rights before map getting to avoid creating instance copy for player
1637 // this check not dependent from map instance copy and same for all instance copies of selected map
1638 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1639 return false;
1641 // If the map is not created, assume it is possible to enter it.
1642 // It will be created in the WorldPortAck.
1643 Map *map = MapManager::Instance().FindMap(mapid);
1644 if (!map || map->CanEnter(this))
1646 SetSelection(0);
1648 CombatStop();
1650 ResetContestedPvP();
1652 // remove player from battleground on far teleport (when changing maps)
1653 if(BattleGround const* bg = GetBattleGround())
1655 // Note: at battleground join battleground id set before teleport
1656 // and we already will found "current" battleground
1657 // just need check that this is targeted map or leave
1658 if(bg->GetMapId() != mapid)
1659 LeaveBattleground(false); // don't teleport to entry point
1662 // remove pet on map change
1663 if (pet)
1664 UnsummonPetTemporaryIfAny();
1666 // remove all dyn objects
1667 RemoveAllDynObjects();
1669 // stop spellcasting
1670 // not attempt interrupt teleportation spell at caster teleport
1671 if(!(options & TELE_TO_SPELL))
1672 if(IsNonMeleeSpellCasted(true))
1673 InterruptNonMeleeSpells(true);
1675 if(!GetSession()->PlayerLogout())
1677 // send transfer packets
1678 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1679 data << uint32(mapid);
1680 if (m_transport)
1682 data << m_transport->GetEntry() << GetMapId();
1684 GetSession()->SendPacket(&data);
1686 data.Initialize(SMSG_NEW_WORLD, (20));
1687 if (m_transport)
1689 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1691 else
1693 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1695 GetSession()->SendPacket( &data );
1696 SendSavedInstances();
1698 // remove from old map now
1699 if(oldmap) oldmap->Remove(this, false);
1702 // new final coordinates
1703 float final_x = x;
1704 float final_y = y;
1705 float final_z = z;
1706 float final_o = orientation;
1708 if(m_transport)
1710 final_x += m_movementInfo.t_x;
1711 final_y += m_movementInfo.t_y;
1712 final_z += m_movementInfo.t_z;
1713 final_o += m_movementInfo.t_o;
1716 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1717 SetFallInformation(0, final_z);
1718 // if the player is saved before worldportack (at logout for example)
1719 // this will be used instead of the current location in SaveToDB
1721 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1723 // move packet sent by client always after far teleport
1724 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1725 SetSemaphoreTeleportFar(true);
1727 else
1728 return false;
1730 return true;
1733 void Player::AddToWorld()
1735 ///- Do not add/remove the player from the object storage
1736 ///- It will crash when updating the ObjectAccessor
1737 ///- The player should only be added when logging in
1738 Unit::AddToWorld();
1740 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1742 if(m_items[i])
1743 m_items[i]->AddToWorld();
1747 void Player::RemoveFromWorld()
1749 // cleanup
1750 if(IsInWorld())
1752 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1753 Uncharm();
1754 UnsummonAllTotems();
1755 RemoveMiniPet();
1756 RemoveGuardians();
1759 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1761 if(m_items[i])
1762 m_items[i]->RemoveFromWorld();
1765 ///- Do not add/remove the player from the object storage
1766 ///- It will crash when updating the ObjectAccessor
1767 ///- The player should only be removed when logging out
1768 Unit::RemoveFromWorld();
1771 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1773 float addRage;
1775 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1777 if(attacker)
1779 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1781 // talent who gave more rage on attack
1782 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1784 else
1786 addRage = damage/rageconversion*2.5;
1788 // Berserker Rage effect
1789 if(HasAura(18499,0))
1790 addRage *= 1.3;
1793 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1795 ModifyPower(POWER_RAGE, uint32(addRage*10));
1798 void Player::RegenerateAll()
1800 if (m_regenTimer != 0)
1801 return;
1802 uint32 regenDelay = 2000;
1804 // Not in combat or they have regeneration
1805 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1806 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1808 RegenerateHealth();
1809 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1811 Regenerate(POWER_RAGE);
1812 if(getClass() == CLASS_DEATH_KNIGHT)
1813 Regenerate(POWER_RUNIC_POWER);
1817 Regenerate( POWER_ENERGY );
1819 Regenerate( POWER_MANA );
1821 if(getClass() == CLASS_DEATH_KNIGHT)
1822 Regenerate( POWER_RUNE );
1824 m_regenTimer = regenDelay;
1827 void Player::Regenerate(Powers power)
1829 uint32 curValue = GetPower(power);
1830 uint32 maxValue = GetMaxPower(power);
1832 float addvalue = 0.0f;
1834 switch (power)
1836 case POWER_MANA:
1838 bool recentCast = IsUnderLastManaUseEffect();
1839 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1840 if (recentCast)
1842 // Mangos Updates Mana in intervals of 2s, which is correct
1843 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1845 else
1847 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1849 } break;
1850 case POWER_RAGE: // Regenerate rage
1852 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1853 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1854 } break;
1855 case POWER_ENERGY: // Regenerate energy (rogue)
1856 addvalue = 20;
1857 break;
1858 case POWER_RUNIC_POWER:
1860 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1861 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1862 } break;
1863 case POWER_RUNE:
1865 for(uint32 i = 0; i < MAX_RUNES; ++i)
1866 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1867 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1868 } break;
1869 case POWER_FOCUS:
1870 case POWER_HAPPINESS:
1871 case POWER_HEALTH:
1872 break;
1875 // Mana regen calculated in Player::UpdateManaRegen()
1876 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1877 if(power != POWER_MANA)
1879 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1880 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1881 if ((*i)->GetModifier()->m_miscvalue == power)
1882 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1885 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1887 curValue += uint32(addvalue);
1888 if (curValue > maxValue)
1889 curValue = maxValue;
1891 else
1893 if(curValue <= uint32(addvalue))
1894 curValue = 0;
1895 else
1896 curValue -= uint32(addvalue);
1898 SetPower(power, curValue);
1901 void Player::RegenerateHealth()
1903 uint32 curValue = GetHealth();
1904 uint32 maxValue = GetMaxHealth();
1906 if (curValue >= maxValue) return;
1908 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1910 float addvalue = 0.0f;
1912 // polymorphed case
1913 if ( IsPolymorphed() )
1914 addvalue = GetMaxHealth()/3;
1915 // normal regen case (maybe partly in combat case)
1916 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1918 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1919 if (!isInCombat())
1921 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1922 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1923 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1925 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1926 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1928 if(!IsStandState())
1929 addvalue *= 1.5;
1932 // always regeneration bonus (including combat)
1933 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1935 if(addvalue < 0)
1936 addvalue = 0;
1938 ModifyHealth(int32(addvalue));
1941 bool Player::CanInteractWithNPCs(bool alive) const
1943 if(alive && !isAlive())
1944 return false;
1945 if(isInFlight())
1946 return false;
1948 return true;
1951 Creature*
1952 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1954 // unit checks
1955 if (!guid)
1956 return NULL;
1958 if(!IsInWorld())
1959 return NULL;
1961 // exist (we need look pets also for some interaction (quest/etc)
1962 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1963 if (!unit)
1964 return NULL;
1966 // player check
1967 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1968 return NULL;
1970 // appropriate npc type
1971 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1972 return NULL;
1974 // alive or spirit healer
1975 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1976 return NULL;
1978 // not allow interaction under control, but allow with own pets
1979 if(unit->GetCharmerGUID())
1980 return NULL;
1982 // not enemy
1983 if( unit->IsHostileTo(this))
1984 return NULL;
1986 // not unfriendly
1987 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1988 if(factionTemplate->faction)
1989 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
1990 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
1991 return NULL;
1993 // not too far
1994 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
1995 return NULL;
1997 return unit;
2000 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2002 if(GameObject *go = GetMap()->GetGameObject(guid))
2004 if(go->GetGoType() == type)
2006 float maxdist;
2007 switch(type)
2009 // TODO: find out how the client calculates the maximal usage distance to spellless working
2010 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2011 case GAMEOBJECT_TYPE_GUILD_BANK:
2012 case GAMEOBJECT_TYPE_MAILBOX:
2013 maxdist = 10.0f;
2014 break;
2015 case GAMEOBJECT_TYPE_FISHINGHOLE:
2016 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2017 break;
2018 default:
2019 maxdist = INTERACTION_DISTANCE;
2020 break;
2023 if (go->IsWithinDistInMap(this, maxdist))
2024 return go;
2026 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,
2027 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2030 return NULL;
2033 bool Player::IsUnderWater() const
2035 return IsInWater() &&
2036 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2039 void Player::SetInWater(bool apply)
2041 if(m_isInWater==apply)
2042 return;
2044 //define player in water by opcodes
2045 //move player's guid into HateOfflineList of those mobs
2046 //which can't swim and move guid back into ThreatList when
2047 //on surface.
2048 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2049 m_isInWater = apply;
2051 // remove auras that need water/land
2052 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2054 getHostilRefManager().updateThreatTables();
2057 void Player::SetGameMaster(bool on)
2059 if(on)
2061 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2062 setFaction(35);
2063 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2065 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2066 ResetContestedPvP();
2068 getHostilRefManager().setOnlineOfflineState(false);
2069 CombatStop();
2071 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2073 else
2075 // restore phase
2076 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2077 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2079 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2080 setFactionForRace(getRace());
2081 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2083 // restore FFA PvP Server state
2084 if(sWorld.IsFFAPvPRealm())
2085 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2087 // restore FFA PvP area state, remove not allowed for GM mounts
2088 UpdateArea(m_areaUpdateId);
2090 getHostilRefManager().setOnlineOfflineState(true);
2093 ObjectAccessor::UpdateVisibilityForPlayer(this);
2096 void Player::SetGMVisible(bool on)
2098 if(on)
2100 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2102 // Reapply stealth/invisibility if active or show if not any
2103 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2104 SetVisibility(VISIBILITY_GROUP_STEALTH);
2105 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2106 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2107 else
2108 SetVisibility(VISIBILITY_ON);
2110 else
2112 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2114 SetAcceptWhispers(false);
2115 SetGameMaster(true);
2117 SetVisibility(VISIBILITY_OFF);
2121 bool Player::IsGroupVisibleFor(Player* p) const
2123 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2125 default: return IsInSameGroupWith(p);
2126 case 1: return IsInSameRaidWith(p);
2127 case 2: return GetTeam()==p->GetTeam();
2131 bool Player::IsInSameGroupWith(Player const* p) const
2133 return p==this || GetGroup() != NULL &&
2134 GetGroup() == p->GetGroup() &&
2135 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2138 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2139 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2140 void Player::UninviteFromGroup()
2142 Group* group = GetGroupInvite();
2143 if(!group)
2144 return;
2146 group->RemoveInvite(this);
2148 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2150 if(group->IsCreated())
2152 group->Disband(true);
2153 objmgr.RemoveGroup(group);
2155 else
2156 group->RemoveAllInvites();
2158 delete group;
2162 void Player::RemoveFromGroup(Group* group, uint64 guid)
2164 if(group)
2166 if (group->RemoveMember(guid, 0) <= 1)
2168 // group->Disband(); already disbanded in RemoveMember
2169 objmgr.RemoveGroup(group);
2170 delete group;
2171 // removemember sets the player's group pointer to NULL
2176 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2178 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2179 data << uint64(victim ? victim->GetGUID() : 0); // guid
2180 data << uint32(GivenXP+RestXP); // given experience
2181 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2182 if(victim)
2184 data << uint32(GivenXP); // experience without rested bonus
2185 data << float(1); // 1 - none 0 - 100% group bonus output
2187 data << uint8(0); // new 2.4.0
2188 GetSession()->SendPacket(&data);
2191 void Player::GiveXP(uint32 xp, Unit* victim)
2193 if ( xp < 1 )
2194 return;
2196 if(!isAlive())
2197 return;
2199 uint32 level = getLevel();
2201 // XP to money conversion processed in Player::RewardQuest
2202 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2203 return;
2205 // handle SPELL_AURA_MOD_XP_PCT auras
2206 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2207 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2208 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2210 // XP resting bonus for kill
2211 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2213 SendLogXPGain(xp,victim,rested_bonus_xp);
2215 uint32 curXP = GetUInt32Value(PLAYER_XP);
2216 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2217 uint32 newXP = curXP + xp + rested_bonus_xp;
2219 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2221 newXP -= nextLvlXP;
2223 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2224 GiveLevel(level + 1);
2226 level = getLevel();
2227 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2230 SetUInt32Value(PLAYER_XP, newXP);
2233 // Update player to next level
2234 // Current player experience not update (must be update by caller)
2235 void Player::GiveLevel(uint32 level)
2237 if ( level == getLevel() )
2238 return;
2240 PlayerLevelInfo info;
2241 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2243 PlayerClassLevelInfo classInfo;
2244 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2246 // send levelup info to client
2247 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2248 data << uint32(level);
2249 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2250 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2251 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2252 data << uint32(0);
2253 data << uint32(0);
2254 data << uint32(0);
2255 data << uint32(0);
2256 data << uint32(0);
2257 data << uint32(0);
2258 // end for
2259 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2260 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2262 GetSession()->SendPacket(&data);
2264 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2266 //update level, max level of skills
2267 if(getLevel()!= level)
2268 m_Played_time[1] = 0; // Level Played Time reset
2269 SetLevel(level);
2270 UpdateSkillsForLevel ();
2272 // save base values (bonuses already included in stored stats
2273 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2274 SetCreateStat(Stats(i), info.stats[i]);
2276 SetCreateHealth(classInfo.basehealth);
2277 SetCreateMana(classInfo.basemana);
2279 InitTalentForLevel();
2280 InitTaxiNodesForLevel();
2281 InitGlyphsForLevel();
2283 UpdateAllStats();
2285 // set current level health and mana/energy to maximum after applying all mods.
2286 SetHealth(GetMaxHealth());
2287 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2288 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2289 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2290 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2291 SetPower(POWER_FOCUS, 0);
2292 SetPower(POWER_HAPPINESS, 0);
2294 // give level to summoned pet
2295 Pet* pet = GetPet();
2296 if(pet && pet->getPetType()==SUMMON_PET)
2297 pet->GivePetLevel(level);
2298 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2301 void Player::InitTalentForLevel()
2303 uint32 level = getLevel();
2304 // talents base at level diff ( talents = level - 9 but some can be used already)
2305 if(level < 10)
2307 // Remove all talent points
2308 if(m_usedTalentCount > 0) // Free any used talents
2310 resetTalents(true);
2311 SetFreeTalentPoints(0);
2314 else
2316 uint32 talentPointsForLevel = CalculateTalentsPoints();
2318 // if used more that have then reset
2319 if(m_usedTalentCount > talentPointsForLevel)
2321 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2322 resetTalents(true);
2323 else
2324 SetFreeTalentPoints(0);
2326 // else update amount of free points
2327 else
2328 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2331 SendTalentsInfoData(false); // update at client
2334 void Player::InitStatsForLevel(bool reapplyMods)
2336 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2337 _RemoveAllStatBonuses();
2339 PlayerClassLevelInfo classInfo;
2340 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2342 PlayerLevelInfo info;
2343 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2345 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2346 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2348 UpdateSkillsForLevel ();
2350 // set default cast time multiplier
2351 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2353 // reset size before reapply auras
2354 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2356 // save base values (bonuses already included in stored stats
2357 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2358 SetCreateStat(Stats(i), info.stats[i]);
2360 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2361 SetStat(Stats(i), info.stats[i]);
2363 SetCreateHealth(classInfo.basehealth);
2365 //set create powers
2366 SetCreateMana(classInfo.basemana);
2368 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2370 InitStatBuffMods();
2372 //reset rating fields values
2373 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2374 SetUInt32Value(index, 0);
2376 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2377 for (int i = 0; i < 7; ++i)
2379 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2380 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2381 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2384 //reset attack power, damage and attack speed fields
2385 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2386 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2387 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2389 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2390 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2391 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2392 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2393 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2394 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2396 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2397 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2398 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2399 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2400 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2401 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2403 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2404 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2405 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2406 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2408 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2409 for (uint8 i = 0; i < 7; ++i)
2410 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2412 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2413 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2414 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2416 // Dodge percentage
2417 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2419 // set armor (resistance 0) to original value (create_agility*2)
2420 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2421 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2422 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2423 // set other resistance to original value (0)
2424 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2426 SetResistance(SpellSchools(i), 0);
2427 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2428 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2431 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2432 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2433 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2435 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2436 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2438 // Reset no reagent cost field
2439 for(int i = 0; i < 3; ++i)
2440 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2441 // Init data for form but skip reapply item mods for form
2442 InitDataForForm(reapplyMods);
2444 // save new stats
2445 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2446 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2448 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2450 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2451 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2453 // cleanup unit flags (will be re-applied if need at aura load).
2454 RemoveFlag( UNIT_FIELD_FLAGS,
2455 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2456 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2457 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2458 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2459 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2460 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2462 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2464 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2465 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2467 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2468 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2470 // restore if need some important flags
2471 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2473 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2474 _ApplyAllStatBonuses();
2476 // set current level health and mana/energy to maximum after applying all mods.
2477 SetHealth(GetMaxHealth());
2478 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2479 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2480 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2481 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2482 SetPower(POWER_FOCUS, 0);
2483 SetPower(POWER_HAPPINESS, 0);
2484 SetPower(POWER_RUNIC_POWER, 0);
2487 void Player::SendInitialSpells()
2489 time_t curTime = time(NULL);
2490 time_t infTime = curTime + MONTH/2;
2492 uint16 spellCount = 0;
2494 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2495 data << uint8(0);
2497 size_t countPos = data.wpos();
2498 data << uint16(spellCount); // spell count placeholder
2500 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2502 if(itr->second->state == PLAYERSPELL_REMOVED)
2503 continue;
2505 if(!itr->second->active || itr->second->disabled)
2506 continue;
2508 data << uint32(itr->first);
2509 data << uint16(0); // it's not slot id
2511 spellCount +=1;
2514 data.put<uint16>(countPos,spellCount); // write real count value
2516 uint16 spellCooldowns = m_spellCooldowns.size();
2517 data << uint16(spellCooldowns);
2518 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2520 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2521 if(!sEntry)
2522 continue;
2524 // not send infinity cooldown
2525 if(itr->second.end > infTime)
2526 continue;
2528 data << uint32(itr->first);
2530 time_t cooldown = 0;
2531 if(itr->second.end > curTime)
2532 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2534 data << uint16(itr->second.itemid); // cast item id
2535 data << uint16(sEntry->Category); // spell category
2536 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2538 data << uint32(0); // cooldown
2539 data << uint32(cooldown); // category cooldown
2541 else
2543 data << uint32(cooldown); // cooldown
2544 data << uint32(0); // category cooldown
2548 GetSession()->SendPacket(&data);
2550 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2553 void Player::RemoveMail(uint32 id)
2555 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2557 if ((*itr)->messageID == id)
2559 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2560 m_mail.erase(itr);
2561 return;
2566 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2568 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2569 data << (uint32) mailId;
2570 data << (uint32) mailAction;
2571 data << (uint32) mailError;
2572 if ( mailError == MAIL_ERR_BAG_FULL )
2573 data << (uint32) equipError;
2574 else if( mailAction == MAIL_ITEM_TAKEN )
2576 data << (uint32) item_guid; // item guid low?
2577 data << (uint32) item_count; // item count?
2579 GetSession()->SendPacket(&data);
2582 void Player::SendNewMail()
2584 // deliver undelivered mail
2585 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2586 data << (uint32) 0;
2587 GetSession()->SendPacket(&data);
2590 void Player::UpdateNextMailTimeAndUnreads()
2592 // calculate next delivery time (min. from non-delivered mails
2593 // and recalculate unReadMail
2594 time_t cTime = time(NULL);
2595 m_nextMailDelivereTime = 0;
2596 unReadMails = 0;
2597 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2599 if((*itr)->deliver_time > cTime)
2601 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2602 m_nextMailDelivereTime = (*itr)->deliver_time;
2604 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2605 ++unReadMails;
2609 void Player::AddNewMailDeliverTime(time_t deliver_time)
2611 if(deliver_time <= time(NULL)) // ready now
2613 ++unReadMails;
2614 SendNewMail();
2616 else // not ready and no have ready mails
2618 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2619 m_nextMailDelivereTime = deliver_time;
2623 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2625 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2626 if (!spellInfo)
2628 // do character spell book cleanup (all characters)
2629 if(!IsInWorld() && !learning) // spell load case
2631 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2632 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2634 else
2635 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2637 return false;
2640 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2642 // do character spell book cleanup (all characters)
2643 if(!IsInWorld() && !learning) // spell load case
2645 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2646 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2648 else
2649 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2651 return false;
2654 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2656 bool dependent_set = false;
2657 bool disabled_case = false;
2658 bool superceded_old = false;
2660 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2661 if (itr != m_spells.end())
2663 uint32 next_active_spell_id = 0;
2664 // fix activate state for non-stackable low rank (and find next spell for !active case)
2665 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2667 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2668 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2670 if(HasSpell(next_itr->second))
2672 // high rank already known so this must !active
2673 active = false;
2674 next_active_spell_id = next_itr->second;
2675 break;
2680 // not do anything if already known in expected state
2681 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2682 itr->second->dependent == dependent && itr->second->disabled == disabled)
2684 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2685 itr->second->state = PLAYERSPELL_UNCHANGED;
2687 return false;
2690 // dependent spell known as not dependent, overwrite state
2691 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2693 itr->second->dependent = dependent;
2694 if (itr->second->state != PLAYERSPELL_NEW)
2695 itr->second->state = PLAYERSPELL_CHANGED;
2696 dependent_set = true;
2699 // update active state for known spell
2700 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2702 itr->second->active = active;
2704 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2705 itr->second->state = PLAYERSPELL_UNCHANGED;
2706 else if(itr->second->state != PLAYERSPELL_NEW)
2707 itr->second->state = PLAYERSPELL_CHANGED;
2709 if(active)
2711 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2712 CastSpell (this,spell_id,true);
2714 else if(IsInWorld())
2716 if(next_active_spell_id)
2718 // update spell ranks in spellbook and action bar
2719 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2720 data << uint32(spell_id);
2721 data << uint32(next_active_spell_id);
2722 GetSession()->SendPacket( &data );
2724 else
2726 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2727 data << uint32(spell_id);
2728 GetSession()->SendPacket(&data);
2732 return active; // learn (show in spell book if active now)
2735 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2737 if(itr->second->state != PLAYERSPELL_NEW)
2738 itr->second->state = PLAYERSPELL_CHANGED;
2739 itr->second->disabled = disabled;
2741 if(disabled)
2742 return false;
2744 disabled_case = true;
2746 else switch(itr->second->state)
2748 case PLAYERSPELL_UNCHANGED: // known saved spell
2749 return false;
2750 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2752 delete itr->second;
2753 m_spells.erase(itr);
2754 state = PLAYERSPELL_CHANGED;
2755 break; // need re-add
2757 default: // known not saved yet spell (new or modified)
2759 // can be in case spell loading but learned at some previous spell loading
2760 if(!IsInWorld() && !learning && !dependent_set)
2761 itr->second->state = PLAYERSPELL_UNCHANGED;
2763 return false;
2768 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2770 // talent: unlearn all other talent ranks (high and low)
2771 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2773 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2775 for(int i=0; i < MAX_TALENT_RANK; ++i)
2777 // skip learning spell and no rank spell case
2778 uint32 rankSpellId = talentInfo->RankID[i];
2779 if(!rankSpellId || rankSpellId==spell_id)
2780 continue;
2782 removeSpell(rankSpellId);
2786 // non talent spell: learn low ranks (recursive call)
2787 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2789 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2790 addSpell(prev_spell,active,true,true,disabled);
2791 else // at normal learning
2792 learnSpell(prev_spell,true);
2795 PlayerSpell *newspell = new PlayerSpell;
2796 newspell->state = state;
2797 newspell->active = active;
2798 newspell->dependent = dependent;
2799 newspell->disabled = disabled;
2801 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2802 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2804 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2806 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2807 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2808 if(!i_spellInfo) continue;
2810 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2812 if(itr2->second->active)
2814 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2816 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2818 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2819 data << uint32(itr2->first);
2820 data << uint32(spell_id);
2821 GetSession()->SendPacket( &data );
2824 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2825 itr2->second->active = false;
2826 if(itr2->second->state != PLAYERSPELL_NEW)
2827 itr2->second->state = PLAYERSPELL_CHANGED;
2828 superceded_old = true; // new spell replace old in action bars and spell book.
2830 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2832 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2834 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2835 data << uint32(spell_id);
2836 data << uint32(itr2->first);
2837 GetSession()->SendPacket( &data );
2840 // mark new spell as disable (not learned yet for client and will not learned)
2841 newspell->active = false;
2842 if(newspell->state != PLAYERSPELL_NEW)
2843 newspell->state = PLAYERSPELL_CHANGED;
2850 m_spells[spell_id] = newspell;
2852 // return false if spell disabled
2853 if (newspell->disabled)
2854 return false;
2857 uint32 talentCost = GetTalentSpellCost(spell_id);
2859 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2860 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2861 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2863 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2864 CastSpell(this, spell_id, true);
2866 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2867 else if (IsPassiveSpell(spell_id))
2869 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2870 CastSpell(this, spell_id, true);
2872 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2874 CastSpell(this, spell_id, true);
2875 return false;
2878 // update used talent points count
2879 m_usedTalentCount += talentCost;
2881 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2882 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2884 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2885 SetFreePrimaryProffesions(freeProfs-1);
2888 // add dependent skills
2889 uint16 maxskill = GetMaxSkillValueForLevel();
2891 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2893 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2894 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2896 if(spellLearnSkill)
2898 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2899 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2901 if(skill_value < spellLearnSkill->value)
2902 skill_value = spellLearnSkill->value;
2904 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2906 if(skill_max_value < new_skill_max_value)
2907 skill_max_value = new_skill_max_value;
2909 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2911 else
2913 // not ranked skills
2914 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2916 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2917 if(!pSkill)
2918 continue;
2920 if(HasSkill(pSkill->id))
2921 continue;
2923 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2924 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2925 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2927 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2929 case SKILL_RANGE_LANGUAGE:
2930 SetSkill(pSkill->id, 300, 300 );
2931 break;
2932 case SKILL_RANGE_LEVEL:
2933 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2934 break;
2935 case SKILL_RANGE_MONO:
2936 SetSkill(pSkill->id, 1, 1 );
2937 break;
2938 default:
2939 break;
2945 // learn dependent spells
2946 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2947 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2949 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2951 if(!itr2->second.autoLearned)
2953 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2954 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2955 else // at normal learning
2956 learnSpell(itr2->second.spell,true);
2960 if(!GetSession()->PlayerLoading())
2962 // not ranked skills
2963 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2965 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
2966 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
2969 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
2972 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2973 return active && !disabled && !superceded_old;
2976 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
2978 bool need_cast = false;
2980 switch(spellInfo->Id)
2982 // some spells not have stance data expacted cast at form change or present
2983 case 5420: need_cast = (m_form == FORM_TREE); break;
2984 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
2985 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
2986 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
2987 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
2988 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
2989 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
2990 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
2991 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2992 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
2993 // another spells have proper stance data
2994 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
2997 //Check CasterAuraStates
2998 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3001 void Player::learnSpell(uint32 spell_id, bool dependent)
3003 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3005 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3006 bool active = disabled ? itr->second->active : true;
3008 bool learning = addSpell(spell_id,active,true,dependent,false);
3010 // learn all disabled higher ranks (recursive)
3011 if(disabled)
3013 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3014 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3016 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3017 if (iter != m_spells.end() && iter->second->disabled)
3018 learnSpell(i->second,false);
3022 // prevent duplicated entires in spell book, also not send if not in world (loading)
3023 if(!learning || !IsInWorld ())
3024 return;
3026 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3027 data << uint32(spell_id);
3028 GetSession()->SendPacket(&data);
3031 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3033 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3034 if (itr == m_spells.end())
3035 return;
3037 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3038 return;
3040 // unlearn non talent higher ranks (recursive)
3041 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3042 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3043 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3044 removeSpell(itr2->second,disabled);
3046 bool cur_active = itr->second->active;
3047 bool cur_dependent = itr->second->dependent;
3049 if (disabled)
3051 itr->second->disabled = disabled;
3052 if(itr->second->state != PLAYERSPELL_NEW)
3053 itr->second->state = PLAYERSPELL_CHANGED;
3055 else
3057 if(itr->second->state == PLAYERSPELL_NEW)
3059 delete itr->second;
3060 m_spells.erase(itr);
3062 else
3063 itr->second->state = PLAYERSPELL_REMOVED;
3066 RemoveAurasDueToSpell(spell_id);
3068 // remove pet auras
3069 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3070 RemovePetAura(petSpell);
3072 // free talent points
3073 uint32 talentCosts = GetTalentSpellCost(spell_id);
3074 if(talentCosts > 0)
3076 if(talentCosts < m_usedTalentCount)
3077 m_usedTalentCount -= talentCosts;
3078 else
3079 m_usedTalentCount = 0;
3082 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3083 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3085 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
3086 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3087 SetFreePrimaryProffesions(freeProfs);
3090 // remove dependent skill
3091 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3092 if(spellLearnSkill)
3094 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3095 if(!prev_spell) // first rank, remove skill
3096 SetSkill(spellLearnSkill->skill,0,0);
3097 else
3099 // search prev. skill setting by spell ranks chain
3100 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3101 while(!prevSkill && prev_spell)
3103 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3104 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3107 if(!prevSkill) // not found prev skill setting, remove skill
3108 SetSkill(spellLearnSkill->skill,0,0);
3109 else // set to prev. skill setting values
3111 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3112 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3114 if(skill_value > prevSkill->value)
3115 skill_value = prevSkill->value;
3117 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3119 if(skill_max_value > new_skill_max_value)
3120 skill_max_value = new_skill_max_value;
3122 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3127 else
3129 // not ranked skills
3130 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3131 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3133 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3135 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3136 if(!pSkill)
3137 continue;
3139 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3140 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3141 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3143 // not reset skills for professions and racial abilities
3144 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3145 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3146 continue;
3148 SetSkill(pSkill->id, 0, 0 );
3153 // remove dependent spells
3154 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3155 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3157 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3158 removeSpell(itr2->second.spell, disabled);
3160 // activate lesser rank in spellbook/action bar, and cast it if need
3161 bool prev_activate = false;
3163 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3165 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3167 // if talent then lesser rank also talent and need learn
3168 if(talentCosts)
3169 learnSpell (prev_id,false);
3170 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3171 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3173 // need manually update dependence state (learn spell ignore like attempts)
3174 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3175 if (prev_itr != m_spells.end())
3177 if(prev_itr->second->dependent != cur_dependent)
3179 prev_itr->second->dependent = cur_dependent;
3180 if(prev_itr->second->state != PLAYERSPELL_NEW)
3181 prev_itr->second->state = PLAYERSPELL_CHANGED;
3184 // now re-learn if need re-activate
3185 if(cur_active && !prev_itr->second->active)
3187 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3189 if(update_action_bar_for_low_rank)
3191 // downgrade spell ranks in spellbook and action bar
3192 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3193 data << uint32(spell_id);
3194 data << uint32(prev_id);
3195 GetSession()->SendPacket( &data );
3196 prev_activate = true;
3204 // remove from spell book if not replaced by lesser rank
3205 if(!prev_activate)
3207 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3208 data << uint32(spell_id);
3209 GetSession()->SendPacket(&data);
3213 void Player::RemoveArenaSpellCooldowns()
3215 // remove cooldowns on spells that has < 15 min CD
3216 SpellCooldowns::iterator itr, next;
3217 // iterate spell cooldowns
3218 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3220 next = itr;
3221 ++next;
3222 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3223 // check if spellentry is present and if the cooldown is less than 15 mins
3224 if( entry &&
3225 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3226 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3228 // notify player
3229 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3230 data << uint32(itr->first);
3231 data << uint64(GetGUID());
3232 GetSession()->SendPacket(&data);
3233 // remove cooldown
3234 m_spellCooldowns.erase(itr);
3239 void Player::RemoveAllSpellCooldown()
3241 if(!m_spellCooldowns.empty())
3243 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3245 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3246 data << uint32(itr->first);
3247 data << uint64(GetGUID());
3248 GetSession()->SendPacket(&data);
3250 m_spellCooldowns.clear();
3254 void Player::_LoadSpellCooldowns(QueryResult *result)
3256 // some cooldowns can be already set at aura loading...
3258 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3260 if(result)
3262 time_t curTime = time(NULL);
3266 Field *fields = result->Fetch();
3268 uint32 spell_id = fields[0].GetUInt32();
3269 uint32 item_id = fields[1].GetUInt32();
3270 time_t db_time = (time_t)fields[2].GetUInt64();
3272 if(!sSpellStore.LookupEntry(spell_id))
3274 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3275 continue;
3278 // skip outdated cooldown
3279 if(db_time <= curTime)
3280 continue;
3282 AddSpellCooldown(spell_id, item_id, db_time);
3284 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3286 while( result->NextRow() );
3288 delete result;
3292 void Player::_SaveSpellCooldowns()
3294 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3296 time_t curTime = time(NULL);
3297 time_t infTime = curTime + MONTH/2;
3299 // remove outdated and save active
3300 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3302 if(itr->second.end <= curTime)
3303 m_spellCooldowns.erase(itr++);
3304 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3306 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3307 ++itr;
3309 else
3310 ++itr;
3314 uint32 Player::resetTalentsCost() const
3316 // The first time reset costs 1 gold
3317 if(m_resetTalentsCost < 1*GOLD)
3318 return 1*GOLD;
3319 // then 5 gold
3320 else if(m_resetTalentsCost < 5*GOLD)
3321 return 5*GOLD;
3322 // After that it increases in increments of 5 gold
3323 else if(m_resetTalentsCost < 10*GOLD)
3324 return 10*GOLD;
3325 else
3327 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3328 if(months > 0)
3330 // This cost will be reduced by a rate of 5 gold per month
3331 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3332 // to a minimum of 10 gold.
3333 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3335 else
3337 // After that it increases in increments of 5 gold
3338 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3339 // until it hits a cap of 50 gold.
3340 if(new_cost > 50*GOLD)
3341 new_cost = 50*GOLD;
3342 return new_cost;
3347 bool Player::resetTalents(bool no_cost)
3349 // not need after this call
3350 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3352 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3353 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3356 uint32 talentPointsForLevel = CalculateTalentsPoints();
3358 if (m_usedTalentCount == 0)
3360 SetFreeTalentPoints(talentPointsForLevel);
3361 return false;
3364 uint32 cost = 0;
3366 if(!no_cost)
3368 cost = resetTalentsCost();
3370 if (GetMoney() < cost)
3372 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3373 return false;
3377 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3379 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3381 if (!talentInfo) continue;
3383 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3385 if(!talentTabInfo)
3386 continue;
3388 // unlearn only talents for character class
3389 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3390 // to prevent unexpected lost normal learned spell skip another class talents
3391 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3392 continue;
3394 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3396 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3398 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3400 ++itr;
3401 continue;
3404 // remove learned spells (all ranks)
3405 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3407 // unlearn if first rank is talent or learned by talent
3408 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3410 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3411 itr = GetSpellMap().begin();
3412 continue;
3414 else
3415 ++itr;
3420 SetFreeTalentPoints(talentPointsForLevel);
3422 if(!no_cost)
3424 ModifyMoney(-(int32)cost);
3425 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3426 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3428 m_resetTalentsCost = cost;
3429 m_resetTalentsTime = time(NULL);
3432 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3433 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3435 if(m_canTitanGrip)
3437 m_canTitanGrip = false;
3438 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3439 AutoUnequipOffhandIfNeed();
3442 return true;
3445 Mail* Player::GetMail(uint32 id)
3447 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3449 if ((*itr)->messageID == id)
3451 return (*itr);
3454 return NULL;
3457 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3459 if(target == this)
3461 Object::_SetCreateBits(updateMask, target);
3463 else
3465 for(uint16 index = 0; index < m_valuesCount; index++)
3467 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3468 updateMask->SetBit(index);
3473 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3475 if(target == this)
3477 Object::_SetUpdateBits(updateMask, target);
3479 else
3481 Object::_SetUpdateBits(updateMask, target);
3482 *updateMask &= updateVisualBits;
3486 void Player::InitVisibleBits()
3488 updateVisualBits.SetCount(PLAYER_END);
3490 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3491 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3492 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3493 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3494 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3495 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3496 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3497 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3498 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3499 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3500 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3501 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3502 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3503 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3504 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3505 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3506 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3507 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3508 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3509 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3510 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3511 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3512 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3513 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3514 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3515 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3516 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3517 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3518 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3519 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3520 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3521 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3522 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3523 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3524 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3525 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3526 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3527 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3528 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3529 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3530 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3531 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3532 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3533 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3534 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3535 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3536 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3537 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3538 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3539 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3540 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3541 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3542 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3543 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3544 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3546 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3547 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3548 updateVisualBits.SetBit(PLAYER_FLAGS);
3549 updateVisualBits.SetBit(PLAYER_GUILDID);
3550 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3551 updateVisualBits.SetBit(PLAYER_BYTES);
3552 updateVisualBits.SetBit(PLAYER_BYTES_2);
3553 updateVisualBits.SetBit(PLAYER_BYTES_3);
3554 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3555 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3557 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3558 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3559 updateVisualBits.SetBit(i);
3561 // Players visible items are not inventory stuff
3562 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3564 uint32 offset = i * 2;
3566 // item entry
3567 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3568 // enchant
3569 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3572 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3575 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3577 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3579 if(m_items[i] == NULL)
3580 continue;
3582 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3585 if(target == this)
3587 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3589 if(m_items[i] == NULL)
3590 continue;
3592 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3594 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3596 if(m_items[i] == NULL)
3597 continue;
3599 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3603 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3606 void Player::DestroyForPlayer( Player *target ) const
3608 Unit::DestroyForPlayer( target );
3610 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3612 if(m_items[i] == NULL)
3613 continue;
3615 m_items[i]->DestroyForPlayer( target );
3618 if(target == this)
3620 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3622 if(m_items[i] == NULL)
3623 continue;
3625 m_items[i]->DestroyForPlayer( target );
3627 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3629 if(m_items[i] == NULL)
3630 continue;
3632 m_items[i]->DestroyForPlayer( target );
3637 bool Player::HasSpell(uint32 spell) const
3639 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3640 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3641 !itr->second->disabled);
3644 bool Player::HasActiveSpell(uint32 spell) const
3646 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3647 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3648 itr->second->active && !itr->second->disabled);
3651 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3653 if (!trainer_spell)
3654 return TRAINER_SPELL_RED;
3656 if (!trainer_spell->learnedSpell)
3657 return TRAINER_SPELL_RED;
3659 // known spell
3660 if(HasSpell(trainer_spell->learnedSpell))
3661 return TRAINER_SPELL_GRAY;
3663 // check race/class requirement
3664 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3665 return TRAINER_SPELL_RED;
3667 // check level requirement
3668 if(getLevel() < trainer_spell->reqLevel)
3669 return TRAINER_SPELL_RED;
3671 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3673 // check prev.rank requirement
3674 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3675 return TRAINER_SPELL_RED;
3677 // check additional spell requirement
3678 if(spell_chain->req && !HasSpell(spell_chain->req))
3679 return TRAINER_SPELL_RED;
3682 // check skill requirement
3683 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3684 return TRAINER_SPELL_RED;
3686 // exist, already checked at loading
3687 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3689 // secondary prof. or not prof. spell
3690 uint32 skill = spell->EffectMiscValue[1];
3692 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3693 return TRAINER_SPELL_GREEN;
3695 // check primary prof. limit
3696 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3697 return TRAINER_SPELL_GREEN_DISABLED;
3699 return TRAINER_SPELL_GREEN;
3702 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3704 uint32 guid = GUID_LOPART(playerguid);
3706 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3707 // bones will be deleted by corpse/bones deleting thread shortly
3708 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3710 // remove from guild
3711 uint32 guildId = GetGuildIdFromDB(playerguid);
3712 if(guildId != 0)
3714 Guild* guild = objmgr.GetGuildById(guildId);
3715 if(guild)
3716 guild->DelMember(guid);
3719 // remove from arena teams
3720 LeaveAllArenaTeams(playerguid);
3722 // the player was uninvited already on logout so just remove from group
3723 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3724 if(resultGroup)
3726 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3727 delete resultGroup;
3728 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3729 if(group)
3731 RemoveFromGroup(group, playerguid);
3735 // remove signs from petitions (also remove petitions if owner);
3736 RemovePetitionsAndSigns(playerguid, 10);
3738 // return back all mails with COD and Item 0 1 2 3 4 5 6
3739 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);
3740 if(resultMail)
3744 Field *fields = resultMail->Fetch();
3746 uint32 mail_id = fields[0].GetUInt32();
3747 uint16 mailTemplateId= fields[1].GetUInt16();
3748 uint32 sender = fields[2].GetUInt32();
3749 std::string subject = fields[3].GetCppString();
3750 uint32 itemTextId = fields[4].GetUInt32();
3751 uint32 money = fields[5].GetUInt32();
3752 bool has_items = fields[6].GetBool();
3754 //we can return mail now
3755 //so firstly delete the old one
3756 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3758 MailItemsInfo mi;
3759 if(has_items)
3761 // data needs to be at first place for Item::LoadFromDB
3762 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);
3763 if(resultItems)
3767 Field *fields2 = resultItems->Fetch();
3769 uint32 item_guidlow = fields2[1].GetUInt32();
3770 uint32 item_template = fields2[2].GetUInt32();
3772 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3773 if(!itemProto)
3775 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3776 continue;
3779 Item *pItem = NewItemOrBag(itemProto);
3780 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3782 pItem->FSetState(ITEM_REMOVED);
3783 pItem->SaveToDB(); // it also deletes item object !
3784 continue;
3787 mi.AddItem(item_guidlow, item_template, pItem);
3789 while (resultItems->NextRow());
3791 delete resultItems;
3795 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3797 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3799 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3801 while (resultMail->NextRow());
3803 delete resultMail;
3806 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3807 // Get guids of character's pets, will deleted in transaction
3808 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3810 // NOW we can finally clear other DB data related to character
3811 CharacterDatabase.BeginTransaction();
3812 if (resultPets)
3816 Field *fields3 = resultPets->Fetch();
3817 uint32 petguidlow = fields3[0].GetUInt32();
3818 Pet::DeleteFromDB(petguidlow);
3819 } while (resultPets->NextRow());
3820 delete resultPets;
3823 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3824 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3825 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3826 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3827 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3828 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3829 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3830 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3831 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3832 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3833 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3834 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3835 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3836 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3837 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3838 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3839 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3840 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3841 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3842 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3843 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3844 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3845 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
3846 CharacterDatabase.CommitTransaction();
3848 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3849 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3852 void Player::SetMovement(PlayerMovementType pType)
3854 WorldPacket data;
3855 switch(pType)
3857 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3858 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3859 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3860 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3861 default:
3862 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3863 return;
3865 data.append(GetPackGUID());
3866 data << uint32(0);
3867 GetSession()->SendPacket( &data );
3870 /* Preconditions:
3871 - a resurrectable corpse must not be loaded for the player (only bones)
3872 - the player must be in world
3874 void Player::BuildPlayerRepop()
3876 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3877 data.append(GetPackGUID());
3878 GetSession()->SendPacket(&data);
3880 if(getRace() == RACE_NIGHTELF)
3881 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)
3882 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3884 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3885 // there must be SMSG.STOP_MIRROR_TIMER
3886 // there we must send 888 opcode
3888 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3889 if(GetCorpse())
3891 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3892 assert(false);
3895 // create a corpse and place it at the player's location
3896 CreateCorpse();
3897 Corpse *corpse = GetCorpse();
3898 if(!corpse)
3900 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3901 return;
3903 GetMap()->Add(corpse);
3905 // convert player body to ghost
3906 SetHealth( 1 );
3908 SetMovement(MOVE_WATER_WALK);
3909 if(!GetSession()->isLogingOut())
3910 SetMovement(MOVE_UNROOT);
3912 // BG - remove insignia related
3913 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3915 SendCorpseReclaimDelay();
3917 // to prevent cheating
3918 corpse->ResetGhostTime();
3920 StopMirrorTimers(); //disable timers(bars)
3922 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3924 // set and clear other
3925 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3928 void Player::SendDelayResponse(const uint32 ml_seconds)
3930 //FIXME: is this delay time arg really need? 50msec by default in code
3931 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3932 data << (uint32)time(NULL);
3933 data << (uint32)0;
3934 GetSession()->SendPacket( &data );
3937 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3939 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3940 data << uint32(-1);
3941 data << float(0);
3942 data << float(0);
3943 data << float(0);
3944 GetSession()->SendPacket(&data);
3946 // speed change, land walk
3948 // remove death flag + set aura
3949 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3950 if(getRace() == RACE_NIGHTELF)
3951 RemoveAurasDueToSpell(20584); // speed bonuses
3952 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3954 setDeathState(ALIVE);
3956 SetMovement(MOVE_LAND_WALK);
3957 SetMovement(MOVE_UNROOT);
3959 m_deathTimer = 0;
3961 // set health/powers (0- will be set in caller)
3962 if(restore_percent>0.0f)
3964 SetHealth(uint32(GetMaxHealth()*restore_percent));
3965 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3966 SetPower(POWER_RAGE, 0);
3967 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3970 // trigger update zone for alive state zone updates
3971 uint32 newzone, newarea;
3972 GetZoneAndAreaId(newzone,newarea);
3973 UpdateZone(newzone,newarea);
3975 // update visibility
3976 ObjectAccessor::UpdateVisibilityForPlayer(this);
3978 if(!applySickness)
3979 return;
3981 //Characters from level 1-10 are not affected by resurrection sickness.
3982 //Characters from level 11-19 will suffer from one minute of sickness
3983 //for each level they are above 10.
3984 //Characters level 20 and up suffer from ten minutes of sickness.
3985 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3987 if(int32(getLevel()) >= startLevel)
3989 // set resurrection sickness
3990 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3992 // not full duration
3993 if(int32(getLevel()) < startLevel+9)
3995 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3997 for(int i =0; i < 3; ++i)
3999 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4001 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4002 Aur->SendAuraUpdate(false);
4009 void Player::KillPlayer()
4011 SetMovement(MOVE_ROOT);
4013 StopMirrorTimers(); //disable timers(bars)
4015 setDeathState(CORPSE);
4016 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4018 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4019 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4021 // 6 minutes until repop at graveyard
4022 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4024 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4026 // don't create corpse at this moment, player might be falling
4028 // update visibility
4029 ObjectAccessor::UpdateObjectVisibility(this);
4032 void Player::CreateCorpse()
4034 // prevent existence 2 corpse for player
4035 SpawnCorpseBones();
4037 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4039 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4040 SetPvPDeath(false);
4042 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4044 delete corpse;
4045 return;
4048 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4049 _pb = GetUInt32Value(PLAYER_BYTES);
4050 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4052 uint8 race = (uint8)(_uf);
4053 uint8 skin = (uint8)(_pb);
4054 uint8 face = (uint8)(_pb >> 8);
4055 uint8 hairstyle = (uint8)(_pb >> 16);
4056 uint8 haircolor = (uint8)(_pb >> 24);
4057 uint8 facialhair = (uint8)(_pb2);
4059 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4060 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4062 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4063 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4065 uint32 flags = CORPSE_FLAG_UNK2;
4066 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4067 flags |= CORPSE_FLAG_HIDE_HELM;
4068 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4069 flags |= CORPSE_FLAG_HIDE_CLOAK;
4070 if(InBattleGround() && !InArena())
4071 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4072 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4074 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4076 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4078 uint32 iDisplayID;
4079 uint16 iIventoryType;
4080 uint32 _cfi;
4081 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4083 if(m_items[i])
4085 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4086 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4088 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4089 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4093 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4094 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4095 assert(entry);
4096 if(entry->map_type != MAP_BATTLEGROUND)
4097 corpse->SaveToDB();
4099 // register for player, but not show
4100 ObjectAccessor::Instance().AddCorpse(corpse);
4103 void Player::SpawnCorpseBones()
4105 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4106 SaveToDB(); // prevent loading as ghost without corpse
4109 Corpse* Player::GetCorpse() const
4111 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4114 void Player::DurabilityLossAll(double percent, bool inventory)
4116 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4117 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4118 DurabilityLoss(pItem,percent);
4120 if(inventory)
4122 // bags not have durability
4123 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4125 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4126 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4127 DurabilityLoss(pItem,percent);
4129 // keys not have durability
4130 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4132 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4133 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4134 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4135 if(Item* pItem = GetItemByPos( i, j ))
4136 DurabilityLoss(pItem,percent);
4140 void Player::DurabilityLoss(Item* item, double percent)
4142 if(!item )
4143 return;
4145 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4147 if(!pMaxDurability)
4148 return;
4150 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4152 if(pDurabilityLoss < 1 )
4153 pDurabilityLoss = 1;
4155 DurabilityPointsLoss(item,pDurabilityLoss);
4158 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4160 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4161 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4162 DurabilityPointsLoss(pItem,points);
4164 if(inventory)
4166 // bags not have durability
4167 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4169 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4170 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4171 DurabilityPointsLoss(pItem,points);
4173 // keys not have durability
4174 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4176 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4177 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4178 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4179 if(Item* pItem = GetItemByPos( i, j ))
4180 DurabilityPointsLoss(pItem,points);
4184 void Player::DurabilityPointsLoss(Item* item, int32 points)
4186 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4187 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4188 int32 pNewDurability = pOldDurability - points;
4190 if (pNewDurability < 0)
4191 pNewDurability = 0;
4192 else if (pNewDurability > pMaxDurability)
4193 pNewDurability = pMaxDurability;
4195 if (pOldDurability != pNewDurability)
4197 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4198 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4199 _ApplyItemMods(item,item->GetSlot(), false);
4201 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4203 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4204 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4205 _ApplyItemMods(item,item->GetSlot(), true);
4207 item->SetState(ITEM_CHANGED, this);
4211 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4213 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4214 DurabilityPointsLoss(pItem,1);
4217 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4219 uint32 TotalCost = 0;
4220 // equipped, backpack, bags itself
4221 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4222 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4224 // bank, buyback and keys not repaired
4226 // items in inventory bags
4227 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4228 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4229 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4230 return TotalCost;
4233 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4235 Item* item = GetItemByPos(pos);
4237 uint32 TotalCost = 0;
4238 if(!item)
4239 return TotalCost;
4241 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4242 if(!maxDurability)
4243 return TotalCost;
4245 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4247 if(cost)
4249 uint32 LostDurability = maxDurability - curDurability;
4250 if(LostDurability>0)
4252 ItemPrototype const *ditemProto = item->GetProto();
4254 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4255 if(!dcost)
4257 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4258 return TotalCost;
4261 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4262 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4263 if(!dQualitymodEntry)
4265 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4266 return TotalCost;
4269 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4270 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4272 costs = uint32(costs * discountMod);
4274 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4275 costs = 1;
4277 if (guildBank)
4279 if (GetGuildId()==0)
4281 DEBUG_LOG("You are not member of a guild");
4282 return TotalCost;
4285 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4286 if (!pGuild)
4287 return TotalCost;
4289 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4291 DEBUG_LOG("You do not have rights to withdraw for repairs");
4292 return TotalCost;
4295 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4297 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4298 return TotalCost;
4301 if (pGuild->GetGuildBankMoney() < costs)
4303 DEBUG_LOG("There is not enough money in bank");
4304 return TotalCost;
4307 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4308 TotalCost = costs;
4310 else if (GetMoney() < costs)
4312 DEBUG_LOG("You do not have enough money");
4313 return TotalCost;
4315 else
4316 ModifyMoney( -int32(costs) );
4320 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4321 item->SetState(ITEM_CHANGED, this);
4323 // reapply mods for total broken and repaired item if equipped
4324 if(IsEquipmentPos(pos) && !curDurability)
4325 _ApplyItemMods(item,pos & 255, true);
4326 return TotalCost;
4329 void Player::RepopAtGraveyard()
4331 // note: this can be called also when the player is alive
4332 // for example from WorldSession::HandleMovementOpcodes
4334 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4336 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4337 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4339 ResurrectPlayer(0.5f);
4340 SpawnCorpseBones();
4343 WorldSafeLocsEntry const *ClosestGrave = NULL;
4345 // Special handle for battleground maps
4346 if( BattleGround *bg = GetBattleGround() )
4347 ClosestGrave = bg->GetClosestGraveYard(this);
4348 else
4349 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4351 // stop countdown until repop
4352 m_deathTimer = 0;
4354 // if no grave found, stay at the current location
4355 // and don't show spirit healer location
4356 if(ClosestGrave)
4358 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4359 if(isDead()) // not send if alive, because it used in TeleportTo()
4361 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4362 data << ClosestGrave->map_id;
4363 data << ClosestGrave->x;
4364 data << ClosestGrave->y;
4365 data << ClosestGrave->z;
4366 GetSession()->SendPacket(&data);
4371 void Player::JoinedChannel(Channel *c)
4373 m_channels.push_back(c);
4376 void Player::LeftChannel(Channel *c)
4378 m_channels.remove(c);
4381 void Player::CleanupChannels()
4383 while(!m_channels.empty())
4385 Channel* ch = *m_channels.begin();
4386 m_channels.erase(m_channels.begin()); // remove from player's channel list
4387 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4388 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4389 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4392 sLog.outDebug("Player: channels cleaned up!");
4395 void Player::UpdateLocalChannels(uint32 newZone )
4397 if(m_channels.empty())
4398 return;
4400 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4401 if(!current_zone)
4402 return;
4404 ChannelMgr* cMgr = channelMgr(GetTeam());
4405 if(!cMgr)
4406 return;
4408 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4410 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4412 next = i; ++next;
4414 // skip non built-in channels
4415 if(!(*i)->IsConstant())
4416 continue;
4418 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4419 if(!ch)
4420 continue;
4422 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4423 continue;
4425 // new channel
4426 char new_channel_name_buf[100];
4427 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4428 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4430 if((*i)!=new_channel)
4432 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4434 // leave old channel
4435 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4436 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4437 LeftChannel(*i); // remove from player's channel list
4438 cMgr->LeftChannel(name); // delete if empty
4441 sLog.outDebug("Player: channels cleaned up!");
4444 void Player::LeaveLFGChannel()
4446 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4448 if((*i)->IsLFG())
4450 (*i)->Leave(GetGUID());
4451 break;
4456 void Player::UpdateDefense()
4458 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4460 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4462 // update dependent from defense skill part
4463 UpdateDefenseBonusesMod();
4467 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4469 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4471 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4472 return;
4475 float val = 1.0f;
4477 switch(modType)
4479 case FLAT_MOD:
4480 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4481 break;
4482 case PCT_MOD:
4483 if(amount <= -100.0f)
4484 amount = -200.0f;
4486 val = (100.0f + amount) / 100.0f;
4487 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4488 break;
4491 if(!CanModifyStats())
4492 return;
4494 switch(modGroup)
4496 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4497 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4498 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4499 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4500 default: break;
4504 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4506 if(modGroup >= BASEMOD_END || modType > MOD_END)
4508 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4509 return 0.0f;
4512 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4513 return 0.0f;
4515 return m_auraBaseMod[modGroup][modType];
4518 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4520 if(modGroup >= BASEMOD_END)
4522 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4523 return 0.0f;
4526 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4527 return 0.0f;
4529 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4532 uint32 Player::GetShieldBlockValue() const
4534 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4536 value = (value < 0) ? 0 : value;
4538 return uint32(value);
4541 float Player::GetMeleeCritFromAgility()
4543 uint32 level = getLevel();
4544 uint32 pclass = getClass();
4546 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4548 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4549 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4550 if (critBase==NULL || critRatio==NULL)
4551 return 0.0f;
4553 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4554 return crit*100.0f;
4557 float Player::GetDodgeFromAgility()
4559 // Table for base dodge values
4560 float dodge_base[MAX_CLASSES] = {
4561 0.0075f, // Warrior
4562 0.00652f, // Paladin
4563 -0.0545f, // Hunter
4564 -0.0059f, // Rogue
4565 0.03183f, // Priest
4566 0.0114f, // DK
4567 0.0167f, // Shaman
4568 0.034575f, // Mage
4569 0.02011f, // Warlock
4570 0.0f, // ??
4571 -0.0187f // Druid
4573 // Crit/agility to dodge/agility coefficient multipliers
4574 float crit_to_dodge[MAX_CLASSES] = {
4575 1.1f, // Warrior
4576 1.0f, // Paladin
4577 1.6f, // Hunter
4578 2.0f, // Rogue
4579 1.0f, // Priest
4580 1.0f, // DK?
4581 1.0f, // Shaman
4582 1.0f, // Mage
4583 1.0f, // Warlock
4584 0.0f, // ??
4585 1.7f // Druid
4588 uint32 level = getLevel();
4589 uint32 pclass = getClass();
4591 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4593 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4594 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4595 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4596 return 0.0f;
4598 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4599 return dodge*100.0f;
4602 float Player::GetSpellCritFromIntellect()
4604 uint32 level = getLevel();
4605 uint32 pclass = getClass();
4607 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4609 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4610 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4611 if (critBase==NULL || critRatio==NULL)
4612 return 0.0f;
4614 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4615 return crit*100.0f;
4618 float Player::GetRatingCoefficient(CombatRating cr) const
4620 uint32 level = getLevel();
4622 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4624 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4625 if (Rating == NULL)
4626 return 1.0f; // By default use minimum coefficient (not must be called)
4628 return Rating->ratio;
4631 float Player::GetRatingBonusValue(CombatRating cr) const
4633 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4636 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4638 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4639 if (melee>33.0f) melee = 33.0f;
4640 return uint32 (melee * damage /100.0f);
4643 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4645 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4646 if (ranged>33.0f) ranged=33.0f;
4647 return uint32 (ranged * damage /100.0f);
4650 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4652 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4653 // In wow script resilience limited to 33%
4654 if (spell>33.0f)
4655 spell = 33.0f;
4656 return uint32 (spell * damage / 100.0f);
4659 uint32 Player::GetDotDamageReduction(uint32 damage) const
4661 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4662 // Dot resilience not limited (limit it by 100%)
4663 if (spellDot > 100.0f)
4664 spellDot = 100.0f;
4665 return uint32 (spellDot * damage / 100.0f);
4668 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4670 switch (attType)
4672 case BASE_ATTACK:
4673 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4674 case OFF_ATTACK:
4675 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4676 default:
4677 break;
4679 return 0.0f;
4682 float Player::OCTRegenHPPerSpirit()
4684 uint32 level = getLevel();
4685 uint32 pclass = getClass();
4687 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4689 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4690 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4691 if (baseRatio==NULL || moreRatio==NULL)
4692 return 0.0f;
4694 // Formula from PaperDollFrame script
4695 float spirit = GetStat(STAT_SPIRIT);
4696 float baseSpirit = spirit;
4697 if (baseSpirit>50) baseSpirit = 50;
4698 float moreSpirit = spirit - baseSpirit;
4699 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4700 return regen;
4703 float Player::OCTRegenMPPerSpirit()
4705 uint32 level = getLevel();
4706 uint32 pclass = getClass();
4708 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4710 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4711 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4712 if (moreRatio==NULL)
4713 return 0.0f;
4715 // Formula get from PaperDollFrame script
4716 float spirit = GetStat(STAT_SPIRIT);
4717 float regen = spirit * moreRatio->ratio;
4718 return regen;
4721 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4723 m_baseRatingValue[cr]+=(apply ? value : -value);
4725 int32 amount = uint32(m_baseRatingValue[cr]);
4726 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4727 // stat used stored in miscValueB for this aura
4728 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4729 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4730 if ((*i)->GetMiscValue() & (1<<cr))
4731 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4732 if (amount < 0)
4733 amount = 0;
4734 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4736 float RatingCoeffecient = GetRatingCoefficient(cr);
4737 float RatingChange = 0.0f;
4739 bool affectStats = CanModifyStats();
4741 switch (cr)
4743 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4744 case CR_DEFENSE_SKILL:
4745 UpdateDefenseBonusesMod();
4746 break;
4747 case CR_DODGE:
4748 UpdateDodgePercentage();
4749 break;
4750 case CR_PARRY:
4751 UpdateParryPercentage();
4752 break;
4753 case CR_BLOCK:
4754 UpdateBlockPercentage();
4755 break;
4756 case CR_HIT_MELEE:
4757 UpdateMeleeHitChances();
4758 break;
4759 case CR_HIT_RANGED:
4760 UpdateRangedHitChances();
4761 break;
4762 case CR_HIT_SPELL:
4763 UpdateSpellHitChances();
4764 break;
4765 case CR_CRIT_MELEE:
4766 if(affectStats)
4768 UpdateCritPercentage(BASE_ATTACK);
4769 UpdateCritPercentage(OFF_ATTACK);
4771 break;
4772 case CR_CRIT_RANGED:
4773 if(affectStats)
4774 UpdateCritPercentage(RANGED_ATTACK);
4775 break;
4776 case CR_CRIT_SPELL:
4777 if(affectStats)
4778 UpdateAllSpellCritChances();
4779 break;
4780 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4781 case CR_HIT_TAKEN_RANGED:
4782 break;
4783 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4784 break;
4785 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4786 case CR_CRIT_TAKEN_RANGED:
4787 break;
4788 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4789 break;
4790 case CR_HASTE_MELEE:
4791 RatingChange = value / RatingCoeffecient;
4792 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4793 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4794 break;
4795 case CR_HASTE_RANGED:
4796 RatingChange = value / RatingCoeffecient;
4797 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4798 break;
4799 case CR_HASTE_SPELL:
4800 RatingChange = value / RatingCoeffecient;
4801 ApplyCastTimePercentMod(RatingChange,apply);
4802 break;
4803 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4804 case CR_WEAPON_SKILL_OFFHAND:
4805 case CR_WEAPON_SKILL_RANGED:
4806 break;
4807 case CR_EXPERTISE:
4808 if(affectStats)
4810 UpdateExpertise(BASE_ATTACK);
4811 UpdateExpertise(OFF_ATTACK);
4813 break;
4814 case CR_ARMOR_PENETRATION:
4815 break;
4819 void Player::SetRegularAttackTime()
4821 for(int i = 0; i < MAX_ATTACK; ++i)
4823 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4824 if(tmpitem && !tmpitem->IsBroken())
4826 ItemPrototype const *proto = tmpitem->GetProto();
4827 if(proto->Delay)
4828 SetAttackTime(WeaponAttackType(i), proto->Delay);
4829 else
4830 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4835 //skill+step, checking for max value
4836 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4838 if(!skill_id)
4839 return false;
4841 uint16 i=0;
4842 for (; i < PLAYER_MAX_SKILLS; ++i)
4843 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4844 break;
4846 if(i>=PLAYER_MAX_SKILLS)
4847 return false;
4849 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4850 uint32 value = SKILL_VALUE(data);
4851 uint32 max = SKILL_MAX(data);
4853 if ((!max) || (!value) || (value >= max))
4854 return false;
4856 if (value*512 < max*urand(0,512))
4858 uint32 new_value = value+step;
4859 if(new_value > max)
4860 new_value = max;
4862 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4863 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4864 return true;
4867 return false;
4870 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4872 if ( SkillValue >= GrayLevel )
4873 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4874 if ( SkillValue >= GreenLevel )
4875 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4876 if ( SkillValue >= YellowLevel )
4877 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4878 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4881 bool Player::UpdateCraftSkill(uint32 spellid)
4883 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4885 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4886 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4888 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4890 if(_spell_idx->second->skillId)
4892 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4894 // Alchemy Discoveries here
4895 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4896 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4898 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4899 learnSpell(discoveredSpell,false);
4902 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4904 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4905 _spell_idx->second->max_value,
4906 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4907 _spell_idx->second->min_value),
4908 craft_skill_gain);
4911 return false;
4914 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4916 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4918 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4920 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4921 switch (SkillId)
4923 case SKILL_HERBALISM:
4924 case SKILL_LOCKPICKING:
4925 case SKILL_JEWELCRAFTING:
4926 case SKILL_INSCRIPTION:
4927 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4928 case SKILL_SKINNING:
4929 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4930 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4931 else
4932 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4933 case SKILL_MINING:
4934 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4935 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4936 else
4937 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4939 return false;
4942 bool Player::UpdateFishingSkill()
4944 sLog.outDebug("UpdateFishingSkill");
4946 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4948 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4950 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4952 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4955 // levels sync. with spell requirement for skill levels to learn
4956 // bonus abilities in sSkillLineAbilityStore
4957 // Used only to avoid scan DBC at each skill grow
4958 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
4960 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4962 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4963 if ( !SkillId )
4964 return false;
4966 if(Chance <= 0) // speedup in 0 chance case
4968 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4969 return false;
4972 uint16 i=0;
4973 for (; i < PLAYER_MAX_SKILLS; ++i)
4974 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4975 if ( i >= PLAYER_MAX_SKILLS )
4976 return false;
4978 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4979 uint16 SkillValue = SKILL_VALUE(data);
4980 uint16 MaxValue = SKILL_MAX(data);
4982 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4983 return false;
4985 int32 Roll = irand(1,1000);
4987 if ( Roll <= Chance )
4989 uint32 new_value = SkillValue+step;
4990 if(new_value > MaxValue)
4991 new_value = MaxValue;
4993 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4994 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
4996 if((SkillValue < *bsl && new_value >= *bsl))
4998 learnSkillRewardedSpells( SkillId, new_value);
4999 break;
5002 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5003 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5004 return true;
5007 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5008 return false;
5011 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5013 // no skill gain in pvp
5014 Unit *pVictim = getVictim();
5015 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5016 return;
5018 if(IsInFeralForm())
5019 return; // always maximized SKILL_FERAL_COMBAT in fact
5021 if(m_form == FORM_TREE)
5022 return; // use weapon but not skill up
5024 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5026 switch(attType)
5028 case BASE_ATTACK:
5030 Item *tmpitem = GetWeaponForAttack(attType,true);
5032 if (!tmpitem)
5033 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5034 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5035 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5036 break;
5038 case OFF_ATTACK:
5039 case RANGED_ATTACK:
5041 Item *tmpitem = GetWeaponForAttack(attType,true);
5042 if (tmpitem)
5043 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5044 break;
5047 UpdateAllCritPercentages();
5050 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5052 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5053 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5054 uint32 moblevel = pVictim->getLevelForTarget(this);
5055 if(moblevel < greylevel)
5056 return;
5058 if (moblevel > plevel + 5)
5059 moblevel = plevel + 5;
5061 uint32 lvldif = moblevel - greylevel;
5062 if(lvldif < 3)
5063 lvldif = 3;
5065 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5066 if(skilldif <= 0)
5067 return;
5069 float chance = float(3 * lvldif * skilldif) / plevel;
5070 if(!defence)
5072 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5073 chance *= 0.1f * GetStat(STAT_INTELLECT);
5076 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5078 if(roll_chance_f(chance))
5080 if(defence)
5081 UpdateDefense();
5082 else
5083 UpdateWeaponSkill(attType);
5085 else
5086 return;
5089 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5091 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5092 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5094 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5095 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5096 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5098 if(talent) // permanent bonus stored in high part
5099 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5100 else // temporary/item bonus stored in low part
5101 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5102 return;
5106 void Player::UpdateSkillsForLevel()
5108 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5109 uint32 maxSkill = GetMaxSkillValueForLevel();
5111 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5113 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5114 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5116 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5118 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5119 if(!pSkill)
5120 continue;
5122 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5123 continue;
5125 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5126 uint32 max = SKILL_MAX(data);
5127 uint32 val = SKILL_VALUE(data);
5129 /// update only level dependent max skill values
5130 if(max!=1)
5132 /// miximize skill always
5133 if(alwaysMaxSkill)
5134 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5135 /// update max skill value if current max skill not maximized
5136 else if(max != maxconfskill)
5137 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5142 void Player::UpdateSkillsToMaxSkillsForLevel()
5144 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5145 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5147 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5148 if( IsProfessionOrRidingSkill(pskill))
5149 continue;
5150 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5152 uint32 max = SKILL_MAX(data);
5154 if(max > 1)
5155 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5157 if(pskill == SKILL_DEFENSE)
5158 UpdateDefenseBonusesMod();
5162 // This functions sets a skill line value (and adds if doesn't exist yet)
5163 // To "remove" a skill line, set it's values to zero
5164 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5166 if(!id)
5167 return;
5169 uint16 i=0;
5170 for (; i < PLAYER_MAX_SKILLS; ++i)
5171 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5173 if(i<PLAYER_MAX_SKILLS) //has skill
5175 if(currVal)
5177 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5178 learnSkillRewardedSpells(id, currVal);
5179 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5180 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5182 else //remove
5184 // clear skill fields
5185 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5186 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5187 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5189 // remove all spells that related to this skill
5190 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5191 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5192 if (pAbility->skillId==id)
5193 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5196 else if(currVal) //add
5198 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5199 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5201 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5202 if(!pSkill)
5204 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5205 return;
5207 // enable unlearn button for primary professions only
5208 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5209 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5210 else
5211 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5212 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5214 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5216 // apply skill bonuses
5217 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5219 // temporary bonuses
5220 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5221 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5222 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5223 (*j)->ApplyModifier(true);
5225 // permanent bonuses
5226 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5227 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5228 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5229 (*j)->ApplyModifier(true);
5231 // Learn all spells for skill
5232 learnSkillRewardedSpells(id, currVal);
5233 return;
5238 bool Player::HasSkill(uint32 skill) const
5240 if(!skill)return false;
5241 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5243 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5245 return true;
5248 return false;
5251 uint16 Player::GetSkillValue(uint32 skill) const
5253 if(!skill)
5254 return 0;
5256 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5258 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5260 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5262 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5263 result += SKILL_TEMP_BONUS(bonus);
5264 result += SKILL_PERM_BONUS(bonus);
5265 return result < 0 ? 0 : result;
5268 return 0;
5271 uint16 Player::GetMaxSkillValue(uint32 skill) const
5273 if(!skill)return 0;
5274 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5276 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5278 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5280 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5281 result += SKILL_TEMP_BONUS(bonus);
5282 result += SKILL_PERM_BONUS(bonus);
5283 return result < 0 ? 0 : result;
5286 return 0;
5289 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5291 if(!skill)return 0;
5292 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5294 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5296 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5299 return 0;
5302 uint16 Player::GetBaseSkillValue(uint32 skill) const
5304 if(!skill)return 0;
5305 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5307 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5309 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5310 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5311 return result < 0 ? 0 : result;
5314 return 0;
5317 uint16 Player::GetPureSkillValue(uint32 skill) const
5319 if(!skill)return 0;
5320 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5322 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5324 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5327 return 0;
5330 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5332 if(!skill)
5333 return 0;
5335 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5337 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5339 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5343 return 0;
5346 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5348 if(!skill)
5349 return 0;
5351 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5353 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5355 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5359 return 0;
5362 void Player::SendInitialActionButtons() const
5364 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5366 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5367 data << uint8(0); // can be 0, 1, 2
5368 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5370 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5371 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5373 data << uint16(itr->second.action);
5374 data << uint8(itr->second.misc);
5375 data << uint8(itr->second.type);
5377 else
5379 data << uint32(0);
5383 GetSession()->SendPacket( &data );
5384 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5387 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5389 if(button >= MAX_ACTION_BUTTONS)
5391 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5392 return false;
5395 // check cheating with adding non-known spells to action bar
5396 if(type==ACTION_BUTTON_SPELL)
5398 if(!sSpellStore.LookupEntry(action))
5400 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5401 return false;
5404 if(!HasSpell(action))
5406 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5407 return false;
5411 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5413 if (buttonItr==m_actionButtons.end())
5414 { // just add new button
5415 m_actionButtons[button] = ActionButton(action,type,misc);
5417 else
5418 { // change state of current button
5419 ActionButtonUpdateState uState = buttonItr->second.uState;
5420 buttonItr->second = ActionButton(action,type,misc);
5421 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5424 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5425 return true;
5428 void Player::removeActionButton(uint8 button)
5430 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5431 if (buttonItr==m_actionButtons.end())
5432 return;
5434 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5435 m_actionButtons.erase(buttonItr); // new and not saved
5436 else
5437 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5439 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5442 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5444 // prevent crash when a bad coord is sent by the client
5445 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5447 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5448 return false;
5451 Map *m = GetMap();
5453 const float old_x = GetPositionX();
5454 const float old_y = GetPositionY();
5455 const float old_z = GetPositionZ();
5456 const float old_r = GetOrientation();
5458 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5460 if (teleport || old_x != x || old_y != y || old_z != z)
5461 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5462 else
5463 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5465 // move and update visible state if need
5466 m->PlayerRelocation(this, x, y, z, orientation);
5468 // reread after Map::Relocation
5469 m = GetMap();
5470 x = GetPositionX();
5471 y = GetPositionY();
5472 z = GetPositionZ();
5474 // group update
5475 if(GetGroup() && (old_x != x || old_y != y))
5476 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5479 // code block for underwater state update
5480 UpdateUnderwaterState(m, x, y, z);
5482 CheckExploreSystem();
5484 return true;
5487 void Player::SaveRecallPosition()
5489 m_recallMap = GetMapId();
5490 m_recallX = GetPositionX();
5491 m_recallY = GetPositionY();
5492 m_recallZ = GetPositionZ();
5493 m_recallO = GetOrientation();
5496 void Player::SendMessageToSet(WorldPacket *data, bool self)
5498 GetMap()->MessageBroadcast(this, data, self);
5501 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5503 GetMap()->MessageDistBroadcast(this, data, dist, self);
5506 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5508 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5511 void Player::SendDirectMessage(WorldPacket *data)
5513 GetSession()->SendPacket(data);
5516 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5518 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5519 data << uint32(CinematicSequenceId);
5520 SendDirectMessage(&data);
5523 void Player::SendMovieStart(uint32 MovieId)
5525 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5526 data << uint32(MovieId);
5527 SendDirectMessage(&data);
5530 void Player::CheckExploreSystem()
5532 if (!isAlive())
5533 return;
5535 if (isInFlight())
5536 return;
5538 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5539 if(areaFlag==0xffff)
5540 return;
5541 int offset = areaFlag / 32;
5543 if(offset >= 128)
5545 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);
5546 return;
5549 uint32 val = (uint32)(1 << (areaFlag % 32));
5550 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5552 if( !(currFields & val) )
5554 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5556 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5558 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5559 if(!p)
5561 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5563 else if(p->area_level > 0)
5565 uint32 area = p->ID;
5566 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5568 SendExplorationExperience(area,0);
5570 else
5572 int32 diff = int32(getLevel()) - p->area_level;
5573 uint32 XP = 0;
5574 if (diff < -5)
5576 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5578 else if (diff > 5)
5580 int32 exploration_percent = (100-((diff-5)*5));
5581 if (exploration_percent > 100)
5582 exploration_percent = 100;
5583 else if (exploration_percent < 0)
5584 exploration_percent = 0;
5586 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5588 else
5590 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5593 GiveXP( XP, NULL );
5594 SendExplorationExperience(area,XP);
5596 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5601 uint32 Player::TeamForRace(uint8 race)
5603 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5604 if(!rEntry)
5606 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5607 return ALLIANCE;
5610 switch(rEntry->TeamID)
5612 case 7: return ALLIANCE;
5613 case 1: return HORDE;
5616 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5617 return ALLIANCE;
5620 uint32 Player::getFactionForRace(uint8 race)
5622 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5623 if(!rEntry)
5625 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5626 return 0;
5629 return rEntry->FactionID;
5632 void Player::setFactionForRace(uint8 race)
5634 m_team = TeamForRace(race);
5635 setFaction( getFactionForRace(race) );
5638 ReputationRank Player::GetReputationRank(uint32 faction) const
5640 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5641 return GetReputationMgr().GetRank(factionEntry);
5644 //Calculate total reputation percent player gain with quest/creature level
5645 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5647 float percent = 100.0f;
5649 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5651 if(rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5652 percent *= rate;
5654 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5656 percent += rep > 0 ? repMod : -repMod;
5658 if(percent <= 0.0f)
5659 return 0;
5661 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5664 //Calculates how many reputation points player gains in victim's enemy factions
5665 void Player::RewardReputation(Unit *pVictim, float rate)
5667 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5668 return;
5670 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5672 if(!Rep)
5673 return;
5675 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5677 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5678 donerep1 = int32(donerep1*rate);
5679 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5680 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5681 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5682 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5684 // Wiki: Team factions value divided by 2
5685 if (factionEntry1 && Rep->is_teamaward1)
5687 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5688 if(team1_factionEntry)
5689 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5693 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5695 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5696 donerep2 = int32(donerep2*rate);
5697 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5698 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5699 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5700 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5702 // Wiki: Team factions value divided by 2
5703 if (factionEntry2 && Rep->is_teamaward2)
5705 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5706 if(team2_factionEntry)
5707 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5712 //Calculate how many reputation points player gain with the quest
5713 void Player::RewardReputation(Quest const *pQuest)
5715 // quest reputation reward/loss
5716 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5718 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5720 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest),pQuest->RewRepValue[i],true);
5721 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5722 if(factionEntry)
5723 GetReputationMgr().ModifyReputation(factionEntry, rep);
5727 // TODO: implement reputation spillover
5730 void Player::UpdateArenaFields(void)
5732 /* arena calcs go here */
5735 void Player::UpdateHonorFields()
5737 /// called when rewarding honor and at each save
5738 uint64 now = time(NULL);
5739 uint64 today = uint64(time(NULL) / DAY) * DAY;
5741 if(m_lastHonorUpdateTime < today)
5743 uint64 yesterday = today - DAY;
5745 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5747 // update yesterday's contribution
5748 if(m_lastHonorUpdateTime >= yesterday )
5750 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5752 // this is the first update today, reset today's contribution
5753 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5754 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5756 else
5758 // no honor/kills yesterday or today, reset
5759 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5760 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5764 m_lastHonorUpdateTime = now;
5767 ///Calculate the amount of honor gained based on the victim
5768 ///and the size of the group for which the honor is divided
5769 ///An exact honor value can also be given (overriding the calcs)
5770 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5772 // do not reward honor in arenas, but enable onkill spellproc
5773 if(InArena())
5775 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5776 return false;
5778 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5779 return false;
5781 return true;
5784 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5785 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5786 return false;
5788 uint64 victim_guid = 0;
5789 uint32 victim_rank = 0;
5791 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5792 UpdateHonorFields();
5794 if(honor <= 0)
5796 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5797 return false;
5799 victim_guid = uVictim->GetGUID();
5801 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5803 Player *pVictim = (Player *)uVictim;
5805 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5806 return false;
5808 float f = 1; //need for total kills (?? need more info)
5809 uint32 k_grey = 0;
5810 uint32 k_level = getLevel();
5811 uint32 v_level = pVictim->getLevel();
5814 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5815 // [0] Just name
5816 // [1..14] Alliance honor titles and player name
5817 // [15..28] Horde honor titles and player name
5818 // [29..38] Other title and player name
5819 // [39+] Nothing
5820 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5821 // Get Killer titles, CharTitlesEntry::bit_index
5822 // Ranks:
5823 // title[1..14] -> rank[5..18]
5824 // title[15..28] -> rank[5..18]
5825 // title[other] -> 0
5826 if (victim_title == 0)
5827 victim_guid = 0; // Don't show HK: <rank> message, only log.
5828 else if (victim_title < 15)
5829 victim_rank = victim_title + 4;
5830 else if (victim_title < 29)
5831 victim_rank = victim_title - 14 + 4;
5832 else
5833 victim_guid = 0; // Don't show HK: <rank> message, only log.
5836 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5838 if(v_level<=k_grey)
5839 return false;
5841 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5843 int32 v_rank =1; //need more info
5845 honor = ((f * diff_level * (190 + v_rank*10))/6);
5846 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5848 // count the number of playerkills in one day
5849 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5850 // and those in a lifetime
5851 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5852 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5853 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5854 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5856 else
5858 Creature *cVictim = (Creature *)uVictim;
5860 if (!cVictim->isRacialLeader())
5861 return false;
5863 honor = 100; // ??? need more info
5864 victim_rank = 19; // HK: Leader
5868 if (uVictim != NULL)
5870 honor *= sWorld.getRate(RATE_HONOR);
5872 if(groupsize > 1)
5873 honor /= groupsize;
5875 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5878 // honor - for show honor points in log
5879 // victim_guid - for show victim name in log
5880 // victim_rank [1..4] HK: <dishonored rank>
5881 // victim_rank [5..19] HK: <alliance\horde rank>
5882 // victim_rank [0,20+] HK: <>
5883 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5884 data << (uint32) honor;
5885 data << (uint64) victim_guid;
5886 data << (uint32) victim_rank;
5888 GetSession()->SendPacket(&data);
5890 // add honor points
5891 ModifyHonorPoints(int32(honor));
5893 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5894 return true;
5897 void Player::ModifyHonorPoints( int32 value )
5899 if(value < 0)
5901 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5902 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5903 else
5904 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5906 else
5907 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5910 void Player::ModifyArenaPoints( int32 value )
5912 if(value < 0)
5914 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5915 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5916 else
5917 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5919 else
5920 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5923 uint32 Player::GetGuildIdFromDB(uint64 guid)
5925 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5926 if(!result)
5927 return 0;
5929 uint32 id = result->Fetch()[0].GetUInt32();
5930 delete result;
5931 return id;
5934 uint32 Player::GetRankFromDB(uint64 guid)
5936 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5937 if( result )
5939 uint32 v = result->Fetch()[0].GetUInt32();
5940 delete result;
5941 return v;
5943 else
5944 return 0;
5947 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
5949 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);
5950 if(!result)
5951 return 0;
5953 uint32 id = (*result)[0].GetUInt32();
5954 delete result;
5955 return id;
5958 uint32 Player::GetZoneIdFromDB(uint64 guid)
5960 uint32 guidLow = GUID_LOPART(guid);
5961 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
5962 if (!result)
5963 return 0;
5964 Field* fields = result->Fetch();
5965 uint32 zone = fields[0].GetUInt32();
5966 delete result;
5968 if (!zone)
5970 // stored zone is zero, use generic and slow zone detection
5971 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
5972 if( !result )
5973 return 0;
5974 fields = result->Fetch();
5975 uint32 map = fields[0].GetUInt32();
5976 float posx = fields[1].GetFloat();
5977 float posy = fields[2].GetFloat();
5978 float posz = fields[3].GetFloat();
5979 delete result;
5981 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
5983 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
5986 return zone;
5989 void Player::UpdateArea(uint32 newArea)
5991 // FFA_PVP flags are area and not zone id dependent
5992 // so apply them accordingly
5993 m_areaUpdateId = newArea;
5995 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
5997 if(area && (area->flags & AREA_FLAG_ARENA))
5999 if(!isGameMaster())
6000 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6002 else
6004 // remove ffa flag only if not ffapvp realm
6005 // removal in sanctuaries and capitals is handled in zone update
6006 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6007 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6010 UpdateAreaDependentAuras(newArea);
6013 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6015 if(m_zoneUpdateId != newZone)
6016 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6018 m_zoneUpdateId = newZone;
6019 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6021 // zone changed, so area changed as well, update it
6022 UpdateArea(newArea);
6024 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6025 if(!zone)
6026 return;
6028 if (sWorld.getConfig(CONFIG_WEATHER))
6030 Weather *wth = sWorld.FindWeather(zone->ID);
6031 if(wth)
6033 wth->SendWeatherUpdateToPlayer(this);
6035 else
6037 if(!sWorld.AddWeather(zone->ID))
6039 // send fine weather packet to remove old zone's weather
6040 Weather::SendFineWeatherUpdateToPlayer(this);
6045 // in PvP, any not controlled zone (except zone->team == 6, default case)
6046 // in PvE, only opposition team capital
6047 switch(zone->team)
6049 case AREATEAM_ALLY:
6050 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6051 break;
6052 case AREATEAM_HORDE:
6053 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6054 break;
6055 case AREATEAM_NONE:
6056 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6057 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6058 break;
6059 default: // 6 in fact
6060 pvpInfo.inHostileArea = false;
6061 break;
6064 if(pvpInfo.inHostileArea) // in hostile area
6066 if(!IsPvP() || pvpInfo.endTimer != 0)
6067 UpdatePvP(true, true);
6069 else // in friendly area
6071 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6072 pvpInfo.endTimer = time(0); // start toggle-off
6075 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6077 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6078 if(sWorld.IsFFAPvPRealm())
6079 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6081 else
6083 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6086 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6088 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6089 SetRestType(REST_TYPE_IN_CITY);
6090 InnEnter(time(0),GetMapId(),0,0,0);
6092 if(sWorld.IsFFAPvPRealm())
6093 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6095 else // anywhere else
6097 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6099 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6101 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6103 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6104 SetRestType(REST_TYPE_NO);
6106 if(sWorld.IsFFAPvPRealm())
6107 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6110 else // not in tavern (leave city then)
6112 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6113 SetRestType(REST_TYPE_NO);
6115 // Set player to FFA PVP when not in rested environment.
6116 if(sWorld.IsFFAPvPRealm())
6117 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6122 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6123 // if player resurrected at teleport this will be applied in resurrect code
6124 if(isAlive())
6125 DestroyZoneLimitedItem( true, newZone );
6127 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6128 AutoUnequipOffhandIfNeed();
6130 // recent client version not send leave/join channel packets for built-in local channels
6131 UpdateLocalChannels( newZone );
6133 // group update
6134 if(GetGroup())
6135 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6137 UpdateZoneDependentAuras(newZone);
6140 //If players are too far way of duel flag... then player loose the duel
6141 void Player::CheckDuelDistance(time_t currTime)
6143 if(!duel)
6144 return;
6146 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6147 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6148 if(!obj)
6149 return;
6151 if(duel->outOfBound == 0)
6153 if(!IsWithinDistInMap(obj, 50))
6155 duel->outOfBound = currTime;
6157 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6158 GetSession()->SendPacket(&data);
6161 else
6163 if(IsWithinDistInMap(obj, 40))
6165 duel->outOfBound = 0;
6167 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6168 GetSession()->SendPacket(&data);
6170 else if(currTime >= (duel->outOfBound+10))
6172 DuelComplete(DUEL_FLED);
6177 void Player::DuelComplete(DuelCompleteType type)
6179 // duel not requested
6180 if(!duel)
6181 return;
6183 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6184 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6185 GetSession()->SendPacket(&data);
6186 duel->opponent->GetSession()->SendPacket(&data);
6188 if(type != DUEL_INTERUPTED)
6190 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6191 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6192 data << duel->opponent->GetName();
6193 data << GetName();
6194 SendMessageToSet(&data,true);
6197 if (type == DUEL_WON)
6199 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6200 if (duel->opponent)
6201 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6204 // cool-down duel spell
6205 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6207 data<<GetGUID();
6208 data<<uint8(0x0);
6210 data<<(uint32)7266;
6211 data<<uint32(0x0);
6212 GetSession()->SendPacket(&data);
6213 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6214 data<<duel->opponent->GetGUID();
6215 data<<uint8(0x0);
6216 data<<(uint32)7266;
6217 data<<uint32(0x0);
6218 duel->opponent->GetSession()->SendPacket(&data);*/
6220 //Remove Duel Flag object
6221 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6222 if(obj)
6223 duel->initiator->RemoveGameObject(obj,true);
6225 /* remove auras */
6226 std::vector<uint32> auras2remove;
6227 AuraMap const& vAuras = duel->opponent->GetAuras();
6228 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6230 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6231 auras2remove.push_back(i->second->GetId());
6234 for(size_t i=0; i<auras2remove.size(); ++i)
6235 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6237 auras2remove.clear();
6238 AuraMap const& auras = GetAuras();
6239 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6241 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6242 auras2remove.push_back(i->second->GetId());
6244 for(size_t i=0; i<auras2remove.size(); ++i)
6245 RemoveAurasDueToSpell(auras2remove[i]);
6247 // cleanup combo points
6248 if(GetComboTarget()==duel->opponent->GetGUID())
6249 ClearComboPoints();
6250 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6251 ClearComboPoints();
6253 if(duel->opponent->GetComboTarget()==GetGUID())
6254 duel->opponent->ClearComboPoints();
6255 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6256 duel->opponent->ClearComboPoints();
6258 //cleanups
6259 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6260 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6261 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6262 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6264 delete duel->opponent->duel;
6265 duel->opponent->duel = NULL;
6266 delete duel;
6267 duel = NULL;
6270 //---------------------------------------------------------//
6272 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6274 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6275 return;
6277 // not apply/remove mods for broken item
6278 if(item->IsBroken())
6279 return;
6281 ItemPrototype const *proto = item->GetProto();
6283 if(!proto)
6284 return;
6286 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6288 uint32 attacktype = Player::GetAttackBySlot(slot);
6289 if(attacktype < MAX_ATTACK)
6290 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6292 _ApplyItemBonuses(proto,slot,apply);
6294 if( slot==EQUIPMENT_SLOT_RANGED )
6295 _ApplyAmmoBonuses();
6297 ApplyItemEquipSpell(item,apply);
6298 ApplyEnchantment(item, apply);
6300 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6301 CorrectMetaGemEnchants(slot, apply);
6303 sLog.outDebug("_ApplyItemMods complete.");
6306 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6308 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6309 return;
6311 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6313 uint32 statType = 0;
6314 int32 val = 0;
6316 if(proto->ScalingStatDistribution)
6318 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6320 statType = ssd->StatMod[i];
6322 if(uint32 modifier = ssd->Modifier[i])
6324 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6325 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6327 uint32 multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6328 val = (multiplier * modifier) / 10000;
6333 else
6335 statType = proto->ItemStat[i].ItemStatType;
6336 val = proto->ItemStat[i].ItemStatValue;
6339 if(val == 0)
6340 continue;
6342 switch (statType)
6344 case ITEM_MOD_MANA:
6345 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6346 break;
6347 case ITEM_MOD_HEALTH: // modify HP
6348 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6349 break;
6350 case ITEM_MOD_AGILITY: // modify agility
6351 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6352 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6353 break;
6354 case ITEM_MOD_STRENGTH: //modify strength
6355 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6356 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6357 break;
6358 case ITEM_MOD_INTELLECT: //modify intellect
6359 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6360 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6361 break;
6362 case ITEM_MOD_SPIRIT: //modify spirit
6363 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6364 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6365 break;
6366 case ITEM_MOD_STAMINA: //modify stamina
6367 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6368 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6369 break;
6370 case ITEM_MOD_DEFENSE_SKILL_RATING:
6371 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6372 break;
6373 case ITEM_MOD_DODGE_RATING:
6374 ApplyRatingMod(CR_DODGE, int32(val), apply);
6375 break;
6376 case ITEM_MOD_PARRY_RATING:
6377 ApplyRatingMod(CR_PARRY, int32(val), apply);
6378 break;
6379 case ITEM_MOD_BLOCK_RATING:
6380 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6381 break;
6382 case ITEM_MOD_HIT_MELEE_RATING:
6383 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6384 break;
6385 case ITEM_MOD_HIT_RANGED_RATING:
6386 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6387 break;
6388 case ITEM_MOD_HIT_SPELL_RATING:
6389 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6390 break;
6391 case ITEM_MOD_CRIT_MELEE_RATING:
6392 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6393 break;
6394 case ITEM_MOD_CRIT_RANGED_RATING:
6395 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6396 break;
6397 case ITEM_MOD_CRIT_SPELL_RATING:
6398 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6399 break;
6400 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6401 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6402 break;
6403 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6404 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6405 break;
6406 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6407 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6408 break;
6409 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6410 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6411 break;
6412 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6413 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6414 break;
6415 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6416 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6417 break;
6418 case ITEM_MOD_HASTE_MELEE_RATING:
6419 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6420 break;
6421 case ITEM_MOD_HASTE_RANGED_RATING:
6422 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6423 break;
6424 case ITEM_MOD_HASTE_SPELL_RATING:
6425 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6426 break;
6427 case ITEM_MOD_HIT_RATING:
6428 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6429 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6430 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6431 break;
6432 case ITEM_MOD_CRIT_RATING:
6433 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6434 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6435 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6436 break;
6437 case ITEM_MOD_HIT_TAKEN_RATING:
6438 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6439 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6440 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6441 break;
6442 case ITEM_MOD_CRIT_TAKEN_RATING:
6443 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6444 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6445 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6446 break;
6447 case ITEM_MOD_RESILIENCE_RATING:
6448 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6449 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6450 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6451 break;
6452 case ITEM_MOD_HASTE_RATING:
6453 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6454 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6455 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6456 break;
6457 case ITEM_MOD_EXPERTISE_RATING:
6458 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6459 break;
6460 case ITEM_MOD_ATTACK_POWER:
6461 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6462 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6463 break;
6464 case ITEM_MOD_RANGED_ATTACK_POWER:
6465 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6466 break;
6467 case ITEM_MOD_FERAL_ATTACK_POWER:
6468 ApplyFeralAPBonus(int32(val), apply);
6469 break;
6470 case ITEM_MOD_SPELL_HEALING_DONE:
6471 ApplySpellHealingBonus(int32(val), apply);
6472 break;
6473 case ITEM_MOD_SPELL_DAMAGE_DONE:
6474 ApplySpellDamageBonus(int32(val), apply);
6475 break;
6476 case ITEM_MOD_MANA_REGENERATION:
6477 ApplyManaRegenBonus(int32(val), apply);
6478 break;
6479 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6480 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6481 break;
6482 case ITEM_MOD_SPELL_POWER:
6483 ApplySpellHealingBonus(int32(val), apply);
6484 ApplySpellDamageBonus(int32(val), apply);
6485 break;
6489 if (proto->Armor)
6490 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6492 if (proto->Block)
6493 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6495 if (proto->HolyRes)
6496 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6498 if (proto->FireRes)
6499 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6501 if (proto->NatureRes)
6502 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6504 if (proto->FrostRes)
6505 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6507 if (proto->ShadowRes)
6508 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6510 if (proto->ArcaneRes)
6511 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6513 WeaponAttackType attType = BASE_ATTACK;
6514 float damage = 0.0f;
6516 if( slot == EQUIPMENT_SLOT_RANGED && (
6517 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6518 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6520 attType = RANGED_ATTACK;
6522 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6524 attType = OFF_ATTACK;
6527 if (proto->Damage[0].DamageMin > 0 )
6529 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6530 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6531 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6534 if (proto->Damage[0].DamageMax > 0 )
6536 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6537 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6540 // Druids get feral AP bonus from weapon dps
6541 if(getClass() == CLASS_DRUID)
6543 int32 feral_bonus = proto->getFeralBonus();
6544 if (feral_bonus > 0)
6545 ApplyFeralAPBonus(feral_bonus, apply);
6548 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6549 return;
6551 if (proto->Delay)
6553 if(slot == EQUIPMENT_SLOT_RANGED)
6554 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6555 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6556 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6557 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6558 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6561 if(CanModifyStats() && (damage || proto->Delay))
6562 UpdateDamagePhysical(attType);
6565 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6567 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6568 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6569 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6571 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6572 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6573 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6575 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6576 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6577 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6580 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6582 // generic not weapon specific case processes in aura code
6583 if(aura->GetSpellProto()->EquippedItemClass == -1)
6584 return;
6586 BaseModGroup mod = BASEMOD_END;
6587 switch(attackType)
6589 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6590 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6591 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6592 default: return;
6595 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6597 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6601 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6603 // ignore spell mods for not wands
6604 Modifier const* modifier = aura->GetModifier();
6605 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6606 return;
6608 // generic not weapon specific case processes in aura code
6609 if(aura->GetSpellProto()->EquippedItemClass == -1)
6610 return;
6612 UnitMods unitMod = UNIT_MOD_END;
6613 switch(attackType)
6615 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6616 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6617 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6618 default: return;
6621 UnitModifierType unitModType = TOTAL_VALUE;
6622 switch(modifier->m_auraname)
6624 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6625 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6626 default: return;
6629 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6631 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6635 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6637 if(!item)
6638 return;
6640 ItemPrototype const *proto = item->GetProto();
6641 if(!proto)
6642 return;
6644 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6646 _Spell const& spellData = proto->Spells[i];
6648 // no spell
6649 if(!spellData.SpellId )
6650 continue;
6652 // wrong triggering type
6653 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6654 continue;
6656 // check if it is valid spell
6657 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6658 if(!spellproto)
6659 continue;
6661 ApplyEquipSpell(spellproto,item,apply,form_change);
6665 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6667 if(apply)
6669 // Cannot be used in this stance/form
6670 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6671 return;
6673 if(form_change) // check aura active state from other form
6675 bool found = false;
6676 for (int k=0; k < 3; ++k)
6678 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6679 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6681 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6683 found = true;
6684 break;
6687 if(found)
6688 break;
6691 if(found) // and skip re-cast already active aura at form change
6692 return;
6695 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6697 CastSpell(this,spellInfo,true,item);
6699 else
6701 if(form_change) // check aura compatibility
6703 // Cannot be used in this stance/form
6704 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6705 return; // and remove only not compatible at form change
6708 if(item)
6709 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6710 else
6711 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6715 void Player::UpdateEquipSpellsAtFormChange()
6717 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6719 if(m_items[i] && !m_items[i]->IsBroken())
6721 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6722 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6726 // item set bonuses not dependent from item broken state
6727 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6729 ItemSetEffect* eff = ItemSetEff[setindex];
6730 if(!eff)
6731 continue;
6733 for(uint32 y=0;y<8; ++y)
6735 SpellEntry const* spellInfo = eff->spells[y];
6736 if(!spellInfo)
6737 continue;
6739 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6740 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6745 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6747 if(!item || item->IsBroken())
6748 return;
6750 ItemPrototype const *proto = item->GetProto();
6751 if(!proto)
6752 return;
6754 if (!Target || Target == this )
6755 return;
6757 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6759 _Spell const& spellData = proto->Spells[i];
6761 // no spell
6762 if(!spellData.SpellId )
6763 continue;
6765 // wrong triggering type
6766 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6767 continue;
6769 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6770 if(!spellInfo)
6772 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6773 continue;
6776 // not allow proc extra attack spell at extra attack
6777 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6778 return;
6780 float chance = spellInfo->procChance;
6782 if(spellData.SpellPPMRate)
6784 uint32 WeaponSpeed = GetAttackTime(attType);
6785 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6787 else if(chance > 100.0f)
6789 chance = GetWeaponProcChance();
6792 if (roll_chance_f(chance))
6793 CastSpell(Target, spellInfo->Id, true, item);
6796 // item combat enchantments
6797 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6799 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6800 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6801 if(!pEnchant) continue;
6802 for (int s=0;s<3;s++)
6804 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6805 continue;
6807 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6808 if (!spellInfo)
6810 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6811 continue;
6814 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6815 if (roll_chance_f(chance))
6817 if(IsPositiveSpell(pEnchant->spellid[s]))
6818 CastSpell(this, pEnchant->spellid[s], true, item);
6819 else
6820 CastSpell(Target, pEnchant->spellid[s], true, item);
6826 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6828 ItemPrototype const* proto = item->GetProto();
6829 // special learning case
6830 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6832 uint32 learn_spell_id = proto->Spells[0].SpellId;
6833 uint32 learning_spell_id = proto->Spells[1].SpellId;
6835 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6836 if(!spellInfo)
6838 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6839 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6840 return;
6843 Spell *spell = new Spell(this, spellInfo, false);
6844 spell->m_CastItem = item;
6845 spell->m_cast_count = cast_count; //set count of casts
6846 spell->m_currentBasePoints[0] = learning_spell_id;
6847 spell->prepare(&targets);
6848 return;
6851 // use triggered flag only for items with many spell casts and for not first cast
6852 int count = 0;
6854 // item spells casted at use
6855 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6857 _Spell const& spellData = proto->Spells[i];
6859 // no spell
6860 if(!spellData.SpellId)
6861 continue;
6863 // wrong triggering type
6864 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6865 continue;
6867 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6868 if(!spellInfo)
6870 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6871 continue;
6874 Spell *spell = new Spell(this, spellInfo, (count > 0));
6875 spell->m_CastItem = item;
6876 spell->m_cast_count = cast_count; // set count of casts
6877 spell->m_glyphIndex = glyphIndex; // glyph index
6878 spell->prepare(&targets);
6880 ++count;
6883 // Item enchantments spells casted at use
6884 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6886 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6887 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6888 if(!pEnchant) continue;
6889 for (int s=0;s<3;s++)
6891 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6892 continue;
6894 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6895 if (!spellInfo)
6897 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6898 continue;
6901 Spell *spell = new Spell(this, spellInfo, (count > 0));
6902 spell->m_CastItem = item;
6903 spell->m_cast_count = cast_count; // set count of casts
6904 spell->m_glyphIndex = glyphIndex; // glyph index
6905 spell->prepare(&targets);
6907 ++count;
6912 void Player::_RemoveAllItemMods()
6914 sLog.outDebug("_RemoveAllItemMods start.");
6916 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6918 if(m_items[i])
6920 ItemPrototype const *proto = m_items[i]->GetProto();
6921 if(!proto)
6922 continue;
6924 // item set bonuses not dependent from item broken state
6925 if(proto->ItemSet)
6926 RemoveItemsSetItem(this,proto);
6928 if(m_items[i]->IsBroken())
6929 continue;
6931 ApplyItemEquipSpell(m_items[i],false);
6932 ApplyEnchantment(m_items[i], false);
6936 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6938 if(m_items[i])
6940 if(m_items[i]->IsBroken())
6941 continue;
6942 ItemPrototype const *proto = m_items[i]->GetProto();
6943 if(!proto)
6944 continue;
6946 uint32 attacktype = Player::GetAttackBySlot(i);
6947 if(attacktype < MAX_ATTACK)
6948 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6950 _ApplyItemBonuses(proto,i, false);
6952 if( i == EQUIPMENT_SLOT_RANGED )
6953 _ApplyAmmoBonuses();
6957 sLog.outDebug("_RemoveAllItemMods complete.");
6960 void Player::_ApplyAllItemMods()
6962 sLog.outDebug("_ApplyAllItemMods start.");
6964 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6966 if(m_items[i])
6968 if(m_items[i]->IsBroken())
6969 continue;
6971 ItemPrototype const *proto = m_items[i]->GetProto();
6972 if(!proto)
6973 continue;
6975 uint32 attacktype = Player::GetAttackBySlot(i);
6976 if(attacktype < MAX_ATTACK)
6977 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6979 _ApplyItemBonuses(proto,i, true);
6981 if( i == EQUIPMENT_SLOT_RANGED )
6982 _ApplyAmmoBonuses();
6986 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6988 if(m_items[i])
6990 ItemPrototype const *proto = m_items[i]->GetProto();
6991 if(!proto)
6992 continue;
6994 // item set bonuses not dependent from item broken state
6995 if(proto->ItemSet)
6996 AddItemsSetItem(this,m_items[i]);
6998 if(m_items[i]->IsBroken())
6999 continue;
7001 ApplyItemEquipSpell(m_items[i],true);
7002 ApplyEnchantment(m_items[i], true);
7006 sLog.outDebug("_ApplyAllItemMods complete.");
7009 void Player::_ApplyAmmoBonuses()
7011 // check ammo
7012 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7013 if(!ammo_id)
7014 return;
7016 float currentAmmoDPS;
7018 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7019 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7020 currentAmmoDPS = 0.0f;
7021 else
7022 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7024 if(currentAmmoDPS == GetAmmoDPS())
7025 return;
7027 m_ammoDPS = currentAmmoDPS;
7029 if(CanModifyStats())
7030 UpdateDamagePhysical(RANGED_ATTACK);
7033 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7035 if(!ammo_proto)
7036 return false;
7038 // check ranged weapon
7039 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7040 if(!weapon || weapon->IsBroken() )
7041 return false;
7043 ItemPrototype const* weapon_proto = weapon->GetProto();
7044 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7045 return false;
7047 // check ammo ws. weapon compatibility
7048 switch(weapon_proto->SubClass)
7050 case ITEM_SUBCLASS_WEAPON_BOW:
7051 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7052 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7053 return false;
7054 break;
7055 case ITEM_SUBCLASS_WEAPON_GUN:
7056 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7057 return false;
7058 break;
7059 default:
7060 return false;
7063 return true;
7066 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7067 Called by remove insignia spell effect */
7068 void Player::RemovedInsignia(Player* looterPlr)
7070 if (!GetBattleGroundId())
7071 return;
7073 // If not released spirit, do it !
7074 if(m_deathTimer > 0)
7076 m_deathTimer = 0;
7077 BuildPlayerRepop();
7078 RepopAtGraveyard();
7081 Corpse *corpse = GetCorpse();
7082 if (!corpse)
7083 return;
7085 // We have to convert player corpse to bones, not to be able to resurrect there
7086 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7087 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7088 if (!bones)
7089 return;
7091 // Now we must make bones lootable, and send player loot
7092 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7094 // We store the level of our player in the gold field
7095 // We retrieve this information at Player::SendLoot()
7096 bones->loot.gold = getLevel();
7097 bones->lootRecipient = looterPlr;
7098 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7101 void Player::SendLootRelease( uint64 guid )
7103 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7104 data << uint64(guid) << uint8(1);
7105 SendDirectMessage( &data );
7108 void Player::SendLoot(uint64 guid, LootType loot_type)
7110 if (uint64 lguid = GetLootGUID())
7111 m_session->DoLootRelease(lguid);
7113 Loot *loot = 0;
7114 PermissionTypes permission = ALL_PERMISSION;
7116 sLog.outDebug("Player::SendLoot");
7117 if (IS_GAMEOBJECT_GUID(guid))
7119 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7120 GameObject *go = GetMap()->GetGameObject(guid);
7122 // not check distance for GO in case owned GO (fishing bobber case, for example)
7123 // And permit out of range GO with no owner in case fishing hole
7124 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7126 SendLootRelease(guid);
7127 return;
7130 loot = &go->loot;
7132 if (go->getLootState() == GO_READY)
7134 uint32 lootid = go->GetLootId();
7136 if (lootid)
7138 sLog.outDebug(" if(lootid)");
7139 loot->clear();
7140 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7143 if (loot_type == LOOT_FISHING)
7144 go->getFishLoot(loot,this);
7146 go->SetLootState(GO_ACTIVATED);
7149 else if (IS_ITEM_GUID(guid))
7151 Item *item = GetItemByGuid( guid );
7153 if (!item)
7155 SendLootRelease(guid);
7156 return;
7159 loot = &item->loot;
7161 if (!item->m_lootGenerated)
7163 item->m_lootGenerated = true;
7164 loot->clear();
7166 switch(loot_type)
7168 case LOOT_DISENCHANTING:
7169 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7170 break;
7171 case LOOT_PROSPECTING:
7172 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7173 break;
7174 case LOOT_MILLING:
7175 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7176 break;
7177 default:
7178 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7179 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7180 break;
7184 else if (IS_CORPSE_GUID(guid)) // remove insignia
7186 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7188 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7190 SendLootRelease(guid);
7191 return;
7194 loot = &bones->loot;
7196 if (!bones->lootForBody)
7198 bones->lootForBody = true;
7199 uint32 pLevel = bones->loot.gold;
7200 bones->loot.clear();
7201 // It may need a better formula
7202 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7203 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7206 if (bones->lootRecipient != this)
7207 permission = NONE_PERMISSION;
7209 else
7211 Creature *creature = GetMap()->GetCreature(guid);
7213 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7214 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7216 SendLootRelease(guid);
7217 return;
7220 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7222 SendLootRelease(guid);
7223 return;
7226 loot = &creature->loot;
7228 if (loot_type == LOOT_PICKPOCKETING)
7230 if (!creature->lootForPickPocketed)
7232 creature->lootForPickPocketed = true;
7233 loot->clear();
7235 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7236 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7238 // Generate extra money for pick pocket loot
7239 const uint32 a = urand(0, creature->getLevel()/2);
7240 const uint32 b = urand(0, getLevel()/2);
7241 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7244 else
7246 // the player whose group may loot the corpse
7247 Player *recipient = creature->GetLootRecipient();
7248 if (!recipient)
7250 creature->SetLootRecipient(this);
7251 recipient = this;
7254 if (creature->lootForPickPocketed)
7256 creature->lootForPickPocketed = false;
7257 loot->clear();
7260 if (!creature->lootForBody)
7262 creature->lootForBody = true;
7263 loot->clear();
7265 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7266 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7268 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7270 if (Group* group = recipient->GetGroup())
7272 group->UpdateLooterGuid(creature,true);
7274 switch (group->GetLootMethod())
7276 case GROUP_LOOT:
7277 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7278 group->GroupLoot(recipient->GetGUID(), loot, creature);
7279 break;
7280 case NEED_BEFORE_GREED:
7281 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7282 break;
7283 case MASTER_LOOT:
7284 group->MasterLoot(recipient->GetGUID(), loot, creature);
7285 break;
7286 default:
7287 break;
7292 // possible only if creature->lootForBody && loot->empty() at spell cast check
7293 if (loot_type == LOOT_SKINNING)
7295 loot->clear();
7296 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7298 // set group rights only for loot_type != LOOT_SKINNING
7299 else
7301 if(Group* group = GetGroup())
7303 if (group == recipient->GetGroup())
7305 if (group->GetLootMethod() == FREE_FOR_ALL)
7306 permission = ALL_PERMISSION;
7307 else if (group->GetLooterGuid() == GetGUID())
7309 if (group->GetLootMethod() == MASTER_LOOT)
7310 permission = MASTER_PERMISSION;
7311 else
7312 permission = ALL_PERMISSION;
7314 else
7315 permission = GROUP_PERMISSION;
7317 else
7318 permission = NONE_PERMISSION;
7320 else if (recipient == this)
7321 permission = ALL_PERMISSION;
7322 else
7323 permission = NONE_PERMISSION;
7328 SetLootGUID(guid);
7330 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7331 switch(loot_type)
7333 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7334 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7335 default: break;
7338 // need know merged fishing/corpse loot type for achievements
7339 loot->loot_type = loot_type;
7341 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7343 data << uint64(guid);
7344 data << uint8(loot_type);
7345 data << LootView(*loot, this, permission);
7347 SendDirectMessage(&data);
7349 // add 'this' player as one of the players that are looting 'loot'
7350 if (permission != NONE_PERMISSION)
7351 loot->AddLooter(GetGUID());
7353 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7354 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7357 void Player::SendNotifyLootMoneyRemoved()
7359 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7360 GetSession()->SendPacket( &data );
7363 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7365 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7366 data << uint8(lootSlot);
7367 GetSession()->SendPacket( &data );
7370 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7372 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7373 data << Field;
7374 data << Value;
7375 GetSession()->SendPacket(&data);
7378 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7380 // data depends on zoneid/mapid...
7381 BattleGround* bg = GetBattleGround();
7382 uint16 NumberOfFields = 0;
7383 uint32 mapid = GetMapId();
7385 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7387 // may be exist better way to do this...
7388 switch(zoneid)
7390 case 0:
7391 case 1:
7392 case 4:
7393 case 8:
7394 case 10:
7395 case 11:
7396 case 12:
7397 case 36:
7398 case 38:
7399 case 40:
7400 case 41:
7401 case 51:
7402 case 267:
7403 case 1519:
7404 case 1537:
7405 case 2257:
7406 case 2918:
7407 NumberOfFields = 8;
7408 break;
7409 case 139:
7410 NumberOfFields = 41;
7411 break;
7412 case 1377:
7413 NumberOfFields = 15;
7414 break;
7415 case 2597:
7416 NumberOfFields = 83;
7417 break;
7418 case 3277:
7419 NumberOfFields = 16;
7420 break;
7421 case 3358:
7422 case 3820:
7423 NumberOfFields = 40;
7424 break;
7425 case 3483:
7426 NumberOfFields = 27;
7427 break;
7428 case 3518:
7429 NumberOfFields = 39;
7430 break;
7431 case 3519:
7432 NumberOfFields = 38;
7433 break;
7434 case 3521:
7435 NumberOfFields = 37;
7436 break;
7437 case 3698:
7438 case 3702:
7439 case 3968:
7440 NumberOfFields = 11;
7441 break;
7442 case 3703:
7443 NumberOfFields = 11;
7444 break;
7445 default:
7446 NumberOfFields = 12;
7447 break;
7450 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7451 data << uint32(mapid); // mapid
7452 data << uint32(zoneid); // zone id
7453 data << uint32(areaid); // area id, new 2.1.0
7454 data << uint16(NumberOfFields); // count of uint64 blocks
7455 data << uint32(0x8d8) << uint32(0x0); // 1
7456 data << uint32(0x8d7) << uint32(0x0); // 2
7457 data << uint32(0x8d6) << uint32(0x0); // 3
7458 data << uint32(0x8d5) << uint32(0x0); // 4
7459 data << uint32(0x8d4) << uint32(0x0); // 5
7460 data << uint32(0x8d3) << uint32(0x0); // 6
7461 // 7 1 - Arena season in progress, 0 - end of season
7462 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7463 // 8 Arena season id
7464 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7465 if(mapid == 530) // Outland
7467 data << uint32(0x9bf) << uint32(0x0); // 7
7468 data << uint32(0x9bd) << uint32(0xF); // 8
7469 data << uint32(0x9bb) << uint32(0xF); // 9
7471 switch(zoneid)
7473 case 1:
7474 case 11:
7475 case 12:
7476 case 38:
7477 case 40:
7478 case 51:
7479 case 1519:
7480 case 1537:
7481 case 2257:
7482 break;
7483 case 2597: // AV
7484 data << uint32(0x7ae) << uint32(0x1); // 7
7485 data << uint32(0x532) << uint32(0x1); // 8
7486 data << uint32(0x531) << uint32(0x0); // 9
7487 data << uint32(0x52e) << uint32(0x0); // 10
7488 data << uint32(0x571) << uint32(0x0); // 11
7489 data << uint32(0x570) << uint32(0x0); // 12
7490 data << uint32(0x567) << uint32(0x1); // 13
7491 data << uint32(0x566) << uint32(0x1); // 14
7492 data << uint32(0x550) << uint32(0x1); // 15
7493 data << uint32(0x544) << uint32(0x0); // 16
7494 data << uint32(0x536) << uint32(0x0); // 17
7495 data << uint32(0x535) << uint32(0x1); // 18
7496 data << uint32(0x518) << uint32(0x0); // 19
7497 data << uint32(0x517) << uint32(0x0); // 20
7498 data << uint32(0x574) << uint32(0x0); // 21
7499 data << uint32(0x573) << uint32(0x0); // 22
7500 data << uint32(0x572) << uint32(0x0); // 23
7501 data << uint32(0x56f) << uint32(0x0); // 24
7502 data << uint32(0x56e) << uint32(0x0); // 25
7503 data << uint32(0x56d) << uint32(0x0); // 26
7504 data << uint32(0x56c) << uint32(0x0); // 27
7505 data << uint32(0x56b) << uint32(0x0); // 28
7506 data << uint32(0x56a) << uint32(0x1); // 29
7507 data << uint32(0x569) << uint32(0x1); // 30
7508 data << uint32(0x568) << uint32(0x1); // 13
7509 data << uint32(0x565) << uint32(0x0); // 32
7510 data << uint32(0x564) << uint32(0x0); // 33
7511 data << uint32(0x563) << uint32(0x0); // 34
7512 data << uint32(0x562) << uint32(0x0); // 35
7513 data << uint32(0x561) << uint32(0x0); // 36
7514 data << uint32(0x560) << uint32(0x0); // 37
7515 data << uint32(0x55f) << uint32(0x0); // 38
7516 data << uint32(0x55e) << uint32(0x0); // 39
7517 data << uint32(0x55d) << uint32(0x0); // 40
7518 data << uint32(0x3c6) << uint32(0x4); // 41
7519 data << uint32(0x3c4) << uint32(0x6); // 42
7520 data << uint32(0x3c2) << uint32(0x4); // 43
7521 data << uint32(0x516) << uint32(0x1); // 44
7522 data << uint32(0x515) << uint32(0x0); // 45
7523 data << uint32(0x3b6) << uint32(0x6); // 46
7524 data << uint32(0x55c) << uint32(0x0); // 47
7525 data << uint32(0x55b) << uint32(0x0); // 48
7526 data << uint32(0x55a) << uint32(0x0); // 49
7527 data << uint32(0x559) << uint32(0x0); // 50
7528 data << uint32(0x558) << uint32(0x0); // 51
7529 data << uint32(0x557) << uint32(0x0); // 52
7530 data << uint32(0x556) << uint32(0x0); // 53
7531 data << uint32(0x555) << uint32(0x0); // 54
7532 data << uint32(0x554) << uint32(0x1); // 55
7533 data << uint32(0x553) << uint32(0x1); // 56
7534 data << uint32(0x552) << uint32(0x1); // 57
7535 data << uint32(0x551) << uint32(0x1); // 58
7536 data << uint32(0x54f) << uint32(0x0); // 59
7537 data << uint32(0x54e) << uint32(0x0); // 60
7538 data << uint32(0x54d) << uint32(0x1); // 61
7539 data << uint32(0x54c) << uint32(0x0); // 62
7540 data << uint32(0x54b) << uint32(0x0); // 63
7541 data << uint32(0x545) << uint32(0x0); // 64
7542 data << uint32(0x543) << uint32(0x1); // 65
7543 data << uint32(0x542) << uint32(0x0); // 66
7544 data << uint32(0x540) << uint32(0x0); // 67
7545 data << uint32(0x53f) << uint32(0x0); // 68
7546 data << uint32(0x53e) << uint32(0x0); // 69
7547 data << uint32(0x53d) << uint32(0x0); // 70
7548 data << uint32(0x53c) << uint32(0x0); // 71
7549 data << uint32(0x53b) << uint32(0x0); // 72
7550 data << uint32(0x53a) << uint32(0x1); // 73
7551 data << uint32(0x539) << uint32(0x0); // 74
7552 data << uint32(0x538) << uint32(0x0); // 75
7553 data << uint32(0x537) << uint32(0x0); // 76
7554 data << uint32(0x534) << uint32(0x0); // 77
7555 data << uint32(0x533) << uint32(0x0); // 78
7556 data << uint32(0x530) << uint32(0x0); // 79
7557 data << uint32(0x52f) << uint32(0x0); // 80
7558 data << uint32(0x52d) << uint32(0x1); // 81
7559 break;
7560 case 3277: // WS
7561 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7562 bg->FillInitialWorldStates(data);
7563 else
7565 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7566 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7567 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7568 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7569 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7570 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7571 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7572 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7574 break;
7575 case 3358: // AB
7576 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7577 bg->FillInitialWorldStates(data);
7578 else
7580 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7581 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7582 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7583 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7584 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7585 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7586 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7587 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7588 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7589 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7590 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7591 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7592 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7593 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7594 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7595 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7596 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7597 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7598 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7599 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7600 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7601 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7602 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7603 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7604 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7605 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7606 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7607 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7608 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7609 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7610 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7611 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7613 break;
7614 case 3820: // EY
7615 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7616 bg->FillInitialWorldStates(data);
7617 else
7619 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7620 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7621 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7622 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7623 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7624 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7625 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7626 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7627 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7628 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7629 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7630 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7631 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7632 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7633 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7634 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7635 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7636 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7637 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7638 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7639 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7640 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7641 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7642 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7643 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7644 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7645 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7646 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7647 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7648 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7649 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7650 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7651 // and some more ... unknown
7653 break;
7654 case 3483: // Hellfire Peninsula
7655 data << uint32(0x9ba) << uint32(0x1); // 10
7656 data << uint32(0x9b9) << uint32(0x1); // 11
7657 data << uint32(0x9b5) << uint32(0x0); // 12
7658 data << uint32(0x9b4) << uint32(0x1); // 13
7659 data << uint32(0x9b3) << uint32(0x0); // 14
7660 data << uint32(0x9b2) << uint32(0x0); // 15
7661 data << uint32(0x9b1) << uint32(0x1); // 16
7662 data << uint32(0x9b0) << uint32(0x0); // 17
7663 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7664 data << uint32(0x9ac) << uint32(0x0); // 19
7665 data << uint32(0x9a8) << uint32(0x0); // 20
7666 data << uint32(0x9a7) << uint32(0x0); // 21
7667 data << uint32(0x9a6) << uint32(0x1); // 22
7668 break;
7669 case 3519: // Terokkar Forest
7670 data << uint32(0xa41) << uint32(0x0); // 10
7671 data << uint32(0xa40) << uint32(0x14); // 11
7672 data << uint32(0xa3f) << uint32(0x0); // 12
7673 data << uint32(0xa3e) << uint32(0x0); // 13
7674 data << uint32(0xa3d) << uint32(0x5); // 14
7675 data << uint32(0xa3c) << uint32(0x0); // 15
7676 data << uint32(0xa87) << uint32(0x0); // 16
7677 data << uint32(0xa86) << uint32(0x0); // 17
7678 data << uint32(0xa85) << uint32(0x0); // 18
7679 data << uint32(0xa84) << uint32(0x0); // 19
7680 data << uint32(0xa83) << uint32(0x0); // 20
7681 data << uint32(0xa82) << uint32(0x0); // 21
7682 data << uint32(0xa81) << uint32(0x0); // 22
7683 data << uint32(0xa80) << uint32(0x0); // 23
7684 data << uint32(0xa7e) << uint32(0x0); // 24
7685 data << uint32(0xa7d) << uint32(0x0); // 25
7686 data << uint32(0xa7c) << uint32(0x0); // 26
7687 data << uint32(0xa7b) << uint32(0x0); // 27
7688 data << uint32(0xa7a) << uint32(0x0); // 28
7689 data << uint32(0xa79) << uint32(0x0); // 29
7690 data << uint32(0x9d0) << uint32(0x5); // 30
7691 data << uint32(0x9ce) << uint32(0x0); // 31
7692 data << uint32(0x9cd) << uint32(0x0); // 32
7693 data << uint32(0x9cc) << uint32(0x0); // 33
7694 data << uint32(0xa88) << uint32(0x0); // 34
7695 data << uint32(0xad0) << uint32(0x0); // 35
7696 data << uint32(0xacf) << uint32(0x1); // 36
7697 break;
7698 case 3521: // Zangarmarsh
7699 data << uint32(0x9e1) << uint32(0x0); // 10
7700 data << uint32(0x9e0) << uint32(0x0); // 11
7701 data << uint32(0x9df) << uint32(0x0); // 12
7702 data << uint32(0xa5d) << uint32(0x1); // 13
7703 data << uint32(0xa5c) << uint32(0x0); // 14
7704 data << uint32(0xa5b) << uint32(0x1); // 15
7705 data << uint32(0xa5a) << uint32(0x0); // 16
7706 data << uint32(0xa59) << uint32(0x1); // 17
7707 data << uint32(0xa58) << uint32(0x0); // 18
7708 data << uint32(0xa57) << uint32(0x0); // 19
7709 data << uint32(0xa56) << uint32(0x0); // 20
7710 data << uint32(0xa55) << uint32(0x1); // 21
7711 data << uint32(0xa54) << uint32(0x0); // 22
7712 data << uint32(0x9e7) << uint32(0x0); // 23
7713 data << uint32(0x9e6) << uint32(0x0); // 24
7714 data << uint32(0x9e5) << uint32(0x0); // 25
7715 data << uint32(0xa00) << uint32(0x0); // 26
7716 data << uint32(0x9ff) << uint32(0x1); // 27
7717 data << uint32(0x9fe) << uint32(0x0); // 28
7718 data << uint32(0x9fd) << uint32(0x0); // 29
7719 data << uint32(0x9fc) << uint32(0x1); // 30
7720 data << uint32(0x9fb) << uint32(0x0); // 31
7721 data << uint32(0xa62) << uint32(0x0); // 32
7722 data << uint32(0xa61) << uint32(0x1); // 33
7723 data << uint32(0xa60) << uint32(0x1); // 34
7724 data << uint32(0xa5f) << uint32(0x0); // 35
7725 break;
7726 case 3698: // Nagrand Arena
7727 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7728 bg->FillInitialWorldStates(data);
7729 else
7731 data << uint32(0xa0f) << uint32(0x0); // 7
7732 data << uint32(0xa10) << uint32(0x0); // 8
7733 data << uint32(0xa11) << uint32(0x0); // 9 show
7735 break;
7736 case 3702: // Blade's Edge Arena
7737 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7738 bg->FillInitialWorldStates(data);
7739 else
7741 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7742 data << uint32(0x9f1) << uint32(0x0); // 8 green
7743 data << uint32(0x9f3) << uint32(0x0); // 9 show
7745 break;
7746 case 3968: // Ruins of Lordaeron
7747 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7748 bg->FillInitialWorldStates(data);
7749 else
7751 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7752 data << uint32(0xbb9) << uint32(0x0); // 8 green
7753 data << uint32(0xbba) << uint32(0x0); // 9 show
7755 break;
7756 case 3703: // Shattrath City
7757 break;
7758 default:
7759 data << uint32(0x914) << uint32(0x0); // 7
7760 data << uint32(0x913) << uint32(0x0); // 8
7761 data << uint32(0x912) << uint32(0x0); // 9
7762 data << uint32(0x915) << uint32(0x0); // 10
7763 break;
7765 GetSession()->SendPacket(&data);
7768 uint32 Player::GetXPRestBonus(uint32 xp)
7770 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7772 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7773 rested_bonus = xp;
7775 SetRestBonus( GetRestBonus() - rested_bonus);
7777 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7778 return rested_bonus;
7781 void Player::SetBindPoint(uint64 guid)
7783 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7784 data << uint64(guid);
7785 GetSession()->SendPacket( &data );
7788 void Player::SendTalentWipeConfirm(uint64 guid)
7790 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7791 data << uint64(guid);
7792 data << uint32(resetTalentsCost());
7793 GetSession()->SendPacket( &data );
7796 void Player::SendPetSkillWipeConfirm()
7798 Pet* pet = GetPet();
7799 if(!pet)
7800 return;
7801 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7802 data << pet->GetGUID();
7803 data << uint32(pet->resetTalentsCost());
7804 GetSession()->SendPacket( &data );
7807 /*********************************************************/
7808 /*** STORAGE SYSTEM ***/
7809 /*********************************************************/
7811 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7813 assert(i < 3);
7814 if(i < 2 && item)
7816 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7817 return;
7818 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7819 if(charges == 0)
7820 return;
7821 if(charges > 1)
7822 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7823 else if(charges <= 1)
7825 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7826 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7831 void Player::SetSheath( uint32 sheathed )
7833 switch (sheathed)
7835 case SHEATH_STATE_UNARMED: // no prepared weapon
7836 SetVirtualItemSlot(0,NULL);
7837 SetVirtualItemSlot(1,NULL);
7838 SetVirtualItemSlot(2,NULL);
7839 break;
7840 case SHEATH_STATE_MELEE: // prepared melee weapon
7842 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7843 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7844 SetVirtualItemSlot(2,NULL);
7845 }; break;
7846 case SHEATH_STATE_RANGED: // prepared ranged weapon
7847 SetVirtualItemSlot(0,NULL);
7848 SetVirtualItemSlot(1,NULL);
7849 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7850 break;
7851 default:
7852 SetVirtualItemSlot(0,NULL);
7853 SetVirtualItemSlot(1,NULL);
7854 SetVirtualItemSlot(2,NULL);
7855 break;
7857 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7860 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7862 uint8 pClass = getClass();
7864 uint8 slots[4];
7865 slots[0] = NULL_SLOT;
7866 slots[1] = NULL_SLOT;
7867 slots[2] = NULL_SLOT;
7868 slots[3] = NULL_SLOT;
7869 switch( proto->InventoryType )
7871 case INVTYPE_HEAD:
7872 slots[0] = EQUIPMENT_SLOT_HEAD;
7873 break;
7874 case INVTYPE_NECK:
7875 slots[0] = EQUIPMENT_SLOT_NECK;
7876 break;
7877 case INVTYPE_SHOULDERS:
7878 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7879 break;
7880 case INVTYPE_BODY:
7881 slots[0] = EQUIPMENT_SLOT_BODY;
7882 break;
7883 case INVTYPE_CHEST:
7884 slots[0] = EQUIPMENT_SLOT_CHEST;
7885 break;
7886 case INVTYPE_ROBE:
7887 slots[0] = EQUIPMENT_SLOT_CHEST;
7888 break;
7889 case INVTYPE_WAIST:
7890 slots[0] = EQUIPMENT_SLOT_WAIST;
7891 break;
7892 case INVTYPE_LEGS:
7893 slots[0] = EQUIPMENT_SLOT_LEGS;
7894 break;
7895 case INVTYPE_FEET:
7896 slots[0] = EQUIPMENT_SLOT_FEET;
7897 break;
7898 case INVTYPE_WRISTS:
7899 slots[0] = EQUIPMENT_SLOT_WRISTS;
7900 break;
7901 case INVTYPE_HANDS:
7902 slots[0] = EQUIPMENT_SLOT_HANDS;
7903 break;
7904 case INVTYPE_FINGER:
7905 slots[0] = EQUIPMENT_SLOT_FINGER1;
7906 slots[1] = EQUIPMENT_SLOT_FINGER2;
7907 break;
7908 case INVTYPE_TRINKET:
7909 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7910 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7911 break;
7912 case INVTYPE_CLOAK:
7913 slots[0] = EQUIPMENT_SLOT_BACK;
7914 break;
7915 case INVTYPE_WEAPON:
7917 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7919 // suggest offhand slot only if know dual wielding
7920 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7921 if(CanDualWield())
7922 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7923 break;
7925 case INVTYPE_SHIELD:
7926 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7927 break;
7928 case INVTYPE_RANGED:
7929 slots[0] = EQUIPMENT_SLOT_RANGED;
7930 break;
7931 case INVTYPE_2HWEAPON:
7932 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7933 if (CanDualWield() && CanTitanGrip())
7934 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7935 break;
7936 case INVTYPE_TABARD:
7937 slots[0] = EQUIPMENT_SLOT_TABARD;
7938 break;
7939 case INVTYPE_WEAPONMAINHAND:
7940 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7941 break;
7942 case INVTYPE_WEAPONOFFHAND:
7943 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7944 break;
7945 case INVTYPE_HOLDABLE:
7946 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7947 break;
7948 case INVTYPE_THROWN:
7949 slots[0] = EQUIPMENT_SLOT_RANGED;
7950 break;
7951 case INVTYPE_RANGEDRIGHT:
7952 slots[0] = EQUIPMENT_SLOT_RANGED;
7953 break;
7954 case INVTYPE_BAG:
7955 slots[0] = INVENTORY_SLOT_BAG_START + 0;
7956 slots[1] = INVENTORY_SLOT_BAG_START + 1;
7957 slots[2] = INVENTORY_SLOT_BAG_START + 2;
7958 slots[3] = INVENTORY_SLOT_BAG_START + 3;
7959 break;
7960 case INVTYPE_RELIC:
7962 switch(proto->SubClass)
7964 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7965 if (pClass == CLASS_PALADIN)
7966 slots[0] = EQUIPMENT_SLOT_RANGED;
7967 break;
7968 case ITEM_SUBCLASS_ARMOR_IDOL:
7969 if (pClass == CLASS_DRUID)
7970 slots[0] = EQUIPMENT_SLOT_RANGED;
7971 break;
7972 case ITEM_SUBCLASS_ARMOR_TOTEM:
7973 if (pClass == CLASS_SHAMAN)
7974 slots[0] = EQUIPMENT_SLOT_RANGED;
7975 break;
7976 case ITEM_SUBCLASS_ARMOR_MISC:
7977 if (pClass == CLASS_WARLOCK)
7978 slots[0] = EQUIPMENT_SLOT_RANGED;
7979 break;
7980 case ITEM_SUBCLASS_ARMOR_SIGIL:
7981 if (pClass == CLASS_DEATH_KNIGHT)
7982 slots[0] = EQUIPMENT_SLOT_RANGED;
7983 break;
7985 break;
7987 default :
7988 return NULL_SLOT;
7991 if( slot != NULL_SLOT )
7993 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7995 for (int i = 0; i < 4; ++i)
7997 if ( slots[i] == slot )
7998 return slot;
8002 else
8004 // search free slot at first
8005 for (int i = 0; i < 4; ++i)
8007 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8009 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8010 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8011 return slots[i];
8015 // if not found free and can swap return first appropriate from used
8016 for (int i = 0; i < 4; ++i)
8018 if ( slots[i] != NULL_SLOT && swap )
8019 return slots[i];
8023 // no free position
8024 return NULL_SLOT;
8027 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8029 Item *pItem;
8030 uint32 tempcount = 0;
8032 uint8 res = EQUIP_ERR_OK;
8034 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8036 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8037 if( pItem && pItem->GetEntry() == item )
8039 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8040 if(ires==EQUIP_ERR_OK)
8042 tempcount += pItem->GetCount();
8043 if( tempcount >= count )
8044 return EQUIP_ERR_OK;
8046 else
8047 res = ires;
8050 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8052 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8053 if( pItem && pItem->GetEntry() == item )
8055 tempcount += pItem->GetCount();
8056 if( tempcount >= count )
8057 return EQUIP_ERR_OK;
8060 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8062 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8063 if( pItem && pItem->GetEntry() == item )
8065 tempcount += pItem->GetCount();
8066 if( tempcount >= count )
8067 return EQUIP_ERR_OK;
8070 Bag *pBag;
8071 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8073 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8074 if( pBag )
8076 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8078 pItem = GetItemByPos( i, j );
8079 if( pItem && pItem->GetEntry() == item )
8081 tempcount += pItem->GetCount();
8082 if( tempcount >= count )
8083 return EQUIP_ERR_OK;
8089 // not found req. item count and have unequippable items
8090 return res;
8093 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8095 uint32 count = 0;
8096 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8098 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8099 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8100 count += pItem->GetCount();
8102 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8104 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8105 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8106 count += pItem->GetCount();
8108 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8110 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8111 if( pBag )
8112 count += pBag->GetItemCount(item,skipItem);
8115 if(skipItem && skipItem->GetProto()->GemProperties)
8117 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8119 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8120 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8121 count += pItem->GetGemCountWithID(item);
8125 if(inBankAlso)
8127 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8129 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8130 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8131 count += pItem->GetCount();
8133 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8135 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8136 if( pBag )
8137 count += pBag->GetItemCount(item,skipItem);
8140 if(skipItem && skipItem->GetProto()->GemProperties)
8142 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8144 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8145 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8146 count += pItem->GetGemCountWithID(item);
8151 return count;
8154 Item* Player::GetItemByGuid( uint64 guid ) const
8156 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8158 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8159 if( pItem && pItem->GetGUID() == guid )
8160 return pItem;
8162 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8164 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8165 if( pItem && pItem->GetGUID() == guid )
8166 return pItem;
8169 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8171 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8172 if( pBag )
8174 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8176 Item* pItem = pBag->GetItemByPos( j );
8177 if( pItem && pItem->GetGUID() == guid )
8178 return pItem;
8182 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8184 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8185 if( pBag )
8187 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8189 Item* pItem = pBag->GetItemByPos( j );
8190 if( pItem && pItem->GetGUID() == guid )
8191 return pItem;
8196 return NULL;
8199 Item* Player::GetItemByPos( uint16 pos ) const
8201 uint8 bag = pos >> 8;
8202 uint8 slot = pos & 255;
8203 return GetItemByPos( bag, slot );
8206 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8208 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8209 return m_items[slot];
8210 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8211 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8213 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8214 if ( pBag )
8215 return pBag->GetItemByPos(slot);
8217 return NULL;
8220 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8222 uint16 slot;
8223 switch (attackType)
8225 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8226 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8227 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8228 default: return NULL;
8231 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8232 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8233 return NULL;
8235 if(!useable)
8236 return item;
8238 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8239 return NULL;
8241 return item;
8244 Item* Player::GetShield(bool useable) const
8246 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8247 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8248 return NULL;
8250 if(!useable)
8251 return item;
8253 if( item->IsBroken())
8254 return NULL;
8256 return item;
8259 uint32 Player::GetAttackBySlot( uint8 slot )
8261 switch(slot)
8263 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8264 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8265 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8266 default: return MAX_ATTACK;
8270 bool Player::HasBankBagSlot( uint8 slot ) const
8272 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8273 if( slot < maxslot )
8274 return true;
8275 return false;
8278 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8280 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8281 return true;
8282 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8283 return true;
8284 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8285 return true;
8286 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8287 return true;
8288 return false;
8291 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8293 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8294 return true;
8295 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8296 return true;
8297 return false;
8300 bool Player::IsBankPos( uint8 bag, uint8 slot )
8302 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8303 return true;
8304 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8305 return true;
8306 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8307 return true;
8308 return false;
8311 bool Player::IsBagPos( uint16 pos )
8313 uint8 bag = pos >> 8;
8314 uint8 slot = pos & 255;
8315 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8316 return true;
8317 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8318 return true;
8319 return false;
8322 bool Player::IsValidPos( uint8 bag, uint8 slot )
8324 // post selected
8325 if(bag == NULL_BAG)
8326 return true;
8328 if (bag == INVENTORY_SLOT_BAG_0)
8330 // any post selected
8331 if (slot == NULL_SLOT)
8332 return true;
8334 // equipment
8335 if (slot < EQUIPMENT_SLOT_END)
8336 return true;
8338 // bag equip slots
8339 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8340 return true;
8342 // backpack slots
8343 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8344 return true;
8346 // keyring slots
8347 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8348 return true;
8350 // bank main slots
8351 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8352 return true;
8354 // bank bag slots
8355 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8356 return true;
8358 return false;
8361 // bag content slots
8362 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8364 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8365 if(!pBag)
8366 return false;
8368 // any post selected
8369 if (slot == NULL_SLOT)
8370 return true;
8372 return slot < pBag->GetBagSize();
8375 // bank bag content slots
8376 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8378 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8379 if(!pBag)
8380 return false;
8382 // any post selected
8383 if (slot == NULL_SLOT)
8384 return true;
8386 return slot < pBag->GetBagSize();
8389 // where this?
8390 return false;
8394 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8396 uint32 tempcount = 0;
8397 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8399 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8400 if( pItem && pItem->GetEntry() == item )
8402 tempcount += pItem->GetCount();
8403 if( tempcount >= count )
8404 return true;
8407 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8409 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8410 if( pItem && pItem->GetEntry() == item )
8412 tempcount += pItem->GetCount();
8413 if( tempcount >= count )
8414 return true;
8417 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8419 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8421 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8423 Item* pItem = GetItemByPos( i, j );
8424 if( pItem && pItem->GetEntry() == item )
8426 tempcount += pItem->GetCount();
8427 if( tempcount >= count )
8428 return true;
8434 if(inBankAlso)
8436 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8438 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8439 if( pItem && pItem->GetEntry() == item )
8441 tempcount += pItem->GetCount();
8442 if( tempcount >= count )
8443 return true;
8446 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8448 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8450 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8452 Item* pItem = GetItemByPos( i, j );
8453 if( pItem && pItem->GetEntry() == item )
8455 tempcount += pItem->GetCount();
8456 if( tempcount >= count )
8457 return true;
8464 return false;
8467 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8469 uint32 tempcount = 0;
8470 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8472 if(i==int(except_slot))
8473 continue;
8475 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8476 if( pItem && pItem->GetEntry() == item)
8478 tempcount += pItem->GetCount();
8479 if( tempcount >= count )
8480 return true;
8484 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8485 if (pProto && pProto->GemProperties)
8487 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8489 if(i==int(except_slot))
8490 continue;
8492 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8493 if( pItem && pItem->GetProto()->Socket[0].Color)
8495 tempcount += pItem->GetGemCountWithID(item);
8496 if( tempcount >= count )
8497 return true;
8502 return false;
8505 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8507 uint32 tempcount = 0;
8508 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8510 if(i==int(except_slot))
8511 continue;
8513 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8514 if (!pItem)
8515 continue;
8517 ItemPrototype const *pProto = pItem->GetProto();
8518 if (!pProto)
8519 continue;
8521 if (pProto->ItemLimitCategory == limitCategory)
8523 tempcount += pItem->GetCount();
8524 if( tempcount >= count )
8525 return true;
8528 if( pProto->Socket[0].Color)
8530 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8531 if( tempcount >= count )
8532 return true;
8536 return false;
8539 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8541 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8542 if( !pProto )
8544 if(no_space_count)
8545 *no_space_count = count;
8546 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8549 // no maximum
8550 if(pProto->MaxCount <= 0)
8551 return EQUIP_ERR_OK;
8553 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8555 if (curcount + count > uint32(pProto->MaxCount))
8557 if(no_space_count)
8558 *no_space_count = count +curcount - pProto->MaxCount;
8559 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8562 return EQUIP_ERR_OK;
8565 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8567 Item *pItem;
8568 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8570 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8571 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8572 return true;
8574 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8576 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8577 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8578 return true;
8580 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8582 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8584 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8586 pItem = GetItemByPos( i, j );
8587 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8588 return true;
8592 return false;
8595 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8597 Item* pItem2 = GetItemByPos( bag, slot );
8599 // ignore move item (this slot will be empty at move)
8600 if(pItem2==pSrcItem)
8601 pItem2 = NULL;
8603 uint32 need_space;
8605 // empty specific slot - check item fit to slot
8606 if( !pItem2 || swap )
8608 if( bag == INVENTORY_SLOT_BAG_0 )
8610 // keyring case
8611 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8612 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8614 // currencytoken case (disabled until proper implement)
8615 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8616 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8618 // prevent cheating
8619 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8620 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8622 else
8624 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8625 if( !pBag )
8626 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8628 ItemPrototype const* pBagProto = pBag->GetProto();
8629 if( !pBagProto )
8630 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8632 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8633 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8636 // non empty stack with space
8637 need_space = pProto->GetMaxStackSize();
8639 // non empty slot, check item type
8640 else
8642 // check item type
8643 if(pItem2->GetEntry() != pProto->ItemId)
8644 return EQUIP_ERR_ITEM_CANT_STACK;
8646 // check free space
8647 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8648 return EQUIP_ERR_ITEM_CANT_STACK;
8650 // free stack space or infinity
8651 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8654 if(need_space > count)
8655 need_space = count;
8657 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8658 if(!newPosition.isContainedIn(dest))
8660 dest.push_back(newPosition);
8661 count -= need_space;
8663 return EQUIP_ERR_OK;
8666 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
8668 // skip specific bag already processed in first called _CanStoreItem_InBag
8669 if(bag==skip_bag)
8670 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8672 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8673 if( !pBag )
8674 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8676 ItemPrototype const* pBagProto = pBag->GetProto();
8677 if( !pBagProto )
8678 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8680 // specialized bag mode or non-specilized
8681 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8682 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8684 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8685 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8687 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8689 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8690 if(j==skip_slot)
8691 continue;
8693 Item* pItem2 = GetItemByPos( bag, j );
8695 // ignore move item (this slot will be empty at move)
8696 if(pItem2==pSrcItem)
8697 pItem2 = NULL;
8699 // if merge skip empty, if !merge skip non-empty
8700 if((pItem2!=NULL)!=merge)
8701 continue;
8703 if( pItem2 )
8705 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8707 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8708 if(need_space > count)
8709 need_space = count;
8711 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8712 if(!newPosition.isContainedIn(dest))
8714 dest.push_back(newPosition);
8715 count -= need_space;
8717 if(count==0)
8718 return EQUIP_ERR_OK;
8722 else
8724 uint32 need_space = pProto->GetMaxStackSize();
8725 if(need_space > count)
8726 need_space = count;
8728 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8729 if(!newPosition.isContainedIn(dest))
8731 dest.push_back(newPosition);
8732 count -= need_space;
8734 if(count==0)
8735 return EQUIP_ERR_OK;
8739 return EQUIP_ERR_OK;
8742 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
8744 for(uint32 j = slot_begin; j < slot_end; ++j)
8746 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8747 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8748 continue;
8750 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8752 // ignore move item (this slot will be empty at move)
8753 if(pItem2==pSrcItem)
8754 pItem2 = NULL;
8756 // if merge skip empty, if !merge skip non-empty
8757 if((pItem2!=NULL)!=merge)
8758 continue;
8760 if( pItem2 )
8762 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8764 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8765 if(need_space > count)
8766 need_space = count;
8767 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8768 if(!newPosition.isContainedIn(dest))
8770 dest.push_back(newPosition);
8771 count -= need_space;
8773 if(count==0)
8774 return EQUIP_ERR_OK;
8778 else
8780 uint32 need_space = pProto->GetMaxStackSize();
8781 if(need_space > count)
8782 need_space = count;
8784 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8785 if(!newPosition.isContainedIn(dest))
8787 dest.push_back(newPosition);
8788 count -= need_space;
8790 if(count==0)
8791 return EQUIP_ERR_OK;
8795 return EQUIP_ERR_OK;
8798 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8800 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8802 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8803 if( !pProto )
8805 if(no_space_count)
8806 *no_space_count = count;
8807 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8810 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8812 if(no_space_count)
8813 *no_space_count = count;
8814 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8817 // check count of items (skip for auto move for same player from bank)
8818 uint32 no_similar_count = 0; // can't store this amount similar items
8819 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8820 if(res!=EQUIP_ERR_OK)
8822 if(count==no_similar_count)
8824 if(no_space_count)
8825 *no_space_count = no_similar_count;
8826 return res;
8828 count -= no_similar_count;
8831 // in specific slot
8832 if( bag != NULL_BAG && slot != NULL_SLOT )
8834 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8835 if(res!=EQUIP_ERR_OK)
8837 if(no_space_count)
8838 *no_space_count = count + no_similar_count;
8839 return res;
8842 if(count==0)
8844 if(no_similar_count==0)
8845 return EQUIP_ERR_OK;
8847 if(no_space_count)
8848 *no_space_count = count + no_similar_count;
8849 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8853 // not specific slot or have space for partly store only in specific slot
8855 // in specific bag
8856 if( bag != NULL_BAG )
8858 // search stack in bag for merge to
8859 if( pProto->Stackable != 1 )
8861 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8863 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8864 if(res!=EQUIP_ERR_OK)
8866 if(no_space_count)
8867 *no_space_count = count + no_similar_count;
8868 return res;
8871 if(count==0)
8873 if(no_similar_count==0)
8874 return EQUIP_ERR_OK;
8876 if(no_space_count)
8877 *no_space_count = count + no_similar_count;
8878 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8881 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8882 if(res!=EQUIP_ERR_OK)
8884 if(no_space_count)
8885 *no_space_count = count + no_similar_count;
8886 return res;
8889 if(count==0)
8891 if(no_similar_count==0)
8892 return EQUIP_ERR_OK;
8894 if(no_space_count)
8895 *no_space_count = count + no_similar_count;
8896 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8899 else // equipped bag
8901 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8902 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8903 if(res!=EQUIP_ERR_OK)
8904 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8906 if(res!=EQUIP_ERR_OK)
8908 if(no_space_count)
8909 *no_space_count = count + no_similar_count;
8910 return res;
8913 if(count==0)
8915 if(no_similar_count==0)
8916 return EQUIP_ERR_OK;
8918 if(no_space_count)
8919 *no_space_count = count + no_similar_count;
8920 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8925 // search free slot in bag for place to
8926 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8928 // search free slot - keyring case
8929 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8931 uint32 keyringSize = GetMaxKeyringSize();
8932 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8933 if(res!=EQUIP_ERR_OK)
8935 if(no_space_count)
8936 *no_space_count = count + no_similar_count;
8937 return res;
8940 if(count==0)
8942 if(no_similar_count==0)
8943 return EQUIP_ERR_OK;
8945 if(no_space_count)
8946 *no_space_count = count + no_similar_count;
8947 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8950 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8951 if(res!=EQUIP_ERR_OK)
8953 if(no_space_count)
8954 *no_space_count = count + no_similar_count;
8955 return res;
8958 if(count==0)
8960 if(no_similar_count==0)
8961 return EQUIP_ERR_OK;
8963 if(no_space_count)
8964 *no_space_count = count + no_similar_count;
8965 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8968 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8970 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8971 if(res!=EQUIP_ERR_OK)
8973 if(no_space_count)
8974 *no_space_count = count + no_similar_count;
8975 return res;
8978 if(count==0)
8980 if(no_similar_count==0)
8981 return EQUIP_ERR_OK;
8983 if(no_space_count)
8984 *no_space_count = count + no_similar_count;
8985 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8989 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8990 if(res!=EQUIP_ERR_OK)
8992 if(no_space_count)
8993 *no_space_count = count + no_similar_count;
8994 return res;
8997 if(count==0)
8999 if(no_similar_count==0)
9000 return EQUIP_ERR_OK;
9002 if(no_space_count)
9003 *no_space_count = count + no_similar_count;
9004 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9007 else // equipped bag
9009 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9010 if(res!=EQUIP_ERR_OK)
9011 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9013 if(res!=EQUIP_ERR_OK)
9015 if(no_space_count)
9016 *no_space_count = count + no_similar_count;
9017 return res;
9020 if(count==0)
9022 if(no_similar_count==0)
9023 return EQUIP_ERR_OK;
9025 if(no_space_count)
9026 *no_space_count = count + no_similar_count;
9027 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9032 // not specific bag or have space for partly store only in specific bag
9034 // search stack for merge to
9035 if( pProto->Stackable != 1 )
9037 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9038 if(res!=EQUIP_ERR_OK)
9040 if(no_space_count)
9041 *no_space_count = count + no_similar_count;
9042 return res;
9045 if(count==0)
9047 if(no_similar_count==0)
9048 return EQUIP_ERR_OK;
9050 if(no_space_count)
9051 *no_space_count = count + no_similar_count;
9052 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9055 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9056 if(res!=EQUIP_ERR_OK)
9058 if(no_space_count)
9059 *no_space_count = count + no_similar_count;
9060 return res;
9063 if(count==0)
9065 if(no_similar_count==0)
9066 return EQUIP_ERR_OK;
9068 if(no_space_count)
9069 *no_space_count = count + no_similar_count;
9070 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9073 if( pProto->BagFamily )
9075 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9077 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9078 if(res!=EQUIP_ERR_OK)
9079 continue;
9081 if(count==0)
9083 if(no_similar_count==0)
9084 return EQUIP_ERR_OK;
9086 if(no_space_count)
9087 *no_space_count = count + no_similar_count;
9088 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9093 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9095 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9096 if(res!=EQUIP_ERR_OK)
9097 continue;
9099 if(count==0)
9101 if(no_similar_count==0)
9102 return EQUIP_ERR_OK;
9104 if(no_space_count)
9105 *no_space_count = count + no_similar_count;
9106 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9111 // search free slot - special bag case
9112 if( pProto->BagFamily )
9114 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9116 uint32 keyringSize = GetMaxKeyringSize();
9117 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9118 if(res!=EQUIP_ERR_OK)
9120 if(no_space_count)
9121 *no_space_count = count + no_similar_count;
9122 return res;
9125 if(count==0)
9127 if(no_similar_count==0)
9128 return EQUIP_ERR_OK;
9130 if(no_space_count)
9131 *no_space_count = count + no_similar_count;
9132 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9135 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9137 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9138 if(res!=EQUIP_ERR_OK)
9140 if(no_space_count)
9141 *no_space_count = count + no_similar_count;
9142 return res;
9145 if(count==0)
9147 if(no_similar_count==0)
9148 return EQUIP_ERR_OK;
9150 if(no_space_count)
9151 *no_space_count = count + no_similar_count;
9152 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9156 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9158 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9159 if(res!=EQUIP_ERR_OK)
9160 continue;
9162 if(count==0)
9164 if(no_similar_count==0)
9165 return EQUIP_ERR_OK;
9167 if(no_space_count)
9168 *no_space_count = count + no_similar_count;
9169 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9174 // search free slot
9175 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9176 if(res!=EQUIP_ERR_OK)
9178 if(no_space_count)
9179 *no_space_count = count + no_similar_count;
9180 return res;
9183 if(count==0)
9185 if(no_similar_count==0)
9186 return EQUIP_ERR_OK;
9188 if(no_space_count)
9189 *no_space_count = count + no_similar_count;
9190 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9193 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9195 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9196 if(res!=EQUIP_ERR_OK)
9197 continue;
9199 if(count==0)
9201 if(no_similar_count==0)
9202 return EQUIP_ERR_OK;
9204 if(no_space_count)
9205 *no_space_count = count + no_similar_count;
9206 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9210 if(no_space_count)
9211 *no_space_count = count + no_similar_count;
9213 return EQUIP_ERR_INVENTORY_FULL;
9216 //////////////////////////////////////////////////////////////////////////
9217 uint8 Player::CanStoreItems( Item **pItems,int count) const
9219 Item *pItem2;
9221 // fill space table
9222 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9223 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9224 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9225 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9227 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9228 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9229 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9230 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9232 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9234 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9236 if (pItem2 && !pItem2->IsInTrade())
9238 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9242 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9244 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9246 if (pItem2 && !pItem2->IsInTrade())
9248 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9252 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9254 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9256 if (pItem2 && !pItem2->IsInTrade())
9258 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9262 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9264 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9266 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9268 pItem2 = GetItemByPos( i, j );
9269 if (pItem2 && !pItem2->IsInTrade())
9271 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9277 // check free space for all items
9278 for (int k = 0; k < count; ++k)
9280 Item *pItem = pItems[k];
9282 // no item
9283 if (!pItem) continue;
9285 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9286 ItemPrototype const *pProto = pItem->GetProto();
9288 // strange item
9289 if( !pProto )
9290 return EQUIP_ERR_ITEM_NOT_FOUND;
9292 // item it 'bind'
9293 if(pItem->IsBindedNotWith(GetGUID()))
9294 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9296 Bag *pBag;
9297 ItemPrototype const *pBagProto;
9299 // item is 'one item only'
9300 uint8 res = CanTakeMoreSimilarItems(pItem);
9301 if(res != EQUIP_ERR_OK)
9302 return res;
9304 // search stack for merge to
9305 if( pProto->Stackable != 1 )
9307 bool b_found = false;
9309 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9311 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9312 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9314 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9315 b_found = true;
9316 break;
9319 if (b_found) continue;
9321 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9323 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9324 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9326 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9327 b_found = true;
9328 break;
9331 if (b_found) continue;
9333 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9335 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9336 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9338 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9339 b_found = true;
9340 break;
9343 if (b_found) continue;
9345 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9347 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9348 if( pBag )
9350 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9352 pItem2 = GetItemByPos( t, j );
9353 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9355 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9356 b_found = true;
9357 break;
9362 if (b_found) continue;
9365 // special bag case
9366 if( pProto->BagFamily )
9368 bool b_found = false;
9369 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9371 uint32 keyringSize = GetMaxKeyringSize();
9372 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9374 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9376 inv_keys[t-KEYRING_SLOT_START] = 1;
9377 b_found = true;
9378 break;
9383 if (b_found) continue;
9385 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9387 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9389 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9391 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9392 b_found = true;
9393 break;
9398 if (b_found) continue;
9400 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9402 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9403 if( pBag )
9405 pBagProto = pBag->GetProto();
9407 // not plain container check
9408 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9409 ItemCanGoIntoBag(pProto,pBagProto) )
9411 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9413 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9415 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9416 b_found = true;
9417 break;
9423 if (b_found) continue;
9426 // search free slot
9427 bool b_found = false;
9428 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9430 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9432 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9433 b_found = true;
9434 break;
9437 if (b_found) continue;
9439 // search free slot in bags
9440 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9442 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9443 if( pBag )
9445 pBagProto = pBag->GetProto();
9447 // special bag already checked
9448 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9449 continue;
9451 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9453 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9455 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9456 b_found = true;
9457 break;
9463 // no free slot found?
9464 if (!b_found)
9465 return EQUIP_ERR_INVENTORY_FULL;
9468 return EQUIP_ERR_OK;
9471 //////////////////////////////////////////////////////////////////////////
9472 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9474 dest = 0;
9475 Item *pItem = Item::CreateItem( item, 1, this );
9476 if( pItem )
9478 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9479 delete pItem;
9480 return result;
9483 return EQUIP_ERR_ITEM_NOT_FOUND;
9486 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9488 dest = 0;
9489 if( pItem )
9491 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9492 ItemPrototype const *pProto = pItem->GetProto();
9493 if( pProto )
9495 if(pItem->IsBindedNotWith(GetGUID()))
9496 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9498 // check count of items (skip for auto move for same player from bank)
9499 uint8 res = CanTakeMoreSimilarItems(pItem);
9500 if(res != EQUIP_ERR_OK)
9501 return res;
9503 // check this only in game
9504 if(not_loading)
9506 // May be here should be more stronger checks; STUNNED checked
9507 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9508 if (hasUnitState(UNIT_STAT_STUNNED))
9509 return EQUIP_ERR_YOU_ARE_STUNNED;
9511 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9512 // - combat
9513 // - in-progress arenas
9514 if( !pProto->CanChangeEquipStateInCombat() )
9516 if( isInCombat() )
9517 return EQUIP_ERR_NOT_IN_COMBAT;
9519 if(BattleGround* bg = GetBattleGround())
9520 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9521 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9524 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9525 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9527 if(IsNonMeleeSpellCasted(false))
9528 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9531 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9532 if( eslot == NULL_SLOT )
9533 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9535 uint8 msg = CanUseItem( pItem , not_loading );
9536 if( msg != EQUIP_ERR_OK )
9537 return msg;
9538 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9539 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9541 // if swap ignore item (equipped also)
9542 if(uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9543 return res2;
9545 // check unique-equipped special item classes
9546 if (pProto->Class == ITEM_CLASS_QUIVER)
9548 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9550 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9552 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9554 if( pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot ) )
9556 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9557 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9558 else
9559 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9566 uint32 type = pProto->InventoryType;
9568 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9570 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9572 if(!CanDualWield())
9573 return EQUIP_ERR_CANT_DUAL_WIELD;
9575 else if (type == INVTYPE_2HWEAPON)
9577 if(!CanDualWield() || !CanTitanGrip())
9578 return EQUIP_ERR_CANT_DUAL_WIELD;
9581 if(IsTwoHandUsed())
9582 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9585 // equip two-hand weapon case (with possible unequip 2 items)
9586 if( type == INVTYPE_2HWEAPON )
9588 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9590 if (!CanTitanGrip())
9591 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9593 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9594 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9596 if (!CanTitanGrip())
9598 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9599 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9600 ItemPosCountVec off_dest;
9601 if( offItem && (!not_loading ||
9602 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9603 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9604 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9607 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9608 return EQUIP_ERR_OK;
9611 if( !swap )
9612 return EQUIP_ERR_ITEM_NOT_FOUND;
9613 else
9614 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9617 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9619 // Applied only to equipped items and bank bags
9620 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9621 return EQUIP_ERR_OK;
9623 Item* pItem = GetItemByPos(pos);
9625 // Applied only to existed equipped item
9626 if( !pItem )
9627 return EQUIP_ERR_OK;
9629 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9631 ItemPrototype const *pProto = pItem->GetProto();
9632 if( !pProto )
9633 return EQUIP_ERR_ITEM_NOT_FOUND;
9635 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9636 // - combat
9637 // - in-progress arenas
9638 if( !pProto->CanChangeEquipStateInCombat() )
9640 if( isInCombat() )
9641 return EQUIP_ERR_NOT_IN_COMBAT;
9643 if(BattleGround* bg = GetBattleGround())
9644 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9645 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9648 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9649 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9651 return EQUIP_ERR_OK;
9654 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9656 if( !pItem )
9657 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9659 uint32 count = pItem->GetCount();
9661 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9662 ItemPrototype const *pProto = pItem->GetProto();
9663 if( !pProto )
9664 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9666 if( pItem->IsBindedNotWith(GetGUID()) )
9667 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9669 // check count of items (skip for auto move for same player from bank)
9670 uint8 res = CanTakeMoreSimilarItems(pItem);
9671 if(res != EQUIP_ERR_OK)
9672 return res;
9674 // in specific slot
9675 if( bag != NULL_BAG && slot != NULL_SLOT )
9677 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9679 if (!pItem->IsBag())
9680 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9682 if( !HasBankBagSlot( slot ) )
9683 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9685 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9686 return cantuse;
9689 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9690 if(res!=EQUIP_ERR_OK)
9691 return res;
9693 if(count==0)
9694 return EQUIP_ERR_OK;
9697 // not specific slot or have space for partly store only in specific slot
9699 // in specific bag
9700 if( bag != NULL_BAG )
9702 if( pProto->InventoryType == INVTYPE_BAG )
9704 Bag *pBag = (Bag*)pItem;
9705 if( pBag && !pBag->IsEmpty() )
9706 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9709 // search stack in bag for merge to
9710 if( pProto->Stackable != 1 )
9712 if( bag == INVENTORY_SLOT_BAG_0 )
9714 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9715 if(res!=EQUIP_ERR_OK)
9716 return res;
9718 if(count==0)
9719 return EQUIP_ERR_OK;
9721 else
9723 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9724 if(res!=EQUIP_ERR_OK)
9725 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9727 if(res!=EQUIP_ERR_OK)
9728 return res;
9730 if(count==0)
9731 return EQUIP_ERR_OK;
9735 // search free slot in bag
9736 if( bag == INVENTORY_SLOT_BAG_0 )
9738 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9739 if(res!=EQUIP_ERR_OK)
9740 return res;
9742 if(count==0)
9743 return EQUIP_ERR_OK;
9745 else
9747 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9748 if(res != EQUIP_ERR_OK)
9749 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9751 if(res != EQUIP_ERR_OK)
9752 return res;
9754 if(count == 0)
9755 return EQUIP_ERR_OK;
9759 // not specific bag or have space for partly store only in specific bag
9761 // search stack for merge to
9762 if( pProto->Stackable != 1 )
9764 // in slots
9765 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9766 if(res != EQUIP_ERR_OK)
9767 return res;
9769 if(count == 0)
9770 return EQUIP_ERR_OK;
9772 // in special bags
9773 if( pProto->BagFamily )
9775 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9777 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9778 if(res!=EQUIP_ERR_OK)
9779 continue;
9781 if(count==0)
9782 return EQUIP_ERR_OK;
9786 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9788 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9789 if(res!=EQUIP_ERR_OK)
9790 continue;
9792 if(count==0)
9793 return EQUIP_ERR_OK;
9797 // search free place in special bag
9798 if( pProto->BagFamily )
9800 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9802 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9803 if(res!=EQUIP_ERR_OK)
9804 continue;
9806 if(count==0)
9807 return EQUIP_ERR_OK;
9811 // search free space
9812 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9813 if(res!=EQUIP_ERR_OK)
9814 return res;
9816 if(count==0)
9817 return EQUIP_ERR_OK;
9819 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9821 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9822 if(res!=EQUIP_ERR_OK)
9823 continue;
9825 if(count==0)
9826 return EQUIP_ERR_OK;
9828 return EQUIP_ERR_BANK_FULL;
9831 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9833 if( pItem )
9835 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9836 if( !isAlive() && not_loading )
9837 return EQUIP_ERR_YOU_ARE_DEAD;
9838 //if( isStunned() )
9839 // return EQUIP_ERR_YOU_ARE_STUNNED;
9840 ItemPrototype const *pProto = pItem->GetProto();
9841 if( pProto )
9843 if( pItem->IsBindedNotWith(GetGUID()) )
9844 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9845 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9846 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9847 if( pItem->GetSkill() != 0 )
9849 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9850 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9852 if( pProto->RequiredSkill != 0 )
9854 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9855 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9856 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9857 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9859 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9860 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9861 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9862 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9863 if( getLevel() < pProto->RequiredLevel )
9864 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9865 return EQUIP_ERR_OK;
9868 return EQUIP_ERR_ITEM_NOT_FOUND;
9871 bool Player::CanUseItem( ItemPrototype const *pProto )
9873 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9875 if( pProto )
9877 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9878 return false;
9879 if( pProto->RequiredSkill != 0 )
9881 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9882 return false;
9883 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9884 return false;
9886 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9887 return false;
9888 if( getLevel() < pProto->RequiredLevel )
9889 return false;
9890 return true;
9892 return false;
9895 uint8 Player::CanUseAmmo( uint32 item ) const
9897 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9898 if( !isAlive() )
9899 return EQUIP_ERR_YOU_ARE_DEAD;
9900 //if( isStunned() )
9901 // return EQUIP_ERR_YOU_ARE_STUNNED;
9902 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9903 if( pProto )
9905 if( pProto->InventoryType!= INVTYPE_AMMO )
9906 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9907 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9908 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9909 if( pProto->RequiredSkill != 0 )
9911 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9912 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9913 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9914 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9916 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9917 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9918 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9919 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9921 if( getLevel() < pProto->RequiredLevel )
9922 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9924 // Requires No Ammo
9925 if(GetDummyAura(46699))
9926 return EQUIP_ERR_BAG_FULL6;
9928 return EQUIP_ERR_OK;
9930 return EQUIP_ERR_ITEM_NOT_FOUND;
9933 void Player::SetAmmo( uint32 item )
9935 if(!item)
9936 return;
9938 // already set
9939 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9940 return;
9942 // check ammo
9943 if(item)
9945 uint8 msg = CanUseAmmo( item );
9946 if( msg != EQUIP_ERR_OK )
9948 SendEquipError( msg, NULL, NULL );
9949 return;
9953 SetUInt32Value(PLAYER_AMMO_ID, item);
9955 _ApplyAmmoBonuses();
9958 void Player::RemoveAmmo()
9960 SetUInt32Value(PLAYER_AMMO_ID, 0);
9962 m_ammoDPS = 0.0f;
9964 if(CanModifyStats())
9965 UpdateDamagePhysical(RANGED_ATTACK);
9968 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9969 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9971 uint32 count = 0;
9972 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9973 count += itr->count;
9975 Item *pItem = Item::CreateItem( item, count, this );
9976 if( pItem )
9978 ItemAddedQuestCheck( item, count );
9979 if(randomPropertyId)
9980 pItem->SetItemRandomProperties(randomPropertyId);
9981 pItem = StoreItem( dest, pItem, update );
9983 return pItem;
9986 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9988 if( !pItem )
9989 return NULL;
9991 Item* lastItem = pItem;
9992 uint32 entry = pItem->GetEntry();
9993 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9995 uint16 pos = itr->pos;
9996 uint32 count = itr->count;
9998 ++itr;
10000 if(itr == dest.end())
10002 lastItem = _StoreItem(pos,pItem,count,false,update);
10003 break;
10006 lastItem = _StoreItem(pos,pItem,count,true,update);
10008 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10009 return lastItem;
10012 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10013 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10015 if( !pItem )
10016 return NULL;
10018 uint8 bag = pos >> 8;
10019 uint8 slot = pos & 255;
10021 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10023 Item *pItem2 = GetItemByPos( bag, slot );
10025 if (!pItem2)
10027 if (clone)
10028 pItem = pItem->CloneItem(count, this);
10029 else
10030 pItem->SetCount(count);
10032 if (!pItem)
10033 return NULL;
10035 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10036 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10037 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10038 pItem->SetBinding( true );
10040 if (bag == INVENTORY_SLOT_BAG_0)
10042 m_items[slot] = pItem;
10043 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10044 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10045 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10047 pItem->SetSlot( slot );
10048 pItem->SetContainer( NULL );
10050 // need update known currency
10051 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10052 UpdateKnownCurrencies(pItem->GetEntry(), true);
10054 if (IsInWorld() && update)
10056 pItem->AddToWorld();
10057 pItem->SendUpdateToPlayer( this );
10060 pItem->SetState(ITEM_CHANGED, this);
10062 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10064 pBag->StoreItem( slot, pItem, update );
10065 if( IsInWorld() && update )
10067 pItem->AddToWorld();
10068 pItem->SendUpdateToPlayer( this );
10070 pItem->SetState(ITEM_CHANGED, this);
10071 pBag->SetState(ITEM_CHANGED, this);
10074 AddEnchantmentDurations(pItem);
10075 AddItemDurations(pItem);
10077 return pItem;
10079 else
10081 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10082 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10083 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10084 pItem2->SetBinding( true );
10086 pItem2->SetCount( pItem2->GetCount() + count );
10087 if (IsInWorld() && update)
10088 pItem2->SendUpdateToPlayer( this );
10090 if (!clone)
10092 // delete item (it not in any slot currently)
10093 if (IsInWorld() && update)
10095 pItem->RemoveFromWorld();
10096 pItem->DestroyForPlayer( this );
10099 RemoveEnchantmentDurations(pItem);
10100 RemoveItemDurations(pItem);
10102 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10103 pItem->SetState(ITEM_REMOVED, this);
10106 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10107 AddEnchantmentDurations(pItem2);
10109 pItem2->SetState(ITEM_CHANGED, this);
10111 return pItem2;
10115 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10117 if (Item *pItem = Item::CreateItem( item, 1, this ))
10119 ItemAddedQuestCheck( item, 1 );
10120 return EquipItem( pos, pItem, update );
10123 return NULL;
10126 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10129 AddEnchantmentDurations(pItem);
10130 AddItemDurations(pItem);
10132 uint8 bag = pos >> 8;
10133 uint8 slot = pos & 255;
10135 Item *pItem2 = GetItemByPos( bag, slot );
10137 if( !pItem2 )
10139 VisualizeItem( slot, pItem);
10141 if(isAlive())
10143 ItemPrototype const *pProto = pItem->GetProto();
10145 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10146 if(pProto && pProto->ItemSet)
10147 AddItemsSetItem(this, pItem);
10149 _ApplyItemMods(pItem, slot, true);
10151 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10153 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10155 if (getClass() == CLASS_ROGUE)
10156 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10158 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10160 if (!spellProto)
10161 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10162 else
10164 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10166 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10167 data << uint64(GetGUID());
10168 data << uint8(1);
10169 data << uint32(cooldownSpell);
10170 data << uint32(0);
10171 GetSession()->SendPacket(&data);
10176 if( IsInWorld() && update )
10178 pItem->AddToWorld();
10179 pItem->SendUpdateToPlayer( this );
10182 ApplyEquipCooldown(pItem);
10184 if( slot == EQUIPMENT_SLOT_MAINHAND )
10185 UpdateExpertise(BASE_ATTACK);
10186 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10187 UpdateExpertise(OFF_ATTACK);
10189 else
10191 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10192 if( IsInWorld() && update )
10193 pItem2->SendUpdateToPlayer( this );
10195 // delete item (it not in any slot currently)
10196 //pItem->DeleteFromDB();
10197 if( IsInWorld() && update )
10199 pItem->RemoveFromWorld();
10200 pItem->DestroyForPlayer( this );
10203 RemoveEnchantmentDurations(pItem);
10204 RemoveItemDurations(pItem);
10206 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10207 pItem->SetState(ITEM_REMOVED, this);
10208 pItem2->SetState(ITEM_CHANGED, this);
10210 ApplyEquipCooldown(pItem2);
10212 return pItem2;
10215 // only for full equip instead adding to stack
10216 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10218 return pItem;
10221 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10223 if( pItem )
10225 AddEnchantmentDurations(pItem);
10226 AddItemDurations(pItem);
10228 uint8 slot = pos & 255;
10229 VisualizeItem( slot, pItem);
10231 if( IsInWorld() )
10233 pItem->AddToWorld();
10234 pItem->SendUpdateToPlayer( this );
10239 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10241 if(pItem)
10243 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10244 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10245 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10247 else
10249 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10250 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10254 void Player::VisualizeItem( uint8 slot, Item *pItem)
10256 if(!pItem)
10257 return;
10259 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10260 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10261 pItem->SetBinding( true );
10263 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10265 m_items[slot] = pItem;
10266 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10267 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10268 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10269 pItem->SetSlot( slot );
10270 pItem->SetContainer( NULL );
10272 if( slot < EQUIPMENT_SLOT_END )
10273 SetVisibleItemSlot(slot, pItem);
10275 pItem->SetState(ITEM_CHANGED, this);
10278 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10280 // note: removeitem does not actually change the item
10281 // it only takes the item out of storage temporarily
10282 // note2: if removeitem is to be used for delinking
10283 // the item must be removed from the player's updatequeue
10285 Item *pItem = GetItemByPos( bag, slot );
10286 if( pItem )
10288 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10290 RemoveEnchantmentDurations(pItem);
10291 RemoveItemDurations(pItem);
10293 if( bag == INVENTORY_SLOT_BAG_0 )
10295 if ( slot < INVENTORY_SLOT_BAG_END )
10297 ItemPrototype const *pProto = pItem->GetProto();
10298 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10300 if(pProto && pProto->ItemSet)
10301 RemoveItemsSetItem(this, pProto);
10303 _ApplyItemMods(pItem, slot, false);
10305 // remove item dependent auras and casts (only weapon and armor slots)
10306 if(slot < EQUIPMENT_SLOT_END)
10308 RemoveItemDependentAurasAndCasts(pItem);
10310 // remove held enchantments, update expertise
10311 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10313 if (pItem->GetItemSuffixFactor())
10315 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10316 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10318 else
10320 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10321 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10324 UpdateExpertise(BASE_ATTACK);
10326 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10327 UpdateExpertise(OFF_ATTACK);
10330 // need update known currency
10331 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10332 UpdateKnownCurrencies(pItem->GetEntry(), false);
10334 m_items[slot] = NULL;
10335 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10337 if ( slot < EQUIPMENT_SLOT_END )
10338 SetVisibleItemSlot(slot, NULL);
10340 else
10342 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10343 if( pBag )
10344 pBag->RemoveItem(slot, update);
10346 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10347 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10348 pItem->SetSlot( NULL_SLOT );
10349 if( IsInWorld() && update )
10350 pItem->SendUpdateToPlayer( this );
10354 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10355 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10357 if(Item* it = GetItemByPos(bag,slot))
10359 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10360 RemoveItem(bag, slot, update);
10361 it->RemoveFromUpdateQueueOf(this);
10362 if(it->IsInWorld())
10364 it->RemoveFromWorld();
10365 it->DestroyForPlayer( this );
10370 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10371 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10373 // update quest counters
10374 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10376 // store item
10377 Item* pLastItem = StoreItem(dest, pItem, update);
10379 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10380 if(pLastItem == pItem)
10382 // update owner for last item (this can be original item with wrong owner
10383 if(pLastItem->GetOwnerGUID() != GetGUID())
10384 pLastItem->SetOwnerGUID(GetGUID());
10386 // if this original item then it need create record in inventory
10387 // in case trade we already have item in other player inventory
10388 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10392 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10394 Item *pItem = GetItemByPos( bag, slot );
10395 if( pItem )
10397 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10399 // start from destroy contained items (only equipped bag can have its)
10400 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10402 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10403 DestroyItem(slot, i, update);
10406 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10407 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10409 RemoveEnchantmentDurations(pItem);
10410 RemoveItemDurations(pItem);
10412 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10414 if( bag == INVENTORY_SLOT_BAG_0 )
10416 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10418 // equipment and equipped bags can have applied bonuses
10419 if ( slot < INVENTORY_SLOT_BAG_END )
10421 ItemPrototype const *pProto = pItem->GetProto();
10423 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10424 if(pProto && pProto->ItemSet)
10425 RemoveItemsSetItem(this, pProto);
10427 _ApplyItemMods(pItem, slot, false);
10430 if ( slot < EQUIPMENT_SLOT_END )
10432 // remove item dependent auras and casts (only weapon and armor slots)
10433 RemoveItemDependentAurasAndCasts(pItem);
10435 // update expertise
10436 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10437 UpdateExpertise(BASE_ATTACK);
10438 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10439 UpdateExpertise(OFF_ATTACK);
10441 // equipment visual show
10442 SetVisibleItemSlot(slot, NULL);
10444 // need update known currency
10445 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10446 UpdateKnownCurrencies(pItem->GetEntry(), false);
10448 m_items[slot] = NULL;
10450 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10451 pBag->RemoveItem(slot, update);
10453 if( IsInWorld() && update )
10455 pItem->RemoveFromWorld();
10456 pItem->DestroyForPlayer(this);
10459 //pItem->SetOwnerGUID(0);
10460 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10461 pItem->SetSlot( NULL_SLOT );
10462 pItem->SetState(ITEM_REMOVED, this);
10466 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10468 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10469 uint32 remcount = 0;
10471 // in inventory
10472 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10474 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10476 if (pItem->GetEntry() == item)
10478 if (pItem->GetCount() + remcount <= count)
10480 // all items in inventory can unequipped
10481 remcount += pItem->GetCount();
10482 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10484 if (remcount >= count)
10485 return;
10487 else
10489 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10490 pItem->SetCount( pItem->GetCount() - count + remcount );
10491 if (IsInWorld() & update)
10492 pItem->SendUpdateToPlayer( this );
10493 pItem->SetState(ITEM_CHANGED, this);
10494 return;
10500 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10502 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10504 if (pItem->GetEntry() == item)
10506 if (pItem->GetCount() + remcount <= count)
10508 // all keys can be unequipped
10509 remcount += pItem->GetCount();
10510 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10512 if (remcount >= count)
10513 return;
10515 else
10517 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10518 pItem->SetCount( pItem->GetCount() - count + remcount );
10519 if (IsInWorld() & update)
10520 pItem->SendUpdateToPlayer( this );
10521 pItem->SetState(ITEM_CHANGED, this);
10522 return;
10528 // in inventory bags
10529 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10531 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10533 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10535 if(Item* pItem = pBag->GetItemByPos(j))
10537 if (pItem->GetEntry() == item)
10539 // all items in bags can be unequipped
10540 if (pItem->GetCount() + remcount <= count)
10542 remcount += pItem->GetCount();
10543 DestroyItem( i, j, update );
10545 if (remcount >= count)
10546 return;
10548 else
10550 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10551 pItem->SetCount( pItem->GetCount() - count + remcount );
10552 if (IsInWorld() && update)
10553 pItem->SendUpdateToPlayer( this );
10554 pItem->SetState(ITEM_CHANGED, this);
10555 return;
10563 // in equipment and bag list
10564 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10566 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10568 if (pItem && pItem->GetEntry() == item)
10570 if (pItem->GetCount() + remcount <= count)
10572 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10574 remcount += pItem->GetCount();
10575 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10577 if (remcount >= count)
10578 return;
10581 else
10583 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10584 pItem->SetCount( pItem->GetCount() - count + remcount );
10585 if (IsInWorld() & update)
10586 pItem->SendUpdateToPlayer( this );
10587 pItem->SetState(ITEM_CHANGED, this);
10588 return;
10595 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10597 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10599 // in inventory
10600 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10601 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10602 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10603 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10605 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10606 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10607 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10608 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10610 // in inventory bags
10611 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10612 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10613 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10614 if (Item* pItem = pBag->GetItemByPos(j))
10615 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10616 DestroyItem( i, j, update);
10618 // in equipment and bag list
10619 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10620 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10621 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10622 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10625 void Player::DestroyConjuredItems( bool update )
10627 // used when entering arena
10628 // destroys all conjured items
10629 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10631 // in inventory
10632 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10633 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10634 if (pItem->IsConjuredConsumable())
10635 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10637 // in inventory bags
10638 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10639 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10640 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10641 if (Item* pItem = pBag->GetItemByPos(j))
10642 if (pItem->IsConjuredConsumable())
10643 DestroyItem( i, j, update);
10645 // in equipment and bag list
10646 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10647 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10648 if (pItem->IsConjuredConsumable())
10649 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10652 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10654 if(!pItem)
10655 return;
10657 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10659 if( pItem->GetCount() <= count )
10661 count -= pItem->GetCount();
10663 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10665 else
10667 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10668 pItem->SetCount( pItem->GetCount() - count );
10669 count = 0;
10670 if( IsInWorld() & update )
10671 pItem->SendUpdateToPlayer( this );
10672 pItem->SetState(ITEM_CHANGED, this);
10676 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10678 uint8 srcbag = src >> 8;
10679 uint8 srcslot = src & 255;
10681 uint8 dstbag = dst >> 8;
10682 uint8 dstslot = dst & 255;
10684 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10685 if( !pSrcItem )
10687 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10688 return;
10691 // not let split all items (can be only at cheating)
10692 if(pSrcItem->GetCount() == count)
10694 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10695 return;
10698 // not let split more existed items (can be only at cheating)
10699 if(pSrcItem->GetCount() < count)
10701 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10702 return;
10705 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10707 //best error message found for attempting to split while looting
10708 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10709 return;
10712 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10713 Item *pNewItem = pSrcItem->CloneItem( count, this );
10714 if( !pNewItem )
10716 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10717 return;
10720 if( IsInventoryPos( dst ) )
10722 // change item amount before check (for unique max count check)
10723 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10725 ItemPosCountVec dest;
10726 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10727 if( msg != EQUIP_ERR_OK )
10729 delete pNewItem;
10730 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10731 SendEquipError( msg, pSrcItem, NULL );
10732 return;
10735 if( IsInWorld() )
10736 pSrcItem->SendUpdateToPlayer( this );
10737 pSrcItem->SetState(ITEM_CHANGED, this);
10738 StoreItem( dest, pNewItem, true);
10740 else if( IsBankPos ( dst ) )
10742 // change item amount before check (for unique max count check)
10743 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10745 ItemPosCountVec dest;
10746 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10747 if( msg != EQUIP_ERR_OK )
10749 delete pNewItem;
10750 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10751 SendEquipError( msg, pSrcItem, NULL );
10752 return;
10755 if( IsInWorld() )
10756 pSrcItem->SendUpdateToPlayer( this );
10757 pSrcItem->SetState(ITEM_CHANGED, this);
10758 BankItem( dest, pNewItem, true);
10760 else if( IsEquipmentPos ( dst ) )
10762 // change item amount before check (for unique max count check), provide space for splitted items
10763 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10765 uint16 dest;
10766 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10767 if( msg != EQUIP_ERR_OK )
10769 delete pNewItem;
10770 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10771 SendEquipError( msg, pSrcItem, NULL );
10772 return;
10775 if( IsInWorld() )
10776 pSrcItem->SendUpdateToPlayer( this );
10777 pSrcItem->SetState(ITEM_CHANGED, this);
10778 EquipItem( dest, pNewItem, true);
10779 AutoUnequipOffhandIfNeed();
10783 void Player::SwapItem( uint16 src, uint16 dst )
10785 uint8 srcbag = src >> 8;
10786 uint8 srcslot = src & 255;
10788 uint8 dstbag = dst >> 8;
10789 uint8 dstslot = dst & 255;
10791 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10792 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10794 if( !pSrcItem )
10795 return;
10797 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10799 if(!isAlive() )
10801 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10802 return;
10805 // SRC checks
10807 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10809 //best error message found for attempting to swap while looting
10810 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10811 return;
10814 // check unequip potability for equipped items and bank bags
10815 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10817 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10818 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10819 if(msg != EQUIP_ERR_OK)
10821 SendEquipError( msg, pSrcItem, pDstItem );
10822 return;
10826 // prevent put equipped/bank bag in self
10827 if( IsBagPos ( src ) && srcslot == dstbag)
10829 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10830 return;
10833 // DST checks
10835 if (pDstItem)
10837 if(pDstItem->m_lootGenerated) // prevent swap looting item
10839 //best error message found for attempting to swap while looting
10840 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10841 return;
10844 // check unequip potability for equipped items and bank bags
10845 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10847 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10848 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10849 if(msg != EQUIP_ERR_OK)
10851 SendEquipError( msg, pSrcItem, pDstItem );
10852 return;
10857 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10858 // or swap empty bag with another empty or not empty bag (with items exchange)
10860 // Move case
10861 if( !pDstItem )
10863 if( IsInventoryPos( dst ) )
10865 ItemPosCountVec dest;
10866 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10867 if( msg != EQUIP_ERR_OK )
10869 SendEquipError( msg, pSrcItem, NULL );
10870 return;
10873 RemoveItem(srcbag, srcslot, true);
10874 StoreItem( dest, pSrcItem, true);
10876 else if( IsBankPos ( dst ) )
10878 ItemPosCountVec dest;
10879 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10880 if( msg != EQUIP_ERR_OK )
10882 SendEquipError( msg, pSrcItem, NULL );
10883 return;
10886 RemoveItem(srcbag, srcslot, true);
10887 BankItem( dest, pSrcItem, true);
10889 else if( IsEquipmentPos ( dst ) )
10891 uint16 dest;
10892 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10893 if( msg != EQUIP_ERR_OK )
10895 SendEquipError( msg, pSrcItem, NULL );
10896 return;
10899 RemoveItem(srcbag, srcslot, true);
10900 EquipItem(dest, pSrcItem, true);
10901 AutoUnequipOffhandIfNeed();
10904 return;
10907 // attempt merge to / fill target item
10908 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
10910 uint8 msg;
10911 ItemPosCountVec sDest;
10912 uint16 eDest;
10913 if( IsInventoryPos( dst ) )
10914 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10915 else if( IsBankPos ( dst ) )
10916 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10917 else if( IsEquipmentPos ( dst ) )
10918 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10919 else
10920 return;
10922 // can be merge/fill
10923 if(msg == EQUIP_ERR_OK)
10925 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
10927 RemoveItem(srcbag, srcslot, true);
10929 if( IsInventoryPos( dst ) )
10930 StoreItem( sDest, pSrcItem, true);
10931 else if( IsBankPos ( dst ) )
10932 BankItem( sDest, pSrcItem, true);
10933 else if( IsEquipmentPos ( dst ) )
10935 EquipItem( eDest, pSrcItem, true);
10936 AutoUnequipOffhandIfNeed();
10939 else
10941 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
10942 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
10943 pSrcItem->SetState(ITEM_CHANGED, this);
10944 pDstItem->SetState(ITEM_CHANGED, this);
10945 if( IsInWorld() )
10947 pSrcItem->SendUpdateToPlayer( this );
10948 pDstItem->SendUpdateToPlayer( this );
10951 return;
10955 // impossible merge/fill, do real swap
10956 uint8 msg;
10958 // check src->dest move possibility
10959 ItemPosCountVec sDest;
10960 uint16 eDest = 0;
10961 if( IsInventoryPos( dst ) )
10962 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10963 else if( IsBankPos( dst ) )
10964 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10965 else if( IsEquipmentPos( dst ) )
10967 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10968 if( msg == EQUIP_ERR_OK )
10969 msg = CanUnequipItem( eDest, true );
10972 if( msg != EQUIP_ERR_OK )
10974 SendEquipError( msg, pSrcItem, pDstItem );
10975 return;
10978 // check dest->src move possibility
10979 ItemPosCountVec sDest2;
10980 uint16 eDest2 = 0;
10981 if( IsInventoryPos( src ) )
10982 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10983 else if( IsBankPos( src ) )
10984 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10985 else if( IsEquipmentPos( src ) )
10987 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10988 if( msg == EQUIP_ERR_OK )
10989 msg = CanUnequipItem( eDest2, true);
10992 if( msg != EQUIP_ERR_OK )
10994 SendEquipError( msg, pDstItem, pSrcItem );
10995 return;
10998 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
10999 if(pSrcItem->IsBag() && pDstItem->IsBag())
11001 Bag* emptyBag = NULL;
11002 Bag* fullBag = NULL;
11003 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11005 emptyBag = (Bag*)pSrcItem;
11006 fullBag = (Bag*)pDstItem;
11008 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11010 emptyBag = (Bag*)pDstItem;
11011 fullBag = (Bag*)pSrcItem;
11014 // bag swap (with items exchange) case
11015 if(emptyBag && fullBag)
11017 ItemPrototype const* emotyProto = emptyBag->GetProto();
11019 uint32 count = 0;
11021 for(int i=0; i < fullBag->GetBagSize(); ++i)
11023 Item *bagItem = fullBag->GetItemByPos(i);
11024 if (!bagItem)
11025 continue;
11027 ItemPrototype const* bagItemProto = bagItem->GetProto();
11028 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11030 // one from items not go to empty target bag
11031 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11032 return;
11035 ++count;
11039 if (count > emptyBag->GetBagSize())
11041 // too small targeted bag
11042 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11043 return;
11046 // Items swap
11047 count = 0; // will pos in new bag
11048 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11050 Item *bagItem = fullBag->GetItemByPos(i);
11051 if (!bagItem)
11052 continue;
11054 fullBag->RemoveItem(i, true);
11055 emptyBag->StoreItem(count, bagItem, true);
11056 bagItem->SetState(ITEM_CHANGED, this);
11058 ++count;
11063 // now do moves, remove...
11064 RemoveItem(dstbag, dstslot, false);
11065 RemoveItem(srcbag, srcslot, false);
11067 // add to dest
11068 if( IsInventoryPos( dst ) )
11069 StoreItem(sDest, pSrcItem, true);
11070 else if( IsBankPos( dst ) )
11071 BankItem(sDest, pSrcItem, true);
11072 else if( IsEquipmentPos( dst ) )
11073 EquipItem(eDest, pSrcItem, true);
11075 // add to src
11076 if( IsInventoryPos( src ) )
11077 StoreItem(sDest2, pDstItem, true);
11078 else if( IsBankPos( src ) )
11079 BankItem(sDest2, pDstItem, true);
11080 else if( IsEquipmentPos( src ) )
11081 EquipItem(eDest2, pDstItem, true);
11083 AutoUnequipOffhandIfNeed();
11086 void Player::AddItemToBuyBackSlot( Item *pItem )
11088 if( pItem )
11090 uint32 slot = m_currentBuybackSlot;
11091 // if current back slot non-empty search oldest or free
11092 if(m_items[slot])
11094 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11095 uint32 oldest_slot = BUYBACK_SLOT_START;
11097 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11099 // found empty
11100 if(!m_items[i])
11102 slot = i;
11103 break;
11106 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11108 if(oldest_time > i_time)
11110 oldest_time = i_time;
11111 oldest_slot = i;
11115 // find oldest
11116 slot = oldest_slot;
11119 RemoveItemFromBuyBackSlot( slot, true );
11120 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11122 m_items[slot] = pItem;
11123 time_t base = time(NULL);
11124 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11125 uint32 eslot = slot - BUYBACK_SLOT_START;
11127 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11128 ItemPrototype const *pProto = pItem->GetProto();
11129 if( pProto )
11130 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11131 else
11132 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11133 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11135 // move to next (for non filled list is move most optimized choice)
11136 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11137 ++m_currentBuybackSlot;
11141 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11143 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11144 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11145 return m_items[slot];
11146 return NULL;
11149 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11151 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11152 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11154 Item *pItem = m_items[slot];
11155 if( pItem )
11157 pItem->RemoveFromWorld();
11158 if(del) pItem->SetState(ITEM_REMOVED, this);
11161 m_items[slot] = NULL;
11163 uint32 eslot = slot - BUYBACK_SLOT_START;
11164 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11165 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11166 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11168 // if current backslot is filled set to now free slot
11169 if(m_items[m_currentBuybackSlot])
11170 m_currentBuybackSlot = slot;
11174 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11176 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11177 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11178 data << uint8(msg);
11180 if(msg)
11182 data << uint64(pItem ? pItem->GetGUID() : 0);
11183 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11184 data << uint8(0); // not 0 there...
11186 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11188 uint32 level = 0;
11190 if(pItem)
11191 if(ItemPrototype const* proto = pItem->GetProto())
11192 level = proto->RequiredLevel;
11194 data << uint32(level); // new 2.4.0
11197 GetSession()->SendPacket(&data);
11200 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11202 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11203 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11204 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11205 data << uint32(item);
11206 if( param > 0 )
11207 data << uint32(param);
11208 data << uint8(msg);
11209 GetSession()->SendPacket(&data);
11212 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11214 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11215 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11216 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11217 data << uint64(guid);
11218 if( param > 0 )
11219 data << uint32(param);
11220 data << uint8(msg);
11221 GetSession()->SendPacket(&data);
11224 void Player::ClearTrade()
11226 tradeGold = 0;
11227 acceptTrade = false;
11228 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11229 tradeItems[i] = NULL_SLOT;
11232 void Player::TradeCancel(bool sendback)
11234 if(pTrader)
11236 // send yellow "Trade canceled" message to both traders
11237 WorldSession* ws;
11238 ws = GetSession();
11239 if(sendback)
11240 ws->SendCancelTrade();
11241 ws = pTrader->GetSession();
11242 if(!ws->PlayerLogout())
11243 ws->SendCancelTrade();
11245 // cleanup
11246 ClearTrade();
11247 pTrader->ClearTrade();
11248 // prevent loss of reference
11249 pTrader->pTrader = NULL;
11250 pTrader = NULL;
11254 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11256 if(m_itemDuration.empty())
11257 return;
11259 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11261 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11263 Item* item = *itr;
11264 ++itr; // current element can be erased in UpdateDuration
11266 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11267 item->UpdateDuration(this,time);
11271 void Player::UpdateEnchantTime(uint32 time)
11273 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11275 assert(itr->item);
11276 next = itr;
11277 if(!itr->item->GetEnchantmentId(itr->slot))
11279 next = m_enchantDuration.erase(itr);
11281 else if(itr->leftduration <= time)
11283 ApplyEnchantment(itr->item, itr->slot, false, false);
11284 itr->item->ClearEnchantment(itr->slot);
11285 next = m_enchantDuration.erase(itr);
11287 else if(itr->leftduration > time)
11289 itr->leftduration -= time;
11290 ++next;
11295 void Player::AddEnchantmentDurations(Item *item)
11297 for(int x=0; x<MAX_ENCHANTMENT_SLOT; ++x)
11299 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11300 continue;
11302 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11303 if( duration > 0 )
11304 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11308 void Player::RemoveEnchantmentDurations(Item *item)
11310 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11312 if(itr->item == item)
11314 // save duration in item
11315 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11316 itr = m_enchantDuration.erase(itr);
11318 else
11319 ++itr;
11323 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11325 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11326 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11328 next = itr;
11329 if(itr->slot == slot)
11331 if(itr->item && itr->item->GetEnchantmentId(slot))
11333 // remove from stats
11334 ApplyEnchantment(itr->item, slot, false, false);
11335 // remove visual
11336 itr->item->ClearEnchantment(slot);
11338 // remove from update list
11339 next = m_enchantDuration.erase(itr);
11341 else
11342 ++next;
11345 // remove enchants from inventory items
11346 // NOTE: no need to remove these from stats, since these aren't equipped
11347 // in inventory
11348 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11350 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11351 if( pItem && pItem->GetEnchantmentId(slot) )
11352 pItem->ClearEnchantment(slot);
11355 // in inventory bags
11356 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11358 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11359 if( pBag )
11361 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11363 Item* pItem = pBag->GetItemByPos(j);
11364 if( pItem && pItem->GetEnchantmentId(slot) )
11365 pItem->ClearEnchantment(slot);
11371 // duration == 0 will remove item enchant
11372 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11374 if(!item)
11375 return;
11377 if(slot >= MAX_ENCHANTMENT_SLOT)
11378 return;
11380 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11382 if(itr->item == item && itr->slot == slot)
11384 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11385 m_enchantDuration.erase(itr);
11386 break;
11389 if(item && duration > 0 )
11391 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11392 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11396 void Player::ApplyEnchantment(Item *item,bool apply)
11398 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11399 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11402 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11404 if(!item)
11405 return;
11407 if(!item->IsEquipped())
11408 return;
11410 if(slot >= MAX_ENCHANTMENT_SLOT)
11411 return;
11413 uint32 enchant_id = item->GetEnchantmentId(slot);
11414 if(!enchant_id)
11415 return;
11417 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11418 if(!pEnchant)
11419 return;
11421 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11422 return;
11424 if (!item->IsBroken())
11426 for (int s = 0; s < 3; ++s)
11428 uint32 enchant_display_type = pEnchant->type[s];
11429 uint32 enchant_amount = pEnchant->amount[s];
11430 uint32 enchant_spell_id = pEnchant->spellid[s];
11432 switch(enchant_display_type)
11434 case ITEM_ENCHANTMENT_TYPE_NONE:
11435 break;
11436 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11437 // processed in Player::CastItemCombatSpell
11438 break;
11439 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11440 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11441 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11442 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11443 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11444 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11445 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11446 break;
11447 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11448 if(enchant_spell_id)
11450 if(apply)
11452 int32 basepoints = 0;
11453 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11454 if (item->GetItemRandomPropertyId())
11456 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11457 if (item_rand)
11459 // Search enchant_amount
11460 for (int k = 0; k < 3; ++k)
11462 if(item_rand->enchant_id[k] == enchant_id)
11464 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11465 break;
11470 // Cast custom spell vs all equal basepoints getted from enchant_amount
11471 if (basepoints)
11472 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11473 else
11474 CastSpell(this, enchant_spell_id, true, item);
11476 else
11477 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11479 break;
11480 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11481 if (!enchant_amount)
11483 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11484 if(item_rand)
11486 for (int k = 0; k < 3; ++k)
11488 if(item_rand->enchant_id[k] == enchant_id)
11490 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11491 break;
11497 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11498 break;
11499 case ITEM_ENCHANTMENT_TYPE_STAT:
11501 if (!enchant_amount)
11503 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11504 if(item_rand_suffix)
11506 for (int k = 0; k < 3; ++k)
11508 if(item_rand_suffix->enchant_id[k] == enchant_id)
11510 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11511 break;
11517 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11518 switch (enchant_spell_id)
11520 case ITEM_MOD_AGILITY:
11521 sLog.outDebug("+ %u AGILITY",enchant_amount);
11522 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11523 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11524 break;
11525 case ITEM_MOD_STRENGTH:
11526 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11527 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11528 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11529 break;
11530 case ITEM_MOD_INTELLECT:
11531 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11532 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11533 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11534 break;
11535 case ITEM_MOD_SPIRIT:
11536 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11537 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11538 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11539 break;
11540 case ITEM_MOD_STAMINA:
11541 sLog.outDebug("+ %u STAMINA",enchant_amount);
11542 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11543 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11544 break;
11545 case ITEM_MOD_DEFENSE_SKILL_RATING:
11546 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11547 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11548 break;
11549 case ITEM_MOD_DODGE_RATING:
11550 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11551 sLog.outDebug("+ %u DODGE", enchant_amount);
11552 break;
11553 case ITEM_MOD_PARRY_RATING:
11554 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11555 sLog.outDebug("+ %u PARRY", enchant_amount);
11556 break;
11557 case ITEM_MOD_BLOCK_RATING:
11558 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11559 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11560 break;
11561 case ITEM_MOD_HIT_MELEE_RATING:
11562 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11563 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11564 break;
11565 case ITEM_MOD_HIT_RANGED_RATING:
11566 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11567 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11568 break;
11569 case ITEM_MOD_HIT_SPELL_RATING:
11570 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11571 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11572 break;
11573 case ITEM_MOD_CRIT_MELEE_RATING:
11574 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11575 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11576 break;
11577 case ITEM_MOD_CRIT_RANGED_RATING:
11578 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11579 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11580 break;
11581 case ITEM_MOD_CRIT_SPELL_RATING:
11582 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11583 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11584 break;
11585 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11586 // in Enchantments
11587 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11588 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11589 // break;
11590 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11591 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11592 // break;
11593 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11594 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11595 // break;
11596 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11597 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11598 // break;
11599 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11600 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11601 // break;
11602 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11603 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11604 // break;
11605 // case ITEM_MOD_HASTE_MELEE_RATING:
11606 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11607 // break;
11608 // case ITEM_MOD_HASTE_RANGED_RATING:
11609 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11610 // break;
11611 case ITEM_MOD_HASTE_SPELL_RATING:
11612 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11613 break;
11614 case ITEM_MOD_HIT_RATING:
11615 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11616 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11617 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11618 sLog.outDebug("+ %u HIT", enchant_amount);
11619 break;
11620 case ITEM_MOD_CRIT_RATING:
11621 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11622 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11623 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11624 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11625 break;
11626 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11627 // case ITEM_MOD_HIT_TAKEN_RATING:
11628 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11629 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11630 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11631 // break;
11632 // case ITEM_MOD_CRIT_TAKEN_RATING:
11633 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11634 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11635 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11636 // break;
11637 case ITEM_MOD_RESILIENCE_RATING:
11638 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11639 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11640 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11641 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11642 break;
11643 case ITEM_MOD_HASTE_RATING:
11644 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11645 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11646 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11647 sLog.outDebug("+ %u HASTE", enchant_amount);
11648 break;
11649 case ITEM_MOD_EXPERTISE_RATING:
11650 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11651 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11652 break;
11653 case ITEM_MOD_ATTACK_POWER:
11654 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11655 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11656 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11657 break;
11658 case ITEM_MOD_RANGED_ATTACK_POWER:
11659 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11660 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11661 break;
11662 case ITEM_MOD_FERAL_ATTACK_POWER:
11663 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11664 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11665 break;
11666 case ITEM_MOD_SPELL_HEALING_DONE:
11667 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11668 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11669 break;
11670 case ITEM_MOD_SPELL_DAMAGE_DONE:
11671 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11672 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11673 break;
11674 case ITEM_MOD_MANA_REGENERATION:
11675 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11676 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11677 break;
11678 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11679 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11680 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11681 break;
11682 case ITEM_MOD_SPELL_POWER:
11683 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11684 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11685 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11686 break;
11687 default:
11688 break;
11690 break;
11692 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11694 if(getClass() == CLASS_SHAMAN)
11696 float addValue = 0.0f;
11697 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11699 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11700 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11702 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11704 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11705 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11708 break;
11710 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11711 // processed in Player::CastItemUseSpell
11712 break;
11713 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11714 // nothing do..
11715 break;
11716 default:
11717 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11718 break;
11719 } /*switch(enchant_display_type)*/
11720 } /*for*/
11723 // visualize enchantment at player and equipped items
11724 if(slot == PERM_ENCHANTMENT_SLOT)
11725 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
11727 if(slot == TEMP_ENCHANTMENT_SLOT)
11728 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
11731 if(apply_dur)
11733 if(apply)
11735 // set duration
11736 uint32 duration = item->GetEnchantmentDuration(slot);
11737 if(duration > 0)
11738 AddEnchantmentDuration(item, slot, duration);
11740 else
11742 // duration == 0 will remove EnchantDuration
11743 AddEnchantmentDuration(item, slot, 0);
11748 void Player::SendEnchantmentDurations()
11750 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11752 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11756 void Player::SendItemDurations()
11758 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11760 (*itr)->SendTimeUpdate(this);
11764 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11766 if(!item) // prevent crash
11767 return;
11769 // last check 2.0.10
11770 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11771 data << uint64(GetGUID()); // player GUID
11772 data << uint32(received); // 0=looted, 1=from npc
11773 data << uint32(created); // 0=received, 1=created
11774 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11775 data << uint8(item->GetBagSlot()); // bagslot
11776 // item slot, but when added to stack: 0xFFFFFFFF
11777 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11778 data << uint32(item->GetEntry()); // item id
11779 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11780 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11781 data << uint32(count); // count of items
11782 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11784 if (broadcast && GetGroup())
11785 GetGroup()->BroadcastPacket(&data, true);
11786 else
11787 GetSession()->SendPacket(&data);
11790 /*********************************************************/
11791 /*** QUEST SYSTEM ***/
11792 /*********************************************************/
11794 void Player::PrepareQuestMenu( uint64 guid )
11796 Object *pObject;
11797 QuestRelations* pObjectQR;
11798 QuestRelations* pObjectQIR;
11800 // pets also can have quests
11801 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11802 if( pCreature )
11804 pObject = (Object*)pCreature;
11805 pObjectQR = &objmgr.mCreatureQuestRelations;
11806 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11808 else
11810 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11811 if( pGameObject )
11813 pObject = (Object*)pGameObject;
11814 pObjectQR = &objmgr.mGOQuestRelations;
11815 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11817 else
11818 return;
11821 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11822 qm.ClearMenu();
11824 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11826 uint32 quest_id = i->second;
11827 QuestStatus status = GetQuestStatus( quest_id );
11828 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11829 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11830 else if ( status == QUEST_STATUS_INCOMPLETE )
11831 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11832 else if (status == QUEST_STATUS_AVAILABLE )
11833 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11836 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11838 uint32 quest_id = i->second;
11839 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11840 if(!pQuest) continue;
11842 QuestStatus status = GetQuestStatus( quest_id );
11844 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11845 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
11846 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11847 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11851 void Player::SendPreparedQuest( uint64 guid )
11853 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11854 if( questMenu.Empty() )
11855 return;
11857 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11859 uint32 status = qmi0.m_qIcon;
11861 // single element case
11862 if ( questMenu.MenuItemCount() == 1 )
11864 // Auto open -- maybe also should verify there is no greeting
11865 uint32 quest_id = qmi0.m_qId;
11866 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11868 if ( pQuest )
11870 if( status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus( quest_id ) )
11871 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11872 else if( status == DIALOG_STATUS_UNK2 )
11873 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11874 // Send completable on repeatable quest if player don't have quest
11875 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11876 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11877 else
11878 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11881 // multiply entries
11882 else
11884 QEmote qe;
11885 qe._Delay = 0;
11886 qe._Emote = 0;
11887 std::string title = "";
11889 // need pet case for some quests
11890 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11891 if( pCreature )
11893 uint32 textid = pCreature->GetNpcTextId();
11894 GossipText const* gossiptext = objmgr.GetGossipText(textid);
11895 if( !gossiptext )
11897 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11898 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11899 title = "";
11901 else
11903 qe = gossiptext->Options[0].Emotes[0];
11905 if(!gossiptext->Options[0].Text_0.empty())
11907 title = gossiptext->Options[0].Text_0;
11909 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11910 if (loc_idx >= 0)
11912 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11913 if (nl)
11915 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11916 title = nl->Text_0[0][loc_idx];
11920 else
11922 title = gossiptext->Options[0].Text_1;
11924 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11925 if (loc_idx >= 0)
11927 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11928 if (nl)
11930 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11931 title = nl->Text_1[0][loc_idx];
11937 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11941 bool Player::IsActiveQuest( uint32 quest_id ) const
11943 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11945 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11948 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11950 Object *pObject;
11951 QuestRelations* pObjectQR;
11952 QuestRelations* pObjectQIR;
11954 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
11955 if( pCreature )
11957 pObject = (Object*)pCreature;
11958 pObjectQR = &objmgr.mCreatureQuestRelations;
11959 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11961 else
11963 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11964 if( pGameObject )
11966 pObject = (Object*)pGameObject;
11967 pObjectQR = &objmgr.mGOQuestRelations;
11968 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11970 else
11971 return NULL;
11974 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11975 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11977 if (itr->second == nextQuestID)
11978 return objmgr.GetQuestTemplate(nextQuestID);
11981 return NULL;
11984 bool Player::CanSeeStartQuest( Quest const *pQuest )
11986 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11987 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11988 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11989 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11991 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11994 return false;
11997 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11999 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12000 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12001 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12002 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12003 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12004 && SatisfyQuestDay( pQuest, msg );
12007 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12009 if( !SatisfyQuestLog( msg ) )
12010 return false;
12012 uint32 srcitem = pQuest->GetSrcItemId();
12013 if( srcitem > 0 )
12015 uint32 count = pQuest->GetSrcItemCount();
12016 ItemPosCountVec dest;
12017 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12019 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12020 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12021 return true;
12022 else if( msg2 != EQUIP_ERR_OK )
12024 SendEquipError( msg2, NULL, NULL );
12025 return false;
12028 return true;
12031 bool Player::CanCompleteQuest( uint32 quest_id )
12033 if( quest_id )
12035 QuestStatusData& q_status = mQuestStatus[quest_id];
12036 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12037 return false; // not allow re-complete quest
12039 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12041 if(!qInfo)
12042 return false;
12044 // auto complete quest
12045 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12046 return true;
12048 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12051 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12053 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12055 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12056 return false;
12060 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12062 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12064 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12065 continue;
12067 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12068 return false;
12072 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12073 return false;
12075 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12076 return false;
12078 if ( qInfo->GetRewOrReqMoney() < 0 )
12080 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12081 return false;
12084 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12085 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12086 return false;
12088 return true;
12091 return false;
12094 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12096 // Solve problem that player don't have the quest and try complete it.
12097 // if repeatable she must be able to complete event if player don't have it.
12098 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12099 if( !CanTakeQuest(pQuest, false) )
12100 return false;
12102 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12103 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12104 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12105 return false;
12107 if( !CanRewardQuest(pQuest, false) )
12108 return false;
12110 return true;
12113 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12115 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12116 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12117 return false;
12119 // daily quest can't be rewarded (25 daily quest already completed)
12120 if(!SatisfyQuestDay(pQuest,true))
12121 return false;
12123 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12124 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12125 return false;
12127 // prevent receive reward with quest items in bank
12128 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12130 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12132 if( pQuest->ReqItemCount[i]!= 0 &&
12133 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12135 if(msg)
12136 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12137 return false;
12142 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12143 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12144 return false;
12146 return true;
12149 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12151 // prevent receive reward with quest items in bank or for not completed quest
12152 if(!CanRewardQuest(pQuest,msg))
12153 return false;
12155 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12157 if( pQuest->RewChoiceItemId[reward] )
12159 ItemPosCountVec dest;
12160 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12161 if( res != EQUIP_ERR_OK )
12163 SendEquipError( res, NULL, NULL );
12164 return false;
12169 if ( pQuest->GetRewItemsCount() > 0 )
12171 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12173 if( pQuest->RewItemId[i] )
12175 ItemPosCountVec dest;
12176 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12177 if( res != EQUIP_ERR_OK )
12179 SendEquipError( res, NULL, NULL );
12180 return false;
12186 return true;
12189 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12191 uint16 log_slot = FindQuestSlot( 0 );
12192 assert(log_slot < MAX_QUEST_LOG_SIZE);
12194 uint32 quest_id = pQuest->GetQuestId();
12196 // if not exist then created with set uState==NEW and rewarded=false
12197 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12199 // check for repeatable quests status reset
12200 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12201 questStatusData.m_explored = false;
12203 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12205 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12206 questStatusData.m_itemcount[i] = 0;
12209 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12211 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12212 questStatusData.m_creatureOrGOcount[i] = 0;
12215 GiveQuestSourceItem( pQuest );
12216 AdjustQuestReqItemCount( pQuest, questStatusData );
12218 if( pQuest->GetRepObjectiveFaction() )
12219 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12220 GetReputationMgr().SetVisible(factionEntry);
12222 uint32 qtime = 0;
12223 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12225 uint32 limittime = pQuest->GetLimitTime();
12227 // shared timed quest
12228 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12229 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12231 AddTimedQuest( quest_id );
12232 questStatusData.m_timer = limittime * IN_MILISECONDS;
12233 qtime = static_cast<uint32>(time(NULL)) + limittime;
12235 else
12236 questStatusData.m_timer = 0;
12238 SetQuestSlot(log_slot, quest_id, qtime);
12240 if (questStatusData.uState != QUEST_NEW)
12241 questStatusData.uState = QUEST_CHANGED;
12243 //starting initial quest script
12244 if(questGiver && pQuest->GetQuestStartScript()!=0)
12245 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12247 // Some spells applied at quest activation
12248 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12249 if(saBounds.first != saBounds.second)
12251 uint32 zone, area;
12252 GetZoneAndAreaId(zone,area);
12254 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12255 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12256 if( !HasAura(itr->second->spellId,0) )
12257 CastSpell(this,itr->second->spellId,true);
12260 UpdateForQuestWorldObjects();
12263 void Player::CompleteQuest( uint32 quest_id )
12265 if( quest_id )
12267 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12269 uint16 log_slot = FindQuestSlot( quest_id );
12270 if( log_slot < MAX_QUEST_LOG_SIZE)
12271 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12273 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12275 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12276 RewardQuest(qInfo,0,this,false);
12277 else
12278 SendQuestComplete( quest_id );
12283 void Player::IncompleteQuest( uint32 quest_id )
12285 if( quest_id )
12287 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12289 uint16 log_slot = FindQuestSlot( quest_id );
12290 if( log_slot < MAX_QUEST_LOG_SIZE)
12291 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12295 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12297 uint32 quest_id = pQuest->GetQuestId();
12299 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12301 if ( pQuest->ReqItemId[i] )
12302 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12305 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12306 // SetTimedQuest( 0 );
12307 m_timedquests.erase(pQuest->GetQuestId());
12309 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12311 if( pQuest->RewChoiceItemId[reward] )
12313 ItemPosCountVec dest;
12314 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12316 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12317 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12322 if ( pQuest->GetRewItemsCount() > 0 )
12324 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12326 if( pQuest->RewItemId[i] )
12328 ItemPosCountVec dest;
12329 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12331 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12332 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12338 RewardReputation( pQuest );
12340 if( pQuest->GetRewSpellCast() > 0 )
12341 CastSpell( this, pQuest->GetRewSpellCast(), true);
12342 else if( pQuest->GetRewSpell() > 0)
12343 CastSpell( this, pQuest->GetRewSpell(), true);
12345 uint16 log_slot = FindQuestSlot( quest_id );
12346 if( log_slot < MAX_QUEST_LOG_SIZE)
12347 SetQuestSlot(log_slot,0);
12349 QuestStatusData& q_status = mQuestStatus[quest_id];
12351 // Not give XP in case already completed once repeatable quest
12352 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12354 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12355 GiveXP( XP , NULL );
12356 else
12358 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12359 ModifyMoney( money );
12360 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12363 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12364 if(pQuest->GetRewOrReqMoney())
12366 ModifyMoney( pQuest->GetRewOrReqMoney() );
12368 if(pQuest->GetRewOrReqMoney() > 0)
12369 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12372 // honor reward
12373 if(pQuest->GetRewHonorableKills())
12374 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12376 // title reward
12377 if(pQuest->GetCharTitleId())
12379 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12380 SetTitle(titleEntry);
12383 if(pQuest->GetBonusTalents())
12385 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12386 InitTalentForLevel();
12389 // Send reward mail
12390 if(pQuest->GetRewMailTemplateId())
12392 MailMessageType mailType;
12393 uint32 senderGuidOrEntry;
12394 switch(questGiver->GetTypeId())
12396 case TYPEID_UNIT:
12397 mailType = MAIL_CREATURE;
12398 senderGuidOrEntry = questGiver->GetEntry();
12399 break;
12400 case TYPEID_GAMEOBJECT:
12401 mailType = MAIL_GAMEOBJECT;
12402 senderGuidOrEntry = questGiver->GetEntry();
12403 break;
12404 case TYPEID_ITEM:
12405 mailType = MAIL_ITEM;
12406 senderGuidOrEntry = questGiver->GetEntry();
12407 break;
12408 case TYPEID_PLAYER:
12409 mailType = MAIL_NORMAL;
12410 senderGuidOrEntry = questGiver->GetGUIDLow();
12411 break;
12412 default:
12413 mailType = MAIL_NORMAL;
12414 senderGuidOrEntry = GetGUIDLow();
12415 break;
12418 Loot questMailLoot;
12420 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12422 // fill mail
12423 MailItemsInfo mi; // item list preparing
12425 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12426 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12428 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12430 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12432 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12433 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12438 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12441 if(pQuest->IsDaily())
12443 SetDailyQuestStatus(quest_id);
12444 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12447 if ( !pQuest->IsRepeatable() )
12448 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12449 else
12450 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12452 q_status.m_rewarded = true;
12454 if(announce)
12455 SendQuestReward( pQuest, XP, questGiver );
12457 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12458 if (pQuest->GetZoneOrSort() > 0)
12459 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12460 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12461 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12463 uint32 zone = 0;
12464 uint32 area = 0;
12466 // remove auras from spells with quest reward state limitations
12467 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12468 if(saEndBounds.first != saEndBounds.second)
12470 GetZoneAndAreaId(zone,area);
12472 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12473 if(!itr->second->IsFitToRequirements(this,zone,area))
12474 RemoveAurasDueToSpell(itr->second->spellId);
12477 // Some spells applied at quest reward
12478 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12479 if(saBounds.first != saBounds.second)
12481 if(!zone || !area)
12482 GetZoneAndAreaId(zone,area);
12484 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12485 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12486 if( !HasAura(itr->second->spellId,0) )
12487 CastSpell(this,itr->second->spellId,true);
12491 void Player::FailQuest( uint32 quest_id )
12493 if( quest_id )
12495 IncompleteQuest( quest_id );
12497 uint16 log_slot = FindQuestSlot( quest_id );
12498 if( log_slot < MAX_QUEST_LOG_SIZE)
12500 SetQuestSlotTimer(log_slot, 1 );
12501 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12503 SendQuestFailed( quest_id );
12507 void Player::FailTimedQuest( uint32 quest_id )
12509 if( quest_id )
12511 QuestStatusData& q_status = mQuestStatus[quest_id];
12513 q_status.m_timer = 0;
12514 if (q_status.uState != QUEST_NEW)
12515 q_status.uState = QUEST_CHANGED;
12517 IncompleteQuest( quest_id );
12519 uint16 log_slot = FindQuestSlot( quest_id );
12520 if( log_slot < MAX_QUEST_LOG_SIZE)
12522 SetQuestSlotTimer(log_slot, 1 );
12523 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12525 SendQuestTimerFailed( quest_id );
12529 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12531 int32 zoneOrSort = qInfo->GetZoneOrSort();
12532 int32 skillOrClass = qInfo->GetSkillOrClass();
12534 // skip zone zoneOrSort and 0 case skillOrClass
12535 if( zoneOrSort >= 0 && skillOrClass == 0 )
12536 return true;
12538 int32 questSort = -zoneOrSort;
12539 uint8 reqSortClass = ClassByQuestSort(questSort);
12541 // check class sort cases in zoneOrSort
12542 if( reqSortClass != 0 && getClass() != reqSortClass)
12544 if( msg )
12545 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12546 return false;
12549 // check class
12550 if( skillOrClass < 0 )
12552 uint8 reqClass = -int32(skillOrClass);
12553 if(getClass() != reqClass)
12555 if( msg )
12556 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12557 return false;
12560 // check skill
12561 else if( skillOrClass > 0 )
12563 uint32 reqSkill = skillOrClass;
12564 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12566 if( msg )
12567 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12568 return false;
12572 return true;
12575 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12577 if( getLevel() < qInfo->GetMinLevel() )
12579 if( msg )
12580 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12581 return false;
12583 return true;
12586 bool Player::SatisfyQuestLog( bool msg )
12588 // exist free slot
12589 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12590 return true;
12592 if( msg )
12594 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12595 GetSession()->SendPacket( &data );
12596 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12598 return false;
12601 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12603 // No previous quest (might be first quest in a series)
12604 if( qInfo->prevQuests.empty())
12605 return true;
12607 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12609 uint32 prevId = abs(*iter);
12611 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12612 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12614 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12616 // If any of the positive previous quests completed, return true
12617 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12619 // skip one-from-all exclusive group
12620 if(qPrevInfo->GetExclusiveGroup() >= 0)
12621 return true;
12623 // each-from-all exclusive group ( < 0)
12624 // can be start if only all quests in prev quest exclusive group completed and rewarded
12625 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12626 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12628 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12630 for(; iter2 != end; ++iter2)
12632 uint32 exclude_Id = iter2->second;
12634 // skip checked quest id, only state of other quests in group is interesting
12635 if(exclude_Id == prevId)
12636 continue;
12638 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12640 // alternative quest from group also must be completed and rewarded(reported)
12641 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12643 if( msg )
12644 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12645 return false;
12648 return true;
12650 // If any of the negative previous quests active, return true
12651 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12652 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12654 // skip one-from-all exclusive group
12655 if(qPrevInfo->GetExclusiveGroup() >= 0)
12656 return true;
12658 // each-from-all exclusive group ( < 0)
12659 // can be start if only all quests in prev quest exclusive group active
12660 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12661 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12663 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12665 for(; iter2 != end; ++iter2)
12667 uint32 exclude_Id = iter2->second;
12669 // skip checked quest id, only state of other quests in group is interesting
12670 if(exclude_Id == prevId)
12671 continue;
12673 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12675 // alternative quest from group also must be active
12676 if( i_exstatus == mQuestStatus.end() ||
12677 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12678 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12680 if( msg )
12681 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12682 return false;
12685 return true;
12690 // Has only positive prev. quests in non-rewarded state
12691 // and negative prev. quests in non-active state
12692 if( msg )
12693 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12695 return false;
12698 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12700 uint32 reqraces = qInfo->GetRequiredRaces();
12701 if ( reqraces == 0 )
12702 return true;
12703 if( (reqraces & getRaceMask()) == 0 )
12705 if( msg )
12706 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12707 return false;
12709 return true;
12712 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12714 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12715 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12717 if( msg )
12718 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12719 return false;
12722 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12723 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12725 if( msg )
12726 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12727 return false;
12730 return true;
12733 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12735 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12736 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12738 if( msg )
12739 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12740 return false;
12742 return true;
12745 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12747 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12749 if( msg )
12750 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12751 return false;
12753 return true;
12756 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12758 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12759 if(qInfo->GetExclusiveGroup() <= 0)
12760 return true;
12762 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12763 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12765 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12767 for(; iter != end; ++iter)
12769 uint32 exclude_Id = iter->second;
12771 // skip checked quest id, only state of other quests in group is interesting
12772 if(exclude_Id == qInfo->GetQuestId())
12773 continue;
12775 // not allow have daily quest if daily quest from exclusive group already recently completed
12776 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12777 if( !SatisfyQuestDay(Nquest, false) )
12779 if( msg )
12780 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12781 return false;
12784 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12786 // alternative quest already started or completed
12787 if( i_exstatus != mQuestStatus.end()
12788 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12790 if( msg )
12791 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12792 return false;
12795 return true;
12798 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12800 if(!qInfo->GetNextQuestInChain())
12801 return true;
12803 // next quest in chain already started or completed
12804 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12805 if( itr != mQuestStatus.end()
12806 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12808 if( msg )
12809 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12810 return false;
12813 // check for all quests further up the chain
12814 // only necessary if there are quest chains with more than one quest that can be skipped
12815 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12816 return true;
12819 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12821 // No previous quest in chain
12822 if( qInfo->prevChainQuests.empty())
12823 return true;
12825 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12827 uint32 prevId = *iter;
12829 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12831 if( i_prevstatus != mQuestStatus.end() )
12833 // If any of the previous quests in chain active, return false
12834 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12835 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12837 if( msg )
12838 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12839 return false;
12843 // check for all quests further down the chain
12844 // only necessary if there are quest chains with more than one quest that can be skipped
12845 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12846 // return false;
12849 // No previous quest in chain active
12850 return true;
12853 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12855 if(!qInfo->IsDaily())
12856 return true;
12858 bool have_slot = false;
12859 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12861 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12862 if(qInfo->GetQuestId()==id)
12863 return false;
12865 if(!id)
12866 have_slot = true;
12869 if(!have_slot)
12871 if( msg )
12872 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12873 return false;
12876 return true;
12879 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12881 uint32 srcitem = pQuest->GetSrcItemId();
12882 if( srcitem > 0 )
12884 uint32 count = pQuest->GetSrcItemCount();
12885 if( count <= 0 )
12886 count = 1;
12888 ItemPosCountVec dest;
12889 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12890 if( msg == EQUIP_ERR_OK )
12892 Item * item = StoreNewItem(dest, srcitem, true);
12893 SendNewItem(item, count, true, false);
12894 return true;
12896 // player already have max amount required item, just report success
12897 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12898 return true;
12899 else
12900 SendEquipError( msg, NULL, NULL );
12901 return false;
12904 return true;
12907 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12909 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12910 if( qInfo )
12912 uint32 srcitem = qInfo->GetSrcItemId();
12913 if( srcitem > 0 )
12915 uint32 count = qInfo->GetSrcItemCount();
12916 if( count <= 0 )
12917 count = 1;
12919 // exist one case when destroy source quest item not possible:
12920 // non un-equippable item (equipped non-empty bag, for example)
12921 uint8 res = CanUnequipItems(srcitem,count);
12922 if(res != EQUIP_ERR_OK)
12924 if(msg)
12925 SendEquipError( res, NULL, NULL );
12926 return false;
12929 DestroyItemCount(srcitem, count, true, true);
12932 return true;
12935 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12937 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12938 if( qInfo )
12940 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12941 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12942 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12943 && !qInfo->IsRepeatable() )
12944 return itr->second.m_rewarded;
12946 return false;
12948 return false;
12951 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12953 if( quest_id )
12955 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12956 if( itr != mQuestStatus.end() )
12957 return itr->second.m_status;
12959 return QUEST_STATUS_NONE;
12962 bool Player::CanShareQuest(uint32 quest_id) const
12964 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12965 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12967 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12968 if( itr != mQuestStatus.end() )
12969 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12971 return false;
12974 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12976 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12977 if( qInfo )
12979 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12981 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12982 m_timedquests.erase(qInfo->GetQuestId());
12985 QuestStatusData& q_status = mQuestStatus[quest_id];
12987 q_status.m_status = status;
12988 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12991 UpdateForQuestWorldObjects();
12994 // not used in MaNGOS, but used in scripting code
12995 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12997 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12998 if( !qInfo )
12999 return 0;
13001 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13002 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13003 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13005 return 0;
13008 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13010 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13012 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13014 uint32 reqitemcount = pQuest->ReqItemCount[i];
13015 if( reqitemcount != 0 )
13017 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13019 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13020 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13026 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13028 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13029 if ( GetQuestSlotQuestId(i) == quest_id )
13030 return i;
13032 return MAX_QUEST_LOG_SIZE;
13035 void Player::AreaExploredOrEventHappens( uint32 questId )
13037 if( questId )
13039 uint16 log_slot = FindQuestSlot( questId );
13040 if( log_slot < MAX_QUEST_LOG_SIZE)
13042 QuestStatusData& q_status = mQuestStatus[questId];
13044 if(!q_status.m_explored)
13046 q_status.m_explored = true;
13047 if (q_status.uState != QUEST_NEW)
13048 q_status.uState = QUEST_CHANGED;
13051 if( CanCompleteQuest( questId ) )
13052 CompleteQuest( questId );
13056 //not used in mangosd, function for external script library
13057 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13059 if( Group *pGroup = GetGroup() )
13061 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13063 Player *pGroupGuy = itr->getSource();
13065 // for any leave or dead (with not released body) group member at appropriate distance
13066 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13067 pGroupGuy->AreaExploredOrEventHappens(questId);
13070 else
13071 AreaExploredOrEventHappens(questId);
13074 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13076 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13078 uint32 questid = GetQuestSlotQuestId(i);
13079 if ( questid == 0 )
13080 continue;
13082 QuestStatusData& q_status = mQuestStatus[questid];
13084 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13085 continue;
13087 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13088 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13089 continue;
13091 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13093 uint32 reqitem = qInfo->ReqItemId[j];
13094 if ( reqitem == entry )
13096 uint32 reqitemcount = qInfo->ReqItemCount[j];
13097 uint32 curitemcount = q_status.m_itemcount[j];
13098 if ( curitemcount < reqitemcount )
13100 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13101 q_status.m_itemcount[j] += additemcount;
13102 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13104 SendQuestUpdateAddItem( qInfo, j, additemcount );
13106 if ( CanCompleteQuest( questid ) )
13107 CompleteQuest( questid );
13108 return;
13112 UpdateForQuestWorldObjects();
13115 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13117 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13119 uint32 questid = GetQuestSlotQuestId(i);
13120 if(!questid)
13121 continue;
13122 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13123 if ( !qInfo )
13124 continue;
13125 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13126 continue;
13128 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13130 uint32 reqitem = qInfo->ReqItemId[j];
13131 if ( reqitem == entry )
13133 QuestStatusData& q_status = mQuestStatus[questid];
13135 uint32 reqitemcount = qInfo->ReqItemCount[j];
13136 uint32 curitemcount;
13137 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13138 curitemcount = q_status.m_itemcount[j];
13139 else
13140 curitemcount = GetItemCount(entry,true);
13141 if ( curitemcount < reqitemcount + count )
13143 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13144 q_status.m_itemcount[j] = curitemcount - remitemcount;
13145 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13147 IncompleteQuest( questid );
13149 return;
13153 UpdateForQuestWorldObjects();
13156 void Player::KilledMonster( uint32 entry, uint64 guid )
13158 uint32 addkillcount = 1;
13159 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13160 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13162 uint32 questid = GetQuestSlotQuestId(i);
13163 if(!questid)
13164 continue;
13166 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13167 if( !qInfo )
13168 continue;
13169 // just if !ingroup || !noraidgroup || raidgroup
13170 QuestStatusData& q_status = mQuestStatus[questid];
13171 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13173 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13175 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13177 // skip GO activate objective or none
13178 if(qInfo->ReqCreatureOrGOId[j] <=0)
13179 continue;
13181 // skip Cast at creature objective
13182 if(qInfo->ReqSpell[j] !=0 )
13183 continue;
13185 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13187 if ( reqkill == entry )
13189 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13190 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13191 if ( curkillcount < reqkillcount )
13193 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13194 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13196 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13198 if ( CanCompleteQuest( questid ) )
13199 CompleteQuest( questid );
13201 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13202 continue;
13210 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13212 bool isCreature = IS_CREATURE_GUID(guid);
13214 uint32 addCastCount = 1;
13215 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13217 uint32 questid = GetQuestSlotQuestId(i);
13218 if(!questid)
13219 continue;
13221 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13222 if ( !qInfo )
13223 continue;
13225 QuestStatusData& q_status = mQuestStatus[questid];
13227 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13229 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13231 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13233 // skip kill creature objective (0) or wrong spell casts
13234 if(qInfo->ReqSpell[j] != spell_id )
13235 continue;
13237 uint32 reqTarget = 0;
13239 if(isCreature)
13241 // creature activate objectives
13242 if(qInfo->ReqCreatureOrGOId[j] > 0)
13243 // checked at quest_template loading
13244 reqTarget = qInfo->ReqCreatureOrGOId[j];
13246 else
13248 // GO activate objective
13249 if(qInfo->ReqCreatureOrGOId[j] < 0)
13250 // checked at quest_template loading
13251 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13254 // other not this creature/GO related objectives
13255 if( reqTarget != entry )
13256 continue;
13258 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13259 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13260 if ( curCastCount < reqCastCount )
13262 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13263 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13265 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13268 if ( CanCompleteQuest( questid ) )
13269 CompleteQuest( questid );
13271 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13272 break;
13279 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13281 uint32 addTalkCount = 1;
13282 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13284 uint32 questid = GetQuestSlotQuestId(i);
13285 if(!questid)
13286 continue;
13288 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13289 if ( !qInfo )
13290 continue;
13292 QuestStatusData& q_status = mQuestStatus[questid];
13294 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13296 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13298 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13300 // skip spell casts and Gameobject objectives
13301 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13302 continue;
13304 uint32 reqTarget = 0;
13306 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13307 // checked at quest_template loading
13308 reqTarget = qInfo->ReqCreatureOrGOId[j];
13309 else
13310 continue;
13312 if ( reqTarget == entry )
13314 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13315 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13316 if ( curTalkCount < reqTalkCount )
13318 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13319 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13321 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13323 if ( CanCompleteQuest( questid ) )
13324 CompleteQuest( questid );
13326 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13327 continue;
13335 void Player::MoneyChanged( uint32 count )
13337 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13339 uint32 questid = GetQuestSlotQuestId(i);
13340 if (!questid)
13341 continue;
13343 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13344 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13346 QuestStatusData& q_status = mQuestStatus[questid];
13348 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13350 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13352 if ( CanCompleteQuest( questid ) )
13353 CompleteQuest( questid );
13356 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13358 if(int32(count) < -qInfo->GetRewOrReqMoney())
13359 IncompleteQuest( questid );
13365 void Player::ReputationChanged(FactionEntry const* factionEntry )
13367 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13369 if(uint32 questid = GetQuestSlotQuestId(i))
13371 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13373 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13375 QuestStatusData& q_status = mQuestStatus[questid];
13376 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13378 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13379 if ( CanCompleteQuest( questid ) )
13380 CompleteQuest( questid );
13382 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13384 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13385 IncompleteQuest( questid );
13393 bool Player::HasQuestForItem( uint32 itemid ) const
13395 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13397 uint32 questid = GetQuestSlotQuestId(i);
13398 if ( questid == 0 )
13399 continue;
13401 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13402 if(qs_itr == mQuestStatus.end())
13403 continue;
13405 QuestStatusData const& q_status = qs_itr->second;
13407 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13409 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13410 if(!qinfo)
13411 continue;
13413 // hide quest if player is in raid-group and quest is no raid quest
13414 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13415 continue;
13417 // There should be no mixed ReqItem/ReqSource drop
13418 // This part for ReqItem drop
13419 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13421 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13422 return true;
13424 // This part - for ReqSource
13425 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13427 // examined item is a source item
13428 if (qinfo->ReqSourceId[j] == itemid)
13430 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13432 // 'unique' item
13433 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13434 return true;
13436 // allows custom amount drop when not 0
13437 if (qinfo->ReqSourceCount[j])
13439 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13440 return true;
13441 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13442 return true;
13447 return false;
13450 void Player::SendQuestComplete( uint32 quest_id )
13452 if( quest_id )
13454 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13455 data << uint32(quest_id);
13456 GetSession()->SendPacket( &data );
13457 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13461 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13463 uint32 questid = pQuest->GetQuestId();
13464 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13465 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13466 data << uint32(questid);
13468 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13470 data << uint32(XP);
13471 data << uint32(pQuest->GetRewOrReqMoney());
13473 else
13475 data << uint32(0);
13476 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13479 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13480 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13481 GetSession()->SendPacket( &data );
13483 if (pQuest->GetQuestCompleteScript() != 0)
13484 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13487 void Player::SendQuestFailed( uint32 quest_id )
13489 if( quest_id )
13491 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13492 data << quest_id;
13493 data << uint32(0); // failed reason (4 for inventory is full)
13494 GetSession()->SendPacket( &data );
13495 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13499 void Player::SendQuestTimerFailed( uint32 quest_id )
13501 if( quest_id )
13503 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13504 data << quest_id;
13505 GetSession()->SendPacket( &data );
13506 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13510 void Player::SendCanTakeQuestResponse( uint32 msg )
13512 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13513 data << uint32(msg);
13514 GetSession()->SendPacket( &data );
13515 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13518 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13520 if( pPlayer )
13522 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13523 data << uint64(pPlayer->GetGUID());
13524 data << uint8(msg); // valid values: 0-8
13525 GetSession()->SendPacket( &data );
13526 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13530 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13532 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13533 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13534 //data << pQuest->ReqItemId[item_idx];
13535 //data << count;
13536 GetSession()->SendPacket( &data );
13539 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13541 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13543 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13544 if (entry < 0)
13545 // client expected gameobject template id in form (id|0x80000000)
13546 entry = (-entry) | 0x80000000;
13548 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13549 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13550 data << uint32(pQuest->GetQuestId());
13551 data << uint32(entry);
13552 data << uint32(old_count + add_count);
13553 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13554 data << uint64(guid);
13555 GetSession()->SendPacket(&data);
13557 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13558 if( log_slot < MAX_QUEST_LOG_SIZE)
13559 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13562 /*********************************************************/
13563 /*** LOAD SYSTEM ***/
13564 /*********************************************************/
13566 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13568 bool delete_result = true;
13569 if(!result)
13571 // 0 1 2 3 4 5 6 7 8 9
13572 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13573 if(!result) return false;
13575 else delete_result = false;
13577 Field *fields = result->Fetch();
13579 if(!LoadValues( fields[1].GetString()))
13581 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13582 if(delete_result) delete result;
13583 return false;
13586 // overwrite possible wrong/corrupted guid
13587 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13589 m_name = fields[2].GetCppString();
13591 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13592 SetMapId(fields[6].GetUInt32());
13593 // the instance id is not needed at character enum
13595 m_Played_time[0] = fields[7].GetUInt32();
13596 m_Played_time[1] = fields[8].GetUInt32();
13598 m_atLoginFlags = fields[9].GetUInt32();
13600 // I don't see these used anywhere ..
13601 /*_LoadGroup();
13603 _LoadBoundInstances();*/
13605 if (delete_result) delete result;
13607 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13608 m_items[i] = NULL;
13610 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13611 m_deathState = DEAD;
13613 return true;
13616 void Player::_LoadDeclinedNames(QueryResult* result)
13618 if(!result)
13619 return;
13621 if(m_declinedname)
13622 delete m_declinedname;
13624 m_declinedname = new DeclinedName;
13625 Field *fields = result->Fetch();
13626 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13627 m_declinedname->name[i] = fields[i].GetCppString();
13629 delete result;
13632 void Player::_LoadArenaTeamInfo(QueryResult *result)
13634 // arenateamid, played_week, played_season, personal_rating
13635 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13636 if (!result)
13637 return;
13641 Field *fields = result->Fetch();
13643 uint32 arenateamid = fields[0].GetUInt32();
13644 uint32 played_week = fields[1].GetUInt32();
13645 uint32 played_season = fields[2].GetUInt32();
13646 uint32 personal_rating = fields[3].GetUInt32();
13648 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13649 if(!aTeam)
13651 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13652 continue;
13654 uint8 arenaSlot = aTeam->GetSlot();
13656 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13657 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13658 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13659 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13660 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13661 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13663 }while (result->NextRow());
13664 delete result;
13667 void Player::_LoadEquipmentSets(QueryResult *result)
13669 // 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));
13670 if (!result)
13671 return;
13673 uint32 count = 0;
13676 Field *fields = result->Fetch();
13678 EquipmentSet eqSet;
13680 eqSet.Guid = fields[0].GetUInt64();
13681 uint32 index = fields[1].GetUInt32();
13682 eqSet.Name = fields[2].GetCppString();
13683 eqSet.IconName = fields[3].GetCppString();
13684 eqSet.state = EQUIPMENT_SET_UNCHANGED;
13686 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
13687 eqSet.Items[i] = fields[4+i].GetUInt32();
13689 m_EquipmentSets[index] = eqSet;
13691 ++count;
13693 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
13694 break;
13695 } while (result->NextRow());
13696 delete result;
13699 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13701 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13702 if(!result)
13703 return false;
13705 Field *fields = result->Fetch();
13707 x = fields[0].GetFloat();
13708 y = fields[1].GetFloat();
13709 z = fields[2].GetFloat();
13710 o = fields[3].GetFloat();
13711 mapid = fields[4].GetUInt32();
13712 in_flight = !fields[5].GetCppString().empty();
13714 delete result;
13715 return true;
13718 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13720 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13721 if( !result )
13722 return false;
13724 Field *fields = result->Fetch();
13726 data = StrSplit(fields[0].GetCppString(), " ");
13728 delete result;
13730 return true;
13733 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13735 if(index >= data.size())
13736 return 0;
13738 return (uint32)atoi(data[index].c_str());
13741 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13743 float result;
13744 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13745 memcpy(&result, &temp, sizeof(result));
13747 return result;
13750 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13752 Tokens data;
13753 if(!LoadValuesArrayFromDB(data,guid))
13754 return 0;
13756 return GetUInt32ValueFromArray(data,index);
13759 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13761 float result;
13762 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13763 memcpy(&result, &temp, sizeof(result));
13765 return result;
13768 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13770 //// 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
13771 //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);
13772 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13774 if(!result)
13776 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13777 return false;
13780 Field *fields = result->Fetch();
13782 uint32 dbAccountId = fields[1].GetUInt32();
13784 // check if the character's account in the db and the logged in account match.
13785 // player should be able to load/delete character only with correct account!
13786 if( dbAccountId != GetSession()->GetAccountId() )
13788 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13789 delete result;
13790 return false;
13793 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13795 m_name = fields[3].GetCppString();
13797 // check name limitations
13798 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13800 delete result;
13801 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13802 return false;
13805 if(!LoadValues( fields[2].GetString()))
13807 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13808 delete result;
13809 return false;
13812 // overwrite possible wrong/corrupted guid
13813 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13815 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13816 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13818 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13819 SetVisibleItemSlot(slot, NULL);
13821 if (m_items[slot])
13823 delete m_items[slot];
13824 m_items[slot] = NULL;
13828 // update money limits
13829 if(GetMoney() > MAX_MONEY_AMOUNT)
13830 SetMoney(MAX_MONEY_AMOUNT);
13832 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13833 outDebugValues();
13835 m_race = fields[4].GetUInt8();
13836 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13837 //Other way is to saves m_team into characters table.
13838 setFactionForRace(m_race);
13839 SetCharm(NULL);
13841 m_class = fields[5].GetUInt8();
13843 // load home bind and check in same time class/race pair, it used later for restore broken positions
13844 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13845 return false;
13847 InitPrimaryProffesions(); // to max set before any spell loaded
13849 // init saved position, and fix it later if problematic
13850 uint32 transGUID = fields[24].GetUInt32();
13851 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13852 SetMapId(fields[9].GetUInt32());
13853 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13855 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13857 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13859 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13860 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13861 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13863 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13865 // check arena teams integrity
13866 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13868 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13869 if(!arena_team_id)
13870 continue;
13872 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13873 if(at->HaveMember(GetGUID()))
13874 continue;
13876 // arena team not exist or not member, cleanup fields
13877 for(int j =0; j < 6; ++j)
13878 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13881 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13883 if(!IsPositionValid())
13885 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());
13886 RelocateToHomebind();
13888 transGUID = 0;
13890 m_movementInfo.t_x = 0.0f;
13891 m_movementInfo.t_y = 0.0f;
13892 m_movementInfo.t_z = 0.0f;
13893 m_movementInfo.t_o = 0.0f;
13896 uint32 bgid = fields[34].GetUInt32();
13897 uint32 bgteam = fields[35].GetUInt32();
13899 if(bgid) //saved in BattleGround
13901 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13903 // check entry point and fix to homebind if need
13904 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
13905 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
13906 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
13908 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
13910 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
13912 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
13913 AddBattleGroundQueueId(bgQueueTypeId);
13915 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
13916 SetBGTeam(bgteam);
13918 //join player to battleground group
13919 currentBg->EventPlayerLoggedIn(this, GetGUID());
13920 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
13922 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
13924 else
13926 Relocate(GetBattleGroundEntryPoint());
13927 //RemoveArenaAuras(true);
13930 else
13932 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
13933 // if server restart after player save in BG or area
13934 // player can have current coordinates in to BG/Arean map, fix this
13935 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
13937 // return to BG master
13938 SetMapId(fields[36].GetUInt32());
13939 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13941 // check entry point and fix to homebind if need
13942 mapEntry = sMapStore.LookupEntry(GetMapId());
13943 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
13944 RelocateToHomebind();
13948 if (transGUID != 0)
13950 m_movementInfo.t_x = fields[20].GetFloat();
13951 m_movementInfo.t_y = fields[21].GetFloat();
13952 m_movementInfo.t_z = fields[22].GetFloat();
13953 m_movementInfo.t_o = fields[23].GetFloat();
13955 if( !MaNGOS::IsValidMapCoord(
13956 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13957 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13958 // transport size limited
13959 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13961 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13962 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13963 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13965 RelocateToHomebind();
13967 m_movementInfo.t_x = 0.0f;
13968 m_movementInfo.t_y = 0.0f;
13969 m_movementInfo.t_z = 0.0f;
13970 m_movementInfo.t_o = 0.0f;
13972 transGUID = 0;
13976 if (transGUID != 0)
13978 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13980 if( (*iter)->GetGUIDLow() == transGUID)
13982 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
13983 // client without expansion support
13984 if(GetSession()->Expansion() < transMapEntry->Expansion())
13986 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
13987 break;
13990 m_transport = *iter;
13991 m_transport->AddPassenger(this);
13992 SetMapId(m_transport->GetMapId());
13993 break;
13997 if(!m_transport)
13999 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14000 guid,transGUID);
14002 RelocateToHomebind();
14004 m_movementInfo.t_x = 0.0f;
14005 m_movementInfo.t_y = 0.0f;
14006 m_movementInfo.t_z = 0.0f;
14007 m_movementInfo.t_o = 0.0f;
14009 transGUID = 0;
14012 else // not transport case
14014 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14015 // client without expansion support
14016 if(GetSession()->Expansion() < mapEntry->Expansion())
14018 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14019 RelocateToHomebind();
14023 // NOW player must have valid map
14024 // load the player's map here if it's not already loaded
14025 Map *map = GetMap();
14027 // since the player may not be bound to the map yet, make sure subsequent
14028 // getmap calls won't create new maps
14029 SetInstanceId(map->GetInstanceId());
14031 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14032 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14034 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14035 if(at)
14036 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14037 else
14038 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14041 SaveRecallPosition();
14043 time_t now = time(NULL);
14044 time_t logoutTime = time_t(fields[16].GetUInt64());
14046 // since last logout (in seconds)
14047 uint64 time_diff = uint64(now - logoutTime);
14049 // set value, including drunk invisibility detection
14050 // calculate sobering. after 15 minutes logged out, the player will be sober again
14051 float soberFactor;
14052 if(time_diff > 15*MINUTE)
14053 soberFactor = 0;
14054 else
14055 soberFactor = 1-time_diff/(15.0f*MINUTE);
14056 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14057 SetDrunkValue(newDrunkenValue);
14059 m_rest_bonus = fields[15].GetFloat();
14060 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14061 float bubble0 = 0.031;
14062 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14063 float bubble1 = 0.125;
14065 if((int32)fields[16].GetUInt32() > 0)
14067 float bubble = fields[17].GetUInt32() > 0
14068 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14069 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14071 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14074 m_cinematic = fields[12].GetUInt32();
14075 m_Played_time[0]= fields[13].GetUInt32();
14076 m_Played_time[1]= fields[14].GetUInt32();
14078 m_resetTalentsCost = fields[18].GetUInt32();
14079 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14081 // reserve some flags
14082 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14084 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14085 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14087 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14089 uint32 extraflags = fields[25].GetUInt32();
14091 m_stableSlots = fields[26].GetUInt32();
14092 if(m_stableSlots > MAX_PET_STABLES)
14094 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14095 m_stableSlots = MAX_PET_STABLES;
14098 m_atLoginFlags = fields[27].GetUInt32();
14100 // Honor system
14101 // Update Honor kills data
14102 m_lastHonorUpdateTime = logoutTime;
14103 UpdateHonorFields();
14105 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14106 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14107 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14109 std::string taxi_nodes = fields[31].GetCppString();
14111 delete result;
14113 // clear channel spell data (if saved at channel spell casting)
14114 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14115 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14117 // clear charm/summon related fields
14118 SetCharm(NULL);
14119 SetPet(NULL);
14120 SetCharmerGUID(0);
14121 SetOwnerGUID(0);
14122 SetCreatorGUID(0);
14124 // reset some aura modifiers before aura apply
14125 SetFarSightGUID(0);
14126 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14127 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14129 _LoadSkills();
14131 // make sure the unit is considered out of combat for proper loading
14132 ClearInCombat();
14134 // make sure the unit is considered not in duel for proper loading
14135 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14136 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14138 // remember loaded power/health values to restore after stats initialization and modifier applying
14139 uint32 savedHealth = GetHealth();
14140 uint32 savedPower[MAX_POWERS];
14141 for(uint32 i = 0; i < MAX_POWERS; ++i)
14142 savedPower[i] = GetPower(Powers(i));
14144 // reset stats before loading any modifiers
14145 InitStatsForLevel();
14146 InitTaxiNodesForLevel();
14147 InitGlyphsForLevel();
14148 InitRunes();
14150 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14152 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14153 //_LoadMail();
14155 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14156 _LoadGlyphAuras();
14158 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14159 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14160 m_deathState = DEAD;
14162 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14164 // after spell load, learn rewarded spell if need also
14165 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14166 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14168 // after spell and quest load
14169 InitTalentForLevel();
14170 learnDefaultSpells();
14172 // must be before inventory (some items required reputation check)
14173 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14175 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14177 // update items with duration and realtime
14178 UpdateItemDuration(time_diff, true);
14180 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14182 // unread mails and next delivery time, actual mails not loaded
14183 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14185 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14187 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14188 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14189 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14191 if(!HasTitle(curTitle))
14192 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14195 // Not finish taxi flight path
14196 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14198 // problems with taxi path loading
14199 TaxiNodesEntry const* nodeEntry = NULL;
14200 if(uint32 node_id = m_taxi.GetTaxiSource())
14201 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14203 if(!nodeEntry) // don't know taxi start node, to homebind
14205 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14206 RelocateToHomebind();
14207 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14209 else // have start node, to it
14211 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14212 SetMapId(nodeEntry->map_id);
14213 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14214 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14216 m_taxi.ClearTaxiDestinations();
14218 else if(uint32 node_id = m_taxi.GetTaxiSource())
14220 // save source node as recall coord to prevent recall and fall from sky
14221 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14222 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14223 m_recallMap = nodeEntry->map_id;
14224 m_recallX = nodeEntry->x;
14225 m_recallY = nodeEntry->y;
14226 m_recallZ = nodeEntry->z;
14228 // flight will started later
14231 // has to be called after last Relocate() in Player::LoadFromDB
14232 SetFallInformation(0, GetPositionZ());
14234 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14236 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14237 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14238 if(!isAlive())
14239 RemoveAllAurasOnDeath();
14241 //apply all stat bonuses from items and auras
14242 SetCanModifyStats(true);
14243 UpdateAllStats();
14245 // restore remembered power/health values (but not more max values)
14246 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14247 for(uint32 i = 0; i < MAX_POWERS; ++i)
14248 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14250 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14251 outDebugValues();
14253 // GM state
14254 if(GetSession()->GetSecurity() > SEC_PLAYER)
14256 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14258 default:
14259 case 0: break; // disable
14260 case 1: SetGameMaster(true); break; // enable
14261 case 2: // save state
14262 if(extraflags & PLAYER_EXTRA_GM_ON)
14263 SetGameMaster(true);
14264 break;
14267 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14269 default:
14270 case 0: SetGMVisible(false); break; // invisible
14271 case 1: break; // visible
14272 case 2: // save state
14273 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14274 SetGMVisible(false);
14275 break;
14278 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14280 default:
14281 case 0: break; // disable
14282 case 1: SetAcceptTicket(true); break; // enable
14283 case 2: // save state
14284 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14285 SetAcceptTicket(true);
14286 break;
14289 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14291 default:
14292 case 0: break; // disable
14293 case 1: SetGMChat(true); break; // enable
14294 case 2: // save state
14295 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14296 SetGMChat(true);
14297 break;
14300 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14302 default:
14303 case 0: break; // disable
14304 case 1: SetAcceptWhispers(true); break; // enable
14305 case 2: // save state
14306 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14307 SetAcceptWhispers(true);
14308 break;
14312 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14314 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14315 m_achievementMgr.CheckAllAchievementCriteria();
14317 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
14319 return true;
14322 bool Player::isAllowedToLoot(Creature* creature)
14324 if(Player* recipient = creature->GetLootRecipient())
14326 if (recipient == this)
14327 return true;
14328 if( Group* otherGroup = recipient->GetGroup())
14330 Group* thisGroup = GetGroup();
14331 if(!thisGroup)
14332 return false;
14333 return thisGroup == otherGroup;
14335 return false;
14337 else
14338 // prevent other players from looting if the recipient got disconnected
14339 return !creature->hasLootRecipient();
14342 void Player::_LoadActions(QueryResult *result)
14344 m_actionButtons.clear();
14346 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14348 if(result)
14352 Field *fields = result->Fetch();
14354 uint8 button = fields[0].GetUInt8();
14356 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14357 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14358 else
14360 sLog.outError( " ...at loading, and will deleted in DB also");
14362 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14363 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14366 while( result->NextRow() );
14368 delete result;
14372 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14374 m_Auras.clear();
14375 for (int i = 0; i < TOTAL_AURAS; ++i)
14376 m_modAuras[i].clear();
14378 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14380 if(result)
14384 Field *fields = result->Fetch();
14385 uint64 caster_guid = fields[0].GetUInt64();
14386 uint32 spellid = fields[1].GetUInt32();
14387 uint32 effindex = fields[2].GetUInt32();
14388 uint32 stackcount = fields[3].GetUInt32();
14389 int32 damage = (int32)fields[4].GetUInt32();
14390 int32 maxduration = (int32)fields[5].GetUInt32();
14391 int32 remaintime = (int32)fields[6].GetUInt32();
14392 int32 remaincharges = (int32)fields[7].GetUInt32();
14394 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14395 if(!spellproto)
14397 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14398 continue;
14401 if(effindex >= 3)
14403 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14404 continue;
14407 // negative effects should continue counting down after logout
14408 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14410 if(remaintime <= int32(timediff))
14411 continue;
14413 remaintime -= timediff;
14416 // prevent wrong values of remaincharges
14417 if(spellproto->procCharges)
14419 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14420 remaincharges = spellproto->procCharges;
14422 else
14423 remaincharges = 0;
14426 for(uint32 i=0; i<stackcount; ++i)
14428 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14429 if(!damage)
14430 damage = aura->GetModifier()->m_amount;
14432 // reset stolen single target auras
14433 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14434 aura->SetIsSingleTarget(false);
14436 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14437 AddAura(aura);
14438 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14441 while( result->NextRow() );
14443 delete result;
14446 if(m_class == CLASS_WARRIOR)
14447 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14450 void Player::_LoadGlyphAuras()
14452 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14454 if (uint32 glyph = GetGlyph(i))
14456 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14458 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14460 if(gp->TypeFlags == gs->TypeFlags)
14462 CastSpell(this, gp->SpellId, true);
14463 continue;
14465 else
14466 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14468 else
14469 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14471 else
14472 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14474 // On any error remove glyph
14475 SetGlyph(i, 0);
14480 void Player::LoadCorpse()
14482 if( isAlive() )
14484 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14486 else
14488 if(Corpse *corpse = GetCorpse())
14490 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14492 else
14494 //Prevent Dead Player login without corpse
14495 ResurrectPlayer(0.5f);
14500 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14502 //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());
14503 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14504 //NOTE: the "order by `bag`" is important because it makes sure
14505 //the bagMap is filled before items in the bags are loaded
14506 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14507 //expected to be equipped before offhand items (TODO: fixme)
14509 uint32 zone = GetZoneId();
14511 if (result)
14513 std::list<Item*> problematicItems;
14515 // prevent items from being added to the queue when stored
14516 m_itemUpdateQueueBlocked = true;
14519 Field *fields = result->Fetch();
14520 uint32 bag_guid = fields[1].GetUInt32();
14521 uint8 slot = fields[2].GetUInt8();
14522 uint32 item_guid = fields[3].GetUInt32();
14523 uint32 item_id = fields[4].GetUInt32();
14525 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14527 if(!proto)
14529 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14530 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14531 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14532 continue;
14535 Item *item = NewItemOrBag(proto);
14537 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14539 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14540 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14541 item->FSetState(ITEM_REMOVED);
14542 item->SaveToDB(); // it also deletes item object !
14543 continue;
14546 // not allow have in alive state item limited to another map/zone
14547 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14549 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14550 item->FSetState(ITEM_REMOVED);
14551 item->SaveToDB(); // it also deletes item object !
14552 continue;
14555 // "Conjured items disappear if you are logged out for more than 15 minutes"
14556 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14558 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14559 item->FSetState(ITEM_REMOVED);
14560 item->SaveToDB(); // it also deletes item object !
14561 continue;
14564 bool success = true;
14566 if (!bag_guid)
14568 // the item is not in a bag
14569 item->SetContainer( NULL );
14570 item->SetSlot(slot);
14572 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14574 ItemPosCountVec dest;
14575 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14576 item = StoreItem(dest, item, true);
14577 else
14578 success = false;
14580 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14582 uint16 dest;
14583 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14584 QuickEquipItem(dest, item);
14585 else
14586 success = false;
14588 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14590 ItemPosCountVec dest;
14591 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14592 item = BankItem(dest, item, true);
14593 else
14594 success = false;
14597 if(success)
14599 // store bags that may contain items in them
14600 if(item->IsBag() && IsBagPos(item->GetPos()))
14601 bagMap[item_guid] = (Bag*)item;
14604 else
14606 item->SetSlot(NULL_SLOT);
14607 // the item is in a bag, find the bag
14608 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14609 if(itr != bagMap.end())
14610 itr->second->StoreItem(slot, item, true );
14611 else
14612 success = false;
14615 // item's state may have changed after stored
14616 if (success)
14617 item->SetState(ITEM_UNCHANGED, this);
14618 else
14620 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);
14621 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14622 problematicItems.push_back(item);
14624 } while (result->NextRow());
14626 delete result;
14627 m_itemUpdateQueueBlocked = false;
14629 // send by mail problematic items
14630 while(!problematicItems.empty())
14632 // fill mail
14633 MailItemsInfo mi; // item list preparing
14635 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14637 Item* item = problematicItems.front();
14638 problematicItems.pop_front();
14640 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14643 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14645 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14648 //if(isAlive())
14649 _ApplyAllItemMods();
14652 // load mailed item which should receive current player
14653 void Player::_LoadMailedItems(Mail *mail)
14655 // data needs to be at first place for Item::LoadFromDB
14656 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);
14657 if(!result)
14658 return;
14662 Field *fields = result->Fetch();
14663 uint32 item_guid_low = fields[1].GetUInt32();
14664 uint32 item_template = fields[2].GetUInt32();
14666 mail->AddItem(item_guid_low, item_template);
14668 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14670 if(!proto)
14672 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);
14673 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14674 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14675 continue;
14678 Item *item = NewItemOrBag(proto);
14680 if(!item->LoadFromDB(item_guid_low, 0, result))
14682 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14683 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14684 item->FSetState(ITEM_REMOVED);
14685 item->SaveToDB(); // it also deletes item object !
14686 continue;
14689 AddMItem(item);
14690 } while (result->NextRow());
14692 delete result;
14695 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14697 //set a count of unread mails
14698 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14699 if (resultUnread)
14701 Field *fieldMail = resultUnread->Fetch();
14702 unReadMails = fieldMail[0].GetUInt8();
14703 delete resultUnread;
14706 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14707 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14708 if (resultDelivery)
14710 Field *fieldMail = resultDelivery->Fetch();
14711 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14712 delete resultDelivery;
14716 void Player::_LoadMail()
14718 m_mail.clear();
14719 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14720 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());
14721 if(result)
14725 Field *fields = result->Fetch();
14726 Mail *m = new Mail;
14727 m->messageID = fields[0].GetUInt32();
14728 m->messageType = fields[1].GetUInt8();
14729 m->sender = fields[2].GetUInt32();
14730 m->receiver = fields[3].GetUInt32();
14731 m->subject = fields[4].GetCppString();
14732 m->itemTextId = fields[5].GetUInt32();
14733 bool has_items = fields[6].GetBool();
14734 m->expire_time = (time_t)fields[7].GetUInt64();
14735 m->deliver_time = (time_t)fields[8].GetUInt64();
14736 m->money = fields[9].GetUInt32();
14737 m->COD = fields[10].GetUInt32();
14738 m->checked = fields[11].GetUInt32();
14739 m->stationery = fields[12].GetUInt8();
14740 m->mailTemplateId = fields[13].GetInt16();
14742 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14744 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14745 m->mailTemplateId = 0;
14748 m->state = MAIL_STATE_UNCHANGED;
14750 if (has_items)
14751 _LoadMailedItems(m);
14753 m_mail.push_back(m);
14754 } while( result->NextRow() );
14755 delete result;
14757 m_mailsLoaded = true;
14760 void Player::LoadPet()
14762 //fixme: the pet should still be loaded if the player is not in world
14763 // just not added to the map
14764 if(IsInWorld())
14766 Pet *pet = new Pet;
14767 if(!pet->LoadPetFromDB(this,0,0,true))
14768 delete pet;
14772 void Player::_LoadQuestStatus(QueryResult *result)
14774 mQuestStatus.clear();
14776 uint32 slot = 0;
14778 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14779 //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());
14781 if(result)
14785 Field *fields = result->Fetch();
14787 uint32 quest_id = fields[0].GetUInt32();
14788 // used to be new, no delete?
14789 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14790 if( pQuest )
14792 // find or create
14793 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14795 uint32 qstatus = fields[1].GetUInt32();
14796 if(qstatus < MAX_QUEST_STATUS)
14797 questStatusData.m_status = QuestStatus(qstatus);
14798 else
14800 questStatusData.m_status = QUEST_STATUS_NONE;
14801 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14804 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14805 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14807 time_t quest_time = time_t(fields[4].GetUInt64());
14809 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14811 AddTimedQuest( quest_id );
14813 if (quest_time <= sWorld.GetGameTime())
14814 questStatusData.m_timer = 1;
14815 else
14816 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14818 else
14819 quest_time = 0;
14821 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14822 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14823 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14824 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14825 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14826 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14827 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14828 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14830 questStatusData.uState = QUEST_UNCHANGED;
14832 // add to quest log
14833 if( slot < MAX_QUEST_LOG_SIZE &&
14834 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14835 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14836 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14838 SetQuestSlot(slot,quest_id,quest_time);
14840 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14841 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14843 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14844 if(questStatusData.m_creatureOrGOcount[idx])
14845 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14847 ++slot;
14850 if(questStatusData.m_rewarded)
14852 // learn rewarded spell if unknown
14853 learnQuestRewardedSpells(pQuest);
14855 // set rewarded title if any
14856 if(pQuest->GetCharTitleId())
14858 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14859 SetTitle(titleEntry);
14862 if(pQuest->GetBonusTalents())
14863 m_questRewardTalentCount+=pQuest->GetBonusTalents();
14866 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14869 while( result->NextRow() );
14871 delete result;
14874 // clear quest log tail
14875 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14876 SetQuestSlot(i,0);
14879 void Player::_LoadDailyQuestStatus(QueryResult *result)
14881 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14882 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14884 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14886 if(result)
14888 uint32 quest_daily_idx = 0;
14892 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14894 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14895 break;
14898 Field *fields = result->Fetch();
14900 uint32 quest_id = fields[0].GetUInt32();
14902 // save _any_ from daily quest times (it must be after last reset anyway)
14903 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14905 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14906 if( !pQuest )
14907 continue;
14909 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14910 ++quest_daily_idx;
14912 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14914 while( result->NextRow() );
14916 delete result;
14919 m_DailyQuestChanged = false;
14922 void Player::_LoadSpells(QueryResult *result)
14924 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14926 if(result)
14930 Field *fields = result->Fetch();
14932 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
14934 while( result->NextRow() );
14936 delete result;
14940 void Player::_LoadGroup(QueryResult *result)
14942 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14943 if(result)
14945 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14946 delete result;
14947 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14948 if(group)
14950 uint8 subgroup = group->GetMemberGroup(GetGUID());
14951 SetGroup(group, subgroup);
14952 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14954 // the group leader may change the instance difficulty while the player is offline
14955 SetDifficulty(group->GetDifficulty());
14961 void Player::_LoadBoundInstances(QueryResult *result)
14963 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
14964 m_boundInstances[i].clear();
14966 Group *group = GetGroup();
14968 //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));
14969 if(result)
14973 Field *fields = result->Fetch();
14974 bool perm = fields[1].GetBool();
14975 uint32 mapId = fields[2].GetUInt32();
14976 uint32 instanceId = fields[0].GetUInt32();
14977 uint8 difficulty = fields[3].GetUInt8();
14978 time_t resetTime = (time_t)fields[4].GetUInt64();
14979 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14980 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14981 // and in that case it is not used
14983 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
14984 if(!mapEntry || !mapEntry->IsDungeon())
14986 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
14987 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14988 continue;
14991 if(!perm && group)
14993 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);
14994 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14995 continue;
14998 // since non permanent binds are always solo bind, they can always be reset
14999 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15000 if(save) BindToInstance(save, perm, true);
15001 } while(result->NextRow());
15002 delete result;
15006 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15008 // some instances only have one difficulty
15009 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15010 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15012 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15013 if(itr != m_boundInstances[difficulty].end())
15014 return &itr->second;
15015 else
15016 return NULL;
15019 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15021 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15022 UnbindInstance(itr, difficulty, unload);
15025 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15027 if(itr != m_boundInstances[difficulty].end())
15029 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15030 itr->second.save->RemovePlayer(this); // save can become invalid
15031 m_boundInstances[difficulty].erase(itr++);
15035 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15037 if(save)
15039 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15040 if(bind.save)
15042 // update the save when the group kills a boss
15043 if(permanent != bind.perm || save != bind.save)
15044 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());
15046 else
15047 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15049 if(bind.save != save)
15051 if(bind.save) bind.save->RemovePlayer(this);
15052 save->AddPlayer(this);
15055 if(permanent) save->SetCanReset(false);
15057 bind.save = save;
15058 bind.perm = permanent;
15059 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());
15060 return &bind;
15062 else
15063 return NULL;
15066 void Player::SendRaidInfo()
15068 uint32 counter = 0;
15070 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15072 size_t p_counter = data.wpos();
15073 data << uint32(counter); // placeholder
15075 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15077 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15079 if(itr->second.perm)
15081 InstanceSave *save = itr->second.save;
15082 data << uint32(save->GetMapId());
15083 data << uint32(save->GetResetTime() - time(NULL));
15084 data << uint32(save->GetInstanceId());
15085 data << uint32(save->GetDifficulty());
15086 ++counter;
15090 data.put<uint32>(p_counter,counter);
15091 GetSession()->SendPacket(&data);
15095 - called on every successful teleportation to a map
15097 void Player::SendSavedInstances()
15099 bool hasBeenSaved = false;
15100 WorldPacket data;
15102 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15104 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15106 if(itr->second.perm) // only permanent binds are sent
15108 hasBeenSaved = true;
15109 break;
15114 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15115 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15116 data << uint32(hasBeenSaved);
15117 GetSession()->SendPacket(&data);
15119 if(!hasBeenSaved)
15120 return;
15122 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15124 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15126 if(itr->second.perm)
15128 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15129 data << uint32(itr->second.save->GetMapId());
15130 GetSession()->SendPacket(&data);
15136 /// convert the player's binds to the group
15137 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15139 bool has_binds = false;
15140 bool has_solo = false;
15142 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15143 assert(player_guid);
15145 // copy all binds to the group, when changing leader it's assumed the character
15146 // will not have any solo binds
15148 if(player)
15150 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15152 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15154 has_binds = true;
15155 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15156 // permanent binds are not removed
15157 if(!itr->second.perm)
15159 player->UnbindInstance(itr, i, true); // increments itr
15160 has_solo = true;
15162 else
15163 ++itr;
15168 // if the player's not online we don't know what binds it has
15169 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));
15170 // the following should not get executed when changing leaders
15171 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15174 bool Player::_LoadHomeBind(QueryResult *result)
15176 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15177 if(!info)
15179 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15180 return false;
15183 bool ok = false;
15184 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15185 if (result)
15187 Field *fields = result->Fetch();
15188 m_homebindMapId = fields[0].GetUInt32();
15189 m_homebindZoneId = fields[1].GetUInt16();
15190 m_homebindX = fields[2].GetFloat();
15191 m_homebindY = fields[3].GetFloat();
15192 m_homebindZ = fields[4].GetFloat();
15193 delete result;
15195 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15197 // accept saved data only for valid position (and non instanceable), and accessable
15198 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15199 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15201 ok = true;
15203 else
15204 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15207 if(!ok)
15209 m_homebindMapId = info->mapId;
15210 m_homebindZoneId = info->zoneId;
15211 m_homebindX = info->positionX;
15212 m_homebindY = info->positionY;
15213 m_homebindZ = info->positionZ;
15215 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);
15218 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15219 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15221 return true;
15224 /*********************************************************/
15225 /*** SAVE SYSTEM ***/
15226 /*********************************************************/
15228 void Player::SaveToDB()
15230 // delay auto save at any saves (manual, in code, or autosave)
15231 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15233 // first save/honor gain after midnight will also update the player's honor fields
15234 UpdateHonorFields();
15236 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15237 //save, far from tavern/city
15238 //save, but in tavern/city
15239 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15240 outDebugValues();
15242 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15243 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15244 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15245 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15246 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15247 uint32 tmp_displayid = GetDisplayId();
15249 // Set player sit state to standing on save, also stealth and shifted form
15250 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15251 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15252 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15253 SetDisplayId(GetNativeDisplayId());
15255 bool inworld = IsInWorld();
15257 CharacterDatabase.BeginTransaction();
15259 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15261 std::string sql_name = m_name;
15262 CharacterDatabase.escape_string(sql_name);
15264 std::ostringstream ss;
15265 ss << "INSERT INTO characters (guid,account,name,race,class,"
15266 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15267 "taximask, online, cinematic, "
15268 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15269 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15270 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15271 << GetGUIDLow() << ", "
15272 << GetSession()->GetAccountId() << ", '"
15273 << sql_name << "', "
15274 << m_race << ", "
15275 << m_class << ", ";
15277 if(!IsBeingTeleported())
15279 ss << GetMapId() << ", "
15280 << (uint32)GetDifficulty() << ", "
15281 << finiteAlways(GetPositionX()) << ", "
15282 << finiteAlways(GetPositionY()) << ", "
15283 << finiteAlways(GetPositionZ()) << ", "
15284 << finiteAlways(GetOrientation()) << ", '";
15286 else
15288 ss << GetTeleportDest().mapid << ", "
15289 << (uint32)GetDifficulty() << ", "
15290 << finiteAlways(GetTeleportDest().x) << ", "
15291 << finiteAlways(GetTeleportDest().y) << ", "
15292 << finiteAlways(GetTeleportDest().z) << ", "
15293 << finiteAlways(GetTeleportDest().o) << ", '";
15296 uint16 i;
15297 for( i = 0; i < m_valuesCount; ++i )
15299 ss << GetUInt32Value(i) << " ";
15302 ss << "', ";
15304 ss << m_taxi; // string with TaxiMaskSize numbers
15306 ss << ", ";
15307 ss << (inworld ? 1 : 0);
15309 ss << ", ";
15310 ss << m_cinematic;
15312 ss << ", ";
15313 ss << m_Played_time[0];
15314 ss << ", ";
15315 ss << m_Played_time[1];
15317 ss << ", ";
15318 ss << finiteAlways(m_rest_bonus);
15319 ss << ", ";
15320 ss << (uint64)time(NULL);
15321 ss << ", ";
15322 ss << is_save_resting;
15323 ss << ", ";
15324 ss << m_resetTalentsCost;
15325 ss << ", ";
15326 ss << (uint64)m_resetTalentsTime;
15328 ss << ", ";
15329 ss << finiteAlways(m_movementInfo.t_x);
15330 ss << ", ";
15331 ss << finiteAlways(m_movementInfo.t_y);
15332 ss << ", ";
15333 ss << finiteAlways(m_movementInfo.t_z);
15334 ss << ", ";
15335 ss << finiteAlways(m_movementInfo.t_o);
15336 ss << ", ";
15337 if (m_transport)
15338 ss << m_transport->GetGUIDLow();
15339 else
15340 ss << "0";
15342 ss << ", ";
15343 ss << m_ExtraFlags;
15345 ss << ", ";
15346 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15348 ss << ", ";
15349 ss << uint32(m_atLoginFlags);
15351 ss << ", ";
15352 ss << GetZoneId();
15354 ss << ", ";
15355 ss << (uint64)m_deathExpireTime;
15357 ss << ", '";
15358 ss << m_taxi.SaveTaxiDestinationsToString();
15359 ss << "', '0', ";
15360 ss << GetBattleGroundId();
15361 ss << ", ";
15362 ss << GetBGTeam();
15363 ss << ", ";
15364 ss << m_bgEntryPoint.mapid << ", "
15365 << finiteAlways(m_bgEntryPoint.x) << ", "
15366 << finiteAlways(m_bgEntryPoint.y) << ", "
15367 << finiteAlways(m_bgEntryPoint.z) << ", "
15368 << finiteAlways(m_bgEntryPoint.o);
15369 ss << ")";
15371 CharacterDatabase.Execute( ss.str().c_str() );
15373 if(m_mailsUpdated) //save mails only when needed
15374 _SaveMail();
15376 _SaveInventory();
15377 _SaveQuestStatus();
15378 _SaveDailyQuestStatus();
15379 _SaveSpells();
15380 _SaveSpellCooldowns();
15381 _SaveActions();
15382 _SaveAuras();
15383 m_achievementMgr.SaveToDB();
15384 m_reputationMgr.SaveToDB();
15385 _SaveEquipmentSets();
15386 GetSession()->SaveTutorialsData(); // changed only while character in game
15388 CharacterDatabase.CommitTransaction();
15390 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15391 SetDisplayId(tmp_displayid);
15392 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15393 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15394 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15395 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15397 // save pet (hunter pet level and experience and all type pets health/mana).
15398 if(Pet* pet = GetPet())
15399 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15402 // fast save function for item/money cheating preventing - save only inventory and money state
15403 void Player::SaveInventoryAndGoldToDB()
15405 _SaveInventory();
15406 //money is in data field
15407 SaveDataFieldToDB();
15410 void Player::_SaveActions()
15412 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15414 switch (itr->second.uState)
15416 case ACTIONBUTTON_NEW:
15417 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15418 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15419 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15420 ++itr;
15421 break;
15422 case ACTIONBUTTON_CHANGED:
15423 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15424 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15425 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15426 ++itr;
15427 break;
15428 case ACTIONBUTTON_DELETED:
15429 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15430 m_actionButtons.erase(itr++);
15431 break;
15432 default:
15433 ++itr;
15434 break;
15439 void Player::_SaveAuras()
15441 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15443 AuraMap const& auras = GetAuras();
15445 if (auras.empty())
15446 return;
15448 spellEffectPair lastEffectPair = auras.begin()->first;
15449 uint32 stackCounter = 1;
15451 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15453 if(itr == auras.end() || lastEffectPair != itr->first)
15455 AuraMap::const_iterator itr2 = itr;
15456 // save previous spellEffectPair to db
15457 itr2--;
15459 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15461 //skip all auras from spells that are passive or need a shapeshift
15462 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15464 //do not save single target auras (unless they were cast by the player)
15465 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15467 uint8 i;
15468 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15469 for (i = 0; i < 3; ++i)
15470 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15471 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15472 break;
15474 if (i == 3)
15476 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15477 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15478 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()));
15483 if(itr == auras.end())
15484 break;
15487 if (lastEffectPair == itr->first)
15488 stackCounter++;
15489 else
15491 lastEffectPair = itr->first;
15492 stackCounter = 1;
15497 void Player::_SaveInventory()
15499 // force items in buyback slots to new state
15500 // and remove those that aren't already
15501 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15503 Item *item = m_items[i];
15504 if (!item || item->GetState() == ITEM_NEW) continue;
15505 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15506 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15507 m_items[i]->FSetState(ITEM_NEW);
15510 // update enchantment durations
15511 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15513 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15516 // if no changes
15517 if (m_itemUpdateQueue.empty()) return;
15519 // do not save if the update queue is corrupt
15520 bool error = false;
15521 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15523 Item *item = m_itemUpdateQueue[i];
15524 if(!item || item->GetState() == ITEM_REMOVED) continue;
15525 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15527 if (test == NULL)
15529 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());
15530 error = true;
15532 else if (test != item)
15534 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());
15535 error = true;
15539 if (error)
15541 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15542 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15543 return;
15546 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15548 Item *item = m_itemUpdateQueue[i];
15549 if(!item) continue;
15551 Bag *container = item->GetContainer();
15552 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15554 switch(item->GetState())
15556 case ITEM_NEW:
15557 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());
15558 break;
15559 case ITEM_CHANGED:
15560 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());
15561 break;
15562 case ITEM_REMOVED:
15563 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15564 break;
15565 case ITEM_UNCHANGED:
15566 break;
15569 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15571 m_itemUpdateQueue.clear();
15574 void Player::_SaveMail()
15576 if (!m_mailsLoaded)
15577 return;
15579 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15581 Mail *m = (*itr);
15582 if (m->state == MAIL_STATE_CHANGED)
15584 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15585 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15586 if(m->removedItems.size())
15588 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15589 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15590 m->removedItems.clear();
15592 m->state = MAIL_STATE_UNCHANGED;
15594 else if (m->state == MAIL_STATE_DELETED)
15596 if (m->HasItems())
15597 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15598 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15599 if (m->itemTextId)
15600 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15601 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15602 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15606 //deallocate deleted mails...
15607 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15609 if ((*itr)->state == MAIL_STATE_DELETED)
15611 Mail* m = *itr;
15612 m_mail.erase(itr);
15613 delete m;
15614 itr = m_mail.begin();
15616 else
15617 ++itr;
15620 m_mailsUpdated = false;
15623 void Player::_SaveQuestStatus()
15625 // we don't need transactions here.
15626 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15628 switch (i->second.uState)
15630 case QUEST_NEW :
15631 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15632 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15633 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]);
15634 break;
15635 case QUEST_CHANGED :
15636 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15637 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 );
15638 break;
15639 case QUEST_UNCHANGED:
15640 break;
15642 i->second.uState = QUEST_UNCHANGED;
15646 void Player::_SaveDailyQuestStatus()
15648 if(!m_DailyQuestChanged)
15649 return;
15651 m_DailyQuestChanged = false;
15653 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15655 // we don't need transactions here.
15656 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15657 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15658 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15659 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15660 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15663 void Player::_SaveSpells()
15665 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15667 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15668 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15670 // add only changed/new not dependent spells
15671 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15672 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);
15674 if (itr->second->state == PLAYERSPELL_REMOVED)
15676 delete itr->second;
15677 m_spells.erase(itr++);
15679 else
15681 itr->second->state = PLAYERSPELL_UNCHANGED;
15682 ++itr;
15688 void Player::outDebugValues() const
15690 if(!sLog.IsOutDebug()) // optimize disabled debug output
15691 return;
15693 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15694 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15695 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15696 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15697 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15698 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15699 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15700 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15701 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15702 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15703 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15704 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15707 /*********************************************************/
15708 /*** FLOOD FILTER SYSTEM ***/
15709 /*********************************************************/
15711 void Player::UpdateSpeakTime()
15713 // ignore chat spam protection for GMs in any mode
15714 if(GetSession()->GetSecurity() > SEC_PLAYER)
15715 return;
15717 time_t current = time (NULL);
15718 if(m_speakTime > current)
15720 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15721 if(!max_count)
15722 return;
15724 ++m_speakCount;
15725 if(m_speakCount >= max_count)
15727 // prevent overwrite mute time, if message send just before mutes set, for example.
15728 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15729 if(GetSession()->m_muteTime < new_mute)
15730 GetSession()->m_muteTime = new_mute;
15732 m_speakCount = 0;
15735 else
15736 m_speakCount = 0;
15738 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15741 bool Player::CanSpeak() const
15743 return GetSession()->m_muteTime <= time (NULL);
15746 /*********************************************************/
15747 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15748 /*********************************************************/
15750 void Player::SendAttackSwingNotInRange()
15752 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15753 GetSession()->SendPacket( &data );
15756 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15758 std::ostringstream ss;
15759 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15760 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15761 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15762 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15763 sLog.outDebug(ss.str().c_str());
15764 CharacterDatabase.Execute(ss.str().c_str());
15767 void Player::SaveDataFieldToDB()
15769 std::ostringstream ss;
15770 ss<<"UPDATE characters SET data='";
15772 for(uint16 i = 0; i < m_valuesCount; ++i )
15774 ss << GetUInt32Value(i) << " ";
15776 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15778 CharacterDatabase.Execute(ss.str().c_str());
15781 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15783 std::ostringstream ss2;
15784 ss2<<"UPDATE characters SET data='";
15785 int i=0;
15786 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15788 ss2<<tokens[i]<<" ";
15790 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15792 return CharacterDatabase.Execute(ss2.str().c_str());
15795 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15797 char buf[11];
15798 snprintf(buf,11,"%u",value);
15800 if(index >= tokens.size())
15801 return;
15803 tokens[index] = buf;
15806 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15808 Tokens tokens;
15809 if(!LoadValuesArrayFromDB(tokens,guid))
15810 return;
15812 if(index >= tokens.size())
15813 return;
15815 char buf[11];
15816 snprintf(buf,11,"%u",value);
15817 tokens[index] = buf;
15819 SaveValuesArrayInDB(tokens,guid);
15822 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15824 uint32 temp;
15825 memcpy(&temp, &value, sizeof(value));
15826 Player::SetUInt32ValueInDB(index, temp, guid);
15829 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15831 Tokens tokens;
15832 if(!LoadValuesArrayFromDB(tokens, guid))
15833 return;
15835 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15836 uint8 race = unit_bytes0 & 0xFF;
15837 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15839 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15840 if(!info)
15841 return;
15843 unit_bytes0 &= ~(0xFF << 16);
15844 unit_bytes0 |= (gender << 16);
15845 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15847 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15848 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15850 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15852 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15853 player_bytes2 &= ~0xFF;
15854 player_bytes2 |= facialHair;
15855 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15857 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15858 player_bytes3 &= ~0xFF;
15859 player_bytes3 |= gender;
15860 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15862 SaveValuesArrayInDB(tokens, guid);
15865 void Player::SendAttackSwingNotStanding()
15867 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15868 GetSession()->SendPacket( &data );
15871 void Player::SendAttackSwingDeadTarget()
15873 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15874 GetSession()->SendPacket( &data );
15877 void Player::SendAttackSwingCantAttack()
15879 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15880 GetSession()->SendPacket( &data );
15883 void Player::SendAttackSwingCancelAttack()
15885 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15886 GetSession()->SendPacket( &data );
15889 void Player::SendAttackSwingBadFacingAttack()
15891 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15892 GetSession()->SendPacket( &data );
15895 void Player::SendAutoRepeatCancel()
15897 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15898 data.append(GetPackGUID()); // may be it's target guid
15899 GetSession()->SendPacket( &data );
15902 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15904 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15905 data << Area;
15906 data << Experience;
15907 GetSession()->SendPacket(&data);
15910 void Player::SendDungeonDifficulty(bool IsInGroup)
15912 uint8 val = 0x00000001;
15913 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15914 data << (uint32)GetDifficulty();
15915 data << uint32(val);
15916 data << uint32(IsInGroup);
15917 GetSession()->SendPacket(&data);
15920 void Player::SendResetFailedNotify(uint32 mapid)
15922 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15923 data << uint32(mapid);
15924 GetSession()->SendPacket(&data);
15927 /// Reset all solo instances and optionally send a message on success for each
15928 void Player::ResetInstances(uint8 method)
15930 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15932 // we assume that when the difficulty changes, all instances that can be reset will be
15933 uint8 dif = GetDifficulty();
15935 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15937 InstanceSave *p = itr->second.save;
15938 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15939 if(!entry || !p->CanReset())
15941 ++itr;
15942 continue;
15945 if(method == INSTANCE_RESET_ALL)
15947 // the "reset all instances" method can only reset normal maps
15948 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15950 ++itr;
15951 continue;
15955 // if the map is loaded, reset it
15956 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15957 if(map && map->IsDungeon())
15958 ((InstanceMap*)map)->Reset(method);
15960 // since this is a solo instance there should not be any players inside
15961 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15962 SendResetInstanceSuccess(p->GetMapId());
15964 p->DeleteFromDB();
15965 m_boundInstances[dif].erase(itr++);
15967 // the following should remove the instance save from the manager and delete it as well
15968 p->RemovePlayer(this);
15972 void Player::SendResetInstanceSuccess(uint32 MapId)
15974 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15975 data << MapId;
15976 GetSession()->SendPacket(&data);
15979 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15981 // TODO: find what other fail reasons there are besides players in the instance
15982 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15983 data << reason;
15984 data << MapId;
15985 GetSession()->SendPacket(&data);
15988 /*********************************************************/
15989 /*** Update timers ***/
15990 /*********************************************************/
15992 ///checks the 15 afk reports per 5 minutes limit
15993 void Player::UpdateAfkReport(time_t currTime)
15995 if(m_bgAfkReportedTimer <= currTime)
15997 m_bgAfkReportedCount = 0;
15998 m_bgAfkReportedTimer = currTime+5*MINUTE;
16002 void Player::UpdateContestedPvP(uint32 diff)
16004 if(!m_contestedPvPTimer||isInCombat())
16005 return;
16006 if(m_contestedPvPTimer <= diff)
16008 ResetContestedPvP();
16010 else
16011 m_contestedPvPTimer -= diff;
16014 void Player::UpdatePvPFlag(time_t currTime)
16016 if(!IsPvP())
16017 return;
16018 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16019 return;
16021 UpdatePvP(false);
16024 void Player::UpdateDuelFlag(time_t currTime)
16026 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16027 return;
16029 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16030 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16032 duel->startTimer = 0;
16033 duel->startTime = currTime;
16034 duel->opponent->duel->startTimer = 0;
16035 duel->opponent->duel->startTime = currTime;
16038 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16040 if(!pet)
16041 pet = GetPet();
16043 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16045 //returning of reagents only for players, so best done here
16046 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16047 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16049 if(spellInfo)
16051 for(uint32 i = 0; i < 7; ++i)
16053 if(spellInfo->Reagent[i] > 0)
16055 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16056 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16057 if( msg == EQUIP_ERR_OK )
16059 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16060 if(IsInWorld())
16061 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16066 m_temporaryUnsummonedPetNumber = 0;
16069 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16070 return;
16072 // only if current pet in slot
16073 switch(pet->getPetType())
16075 case MINI_PET:
16076 m_miniPet = 0;
16077 break;
16078 case GUARDIAN_PET:
16079 m_guardianPets.erase(pet->GetGUID());
16080 break;
16081 default:
16082 if(GetPetGUID() == pet->GetGUID())
16083 SetPet(NULL);
16084 break;
16087 pet->CombatStop();
16089 if(returnreagent)
16091 switch(pet->GetEntry())
16093 //warlock pets except imp are removed(?) when logging out
16094 case 1860:
16095 case 1863:
16096 case 417:
16097 case 17252:
16098 mode = PET_SAVE_NOT_IN_SLOT;
16099 break;
16103 pet->SavePetToDB(mode);
16105 pet->CleanupsBeforeDelete();
16106 pet->AddObjectToRemoveList();
16107 pet->m_removed = true;
16109 if(pet->isControlled())
16111 WorldPacket data(SMSG_PET_SPELLS, 8);
16112 data << uint64(0);
16113 GetSession()->SendPacket(&data);
16115 if(GetGroup())
16116 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16120 void Player::RemoveMiniPet()
16122 if(Pet* pet = GetMiniPet())
16124 pet->Remove(PET_SAVE_AS_DELETED);
16125 m_miniPet = 0;
16129 Pet* Player::GetMiniPet()
16131 if(!m_miniPet)
16132 return NULL;
16133 return ObjectAccessor::GetPet(m_miniPet);
16136 void Player::RemoveGuardians()
16138 while(!m_guardianPets.empty())
16140 uint64 guid = *m_guardianPets.begin();
16141 if(Pet* pet = ObjectAccessor::GetPet(guid))
16142 pet->Remove(PET_SAVE_AS_DELETED);
16144 m_guardianPets.erase(guid);
16148 bool Player::HasGuardianWithEntry(uint32 entry)
16150 // pet guid middle part is entry (and creature also)
16151 // and in guardian list must be guardians with same entry _always_
16152 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16154 if(Pet* pet = ObjectAccessor::GetPet(*itr))
16155 if (pet->GetEntry() == entry)
16156 return true;
16159 return false;
16162 void Player::Uncharm()
16164 Unit* charm = GetCharm();
16165 if(!charm)
16166 return;
16168 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16169 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16172 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16174 *data << (uint8)msgtype;
16175 *data << (uint32)language;
16176 *data << (uint64)GetGUID();
16177 *data << (uint32)language; //language 2.1.0 ?
16178 *data << (uint64)GetGUID();
16179 *data << (uint32)(text.length()+1);
16180 *data << text;
16181 *data << (uint8)chatTag();
16184 void Player::Say(const std::string& text, const uint32 language)
16186 WorldPacket data(SMSG_MESSAGECHAT, 200);
16187 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16188 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16191 void Player::Yell(const std::string& text, const uint32 language)
16193 WorldPacket data(SMSG_MESSAGECHAT, 200);
16194 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16195 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16198 void Player::TextEmote(const std::string& text)
16200 WorldPacket data(SMSG_MESSAGECHAT, 200);
16201 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16202 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16205 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16207 if (language != LANG_ADDON) // if not addon data
16208 language = LANG_UNIVERSAL; // whispers should always be readable
16210 Player *rPlayer = objmgr.GetPlayer(receiver);
16212 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16213 if(!rPlayer->isDND() || isGameMaster())
16215 WorldPacket data(SMSG_MESSAGECHAT, 200);
16216 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16217 rPlayer->GetSession()->SendPacket(&data);
16219 data.Initialize(SMSG_MESSAGECHAT, 200);
16220 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16221 GetSession()->SendPacket(&data);
16223 else
16225 // announce to player that player he is whispering to is dnd and cannot receive his message
16226 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16229 if(!isAcceptWhispers())
16231 SetAcceptWhispers(true);
16232 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16235 // announce to player that player he is whispering to is afk
16236 if(rPlayer->isAFK())
16237 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16239 // if player whisper someone, auto turn of dnd to be able to receive an answer
16240 if(isDND() && !rPlayer->isGameMaster())
16241 ToggleDND();
16244 void Player::PetSpellInitialize()
16246 Pet* pet = GetPet();
16248 if(!pet)
16249 return;
16251 sLog.outDebug("Pet Spells Groups");
16253 CharmInfo *charmInfo = pet->GetCharmInfo();
16255 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
16256 data << uint64(pet->GetGUID());
16257 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16258 data << uint32(0);
16259 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16261 // action bar loop
16262 for(uint32 i = 0; i < 10; ++i)
16264 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16267 size_t spellsCountPos = data.wpos();
16269 // spells count
16270 uint8 addlist = 0;
16271 data << uint8(addlist); // placeholder
16273 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16275 // spells loop
16276 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16278 if(itr->second->state == PETSPELL_REMOVED)
16279 continue;
16281 data << uint16(itr->first);
16282 data << uint16(itr->second->active); // pet spell active state isn't boolean
16283 ++addlist;
16287 data.put<uint8>(spellsCountPos, addlist);
16289 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16290 data << uint8(cooldownsCount);
16292 time_t curTime = time(NULL);
16294 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16296 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16298 data << uint32(itr->first); // spellid
16299 data << uint16(0); // spell category?
16300 data << uint32(cooldown); // cooldown
16301 data << uint32(0); // category cooldown
16304 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16306 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16308 data << uint32(itr->first); // spellid
16309 data << uint16(0); // spell category?
16310 data << uint32(0); // cooldown
16311 data << uint32(cooldown); // category cooldown
16314 GetSession()->SendPacket(&data);
16317 void Player::PossessSpellInitialize()
16319 Unit* charm = GetCharm();
16321 if(!charm)
16322 return;
16324 CharmInfo *charmInfo = charm->GetCharmInfo();
16326 if(!charmInfo)
16328 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16329 return;
16332 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
16333 data << uint64(charm->GetGUID());
16334 data << uint16(0);
16335 data << uint32(0);
16336 data << uint32(0);
16338 for(uint32 i = 0; i < 10; ++i)
16340 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16343 data << uint8(0); // spells count
16344 data << uint8(0); // cooldowns count
16346 GetSession()->SendPacket(&data);
16349 void Player::CharmSpellInitialize()
16351 Unit* charm = GetCharm();
16353 if(!charm)
16354 return;
16356 CharmInfo *charmInfo = charm->GetCharmInfo();
16357 if(!charmInfo)
16359 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16360 return;
16363 uint8 addlist = 0;
16365 if(charm->GetTypeId() != TYPEID_PLAYER)
16367 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16369 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16371 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16373 if(charmInfo->GetCharmSpell(i)->spellId)
16374 ++addlist;
16379 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+4*addlist+1);
16380 data << uint64(charm->GetGUID());
16381 data << uint16(0);
16382 data << uint32(0);
16384 if(charm->GetTypeId() != TYPEID_PLAYER)
16385 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16386 else
16387 data << uint8(0) << uint8(0) << uint16(0);
16389 for(uint32 i = 0; i < 10; ++i)
16391 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16394 data << uint8(addlist);
16396 if(addlist)
16398 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16400 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16401 if(cspell->spellId)
16403 data << uint16(cspell->spellId);
16404 data << uint16(cspell->active);
16409 data << uint8(0); // cooldowns count
16411 GetSession()->SendPacket(&data);
16414 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16416 if (!mod || !spellInfo)
16417 return false;
16419 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16421 // prevent apply to any spell except spell that trigger expire
16422 if(spell)
16424 if(mod->lastAffected != spell)
16425 return false;
16427 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16428 return false;
16431 return spellmgr.IsAffectedByMod(spellInfo, mod);
16434 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16436 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16438 for(int eff=0;eff<96;++eff)
16440 uint64 _mask = 0;
16441 uint64 _mask2= 0;
16442 if (eff<64) _mask = uint64(1) << (eff- 0);
16443 else _mask2= uint64(1) << (eff-64);
16444 if ( mod->mask & _mask || mod->mask2 & _mask2)
16446 int32 val = 0;
16447 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16449 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16450 val += (*itr)->value;
16452 val += apply ? mod->value : -(mod->value);
16453 WorldPacket data(Opcode, (1+1+4));
16454 data << uint8(eff);
16455 data << uint8(mod->op);
16456 data << int32(val);
16457 SendDirectMessage(&data);
16461 if (apply)
16462 m_spellMods[mod->op].push_back(mod);
16463 else
16465 if (mod->charges == -1)
16466 --m_SpellModRemoveCount;
16467 m_spellMods[mod->op].remove(mod);
16468 delete mod;
16472 void Player::RemoveSpellMods(Spell const* spell)
16474 if(!spell || (m_SpellModRemoveCount == 0))
16475 return;
16477 for(int i=0;i<MAX_SPELLMOD;++i)
16479 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16481 SpellModifier *mod = *itr;
16482 ++itr;
16484 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16486 RemoveAurasDueToSpell(mod->spellId);
16487 if (m_spellMods[i].empty())
16488 break;
16489 else
16490 itr = m_spellMods[i].begin();
16496 // send Proficiency
16497 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16499 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16500 data << pr1 << pr2;
16501 GetSession()->SendPacket (&data);
16504 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16506 QueryResult *result = NULL;
16507 if(type==10)
16508 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16509 else
16510 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16511 if(result)
16513 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.
16514 { // and SendPetitionQueryOpcode reads data from the DB
16515 Field *fields = result->Fetch();
16516 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16517 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16519 // send update if charter owner in game
16520 Player* owner = objmgr.GetPlayer(ownerguid);
16521 if(owner)
16522 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16524 } while ( result->NextRow() );
16526 delete result;
16528 if(type==10)
16529 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16530 else
16531 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16534 CharacterDatabase.BeginTransaction();
16535 if(type == 10)
16537 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16538 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16540 else
16542 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16543 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16545 CharacterDatabase.CommitTransaction();
16548 void Player::LeaveAllArenaTeams(uint64 guid)
16550 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));
16551 if(!result)
16552 return;
16556 Field *fields = result->Fetch();
16557 uint32 at_id = fields[0].GetUInt32();
16558 if(at_id != 0)
16560 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16561 if(at)
16562 at->DelMember(guid);
16564 } while (result->NextRow());
16566 delete result;
16569 void Player::SetRestBonus (float rest_bonus_new)
16571 // Prevent resting on max level
16572 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16573 rest_bonus_new = 0;
16575 if(rest_bonus_new < 0)
16576 rest_bonus_new = 0;
16578 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16580 if(rest_bonus_new > rest_bonus_max)
16581 m_rest_bonus = rest_bonus_max;
16582 else
16583 m_rest_bonus = rest_bonus_new;
16585 // update data for client
16586 if(m_rest_bonus>10)
16587 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16588 else if(m_rest_bonus<=1)
16589 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16591 //RestTickUpdate
16592 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16595 void Player::HandleStealthedUnitsDetection()
16597 std::list<Unit*> stealthedUnits;
16599 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16600 Cell cell(p);
16601 cell.data.Part.reserved = ALL_DISTRICT;
16602 cell.SetNoCreate();
16604 MaNGOS::AnyStealthedCheck u_check;
16605 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16607 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16608 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16610 CellLock<GridReadGuard> cell_lock(cell, p);
16611 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16612 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16614 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16616 if((*i)==this)
16618 i = stealthedUnits.erase(i);
16619 continue;
16622 if ((*i)->isVisibleForOrDetect(this,true))
16625 (*i)->SendUpdateToPlayer(this);
16626 m_clientGUIDs.insert((*i)->GetGUID());
16628 #ifdef MANGOS_DEBUG
16629 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16630 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16631 #endif
16633 // target aura duration for caster show only if target exist at caster client
16634 // send data at target visibility change (adding to client)
16635 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16636 SendAurasForTarget(*i);
16638 i = stealthedUnits.erase(i);
16639 continue;
16642 ++i;
16646 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16648 if(nodes.size() < 2)
16649 return false;
16651 // not let cheating with start flight mounted
16652 if(IsMounted())
16654 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16655 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16656 GetSession()->SendPacket(&data);
16657 return false;
16660 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16662 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16663 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16664 GetSession()->SendPacket(&data);
16665 return false;
16668 // 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
16669 if(GetSession()->isLogingOut() ||
16670 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16671 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16672 IsNonMeleeSpellCasted(false) ||
16673 isInCombat())
16675 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16676 data << uint32(ERR_TAXIPLAYERBUSY);
16677 GetSession()->SendPacket(&data);
16678 return false;
16681 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16682 return false;
16684 uint32 sourcenode = nodes[0];
16686 // starting node too far away (cheat?)
16687 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16688 if (!node)
16690 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16691 data << uint32(ERR_TAXINOSUCHPATH);
16692 GetSession()->SendPacket(&data);
16693 return false;
16696 // check node starting pos data set case if provided
16697 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16699 if (node->map_id != GetMapId() ||
16700 (node->x - GetPositionX())*(node->x - GetPositionX())+
16701 (node->y - GetPositionY())*(node->y - GetPositionY())+
16702 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16703 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16705 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16706 data << uint32(ERR_TAXITOOFARAWAY);
16707 GetSession()->SendPacket(&data);
16708 return false;
16711 // node must have pos if not spell case (npc!=0)
16712 else if(npc)
16714 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16715 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16716 GetSession()->SendPacket(&data);
16717 return false;
16720 // Prepare to flight start now
16722 // stop combat at start taxi flight if any
16723 CombatStop();
16725 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16726 TradeCancel(true);
16728 // clean not finished taxi path if any
16729 m_taxi.ClearTaxiDestinations();
16731 // 0 element current node
16732 m_taxi.AddTaxiDestination(sourcenode);
16734 // fill destinations path tail
16735 uint32 sourcepath = 0;
16736 uint32 totalcost = 0;
16738 uint32 prevnode = sourcenode;
16739 uint32 lastnode = 0;
16741 for(uint32 i = 1; i < nodes.size(); ++i)
16743 uint32 path, cost;
16745 lastnode = nodes[i];
16746 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16748 if(!path)
16750 m_taxi.ClearTaxiDestinations();
16751 return false;
16754 totalcost += cost;
16756 if(prevnode == sourcenode)
16757 sourcepath = path;
16759 m_taxi.AddTaxiDestination(lastnode);
16761 prevnode = lastnode;
16764 if(!mount_id) // if not provide then attempt use default.
16765 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16767 if (mount_id == 0 || sourcepath == 0)
16769 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16770 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16771 GetSession()->SendPacket(&data);
16772 m_taxi.ClearTaxiDestinations();
16773 return false;
16776 uint32 money = GetMoney();
16778 if (npc)
16779 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16781 if(money < totalcost)
16783 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16784 data << uint32(ERR_TAXINOTENOUGHMONEY);
16785 GetSession()->SendPacket(&data);
16786 m_taxi.ClearTaxiDestinations();
16787 return false;
16790 //Checks and preparations done, DO FLIGHT
16791 ModifyMoney(-(int32)totalcost);
16792 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16793 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16795 // prevent stealth flight
16796 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16798 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16799 data << uint32(ERR_TAXIOK);
16800 GetSession()->SendPacket(&data);
16802 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16804 GetSession()->SendDoFlight(mount_id, sourcepath);
16806 return true;
16809 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16811 // last check 2.0.10
16812 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16813 data << GetGUID();
16814 data << uint8(0x0); // flags (0x1, 0x2)
16815 time_t curTime = time(NULL);
16816 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16818 if (itr->second->state == PLAYERSPELL_REMOVED)
16819 continue;
16820 uint32 unSpellId = itr->first;
16821 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16822 if (!spellInfo)
16824 ASSERT(spellInfo);
16825 continue;
16828 // Not send cooldown for this spells
16829 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16830 continue;
16832 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16834 data << unSpellId;
16835 data << unTimeMs; // in m.secs
16836 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
16839 GetSession()->SendPacket(&data);
16842 void Player::InitDataForForm(bool reapplyMods)
16844 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16845 if(ssEntry && ssEntry->attackSpeed)
16847 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16848 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16849 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16851 else
16852 SetRegularAttackTime();
16854 switch(m_form)
16856 case FORM_CAT:
16858 if(getPowerType()!=POWER_ENERGY)
16859 setPowerType(POWER_ENERGY);
16860 break;
16862 case FORM_BEAR:
16863 case FORM_DIREBEAR:
16865 if(getPowerType()!=POWER_RAGE)
16866 setPowerType(POWER_RAGE);
16867 break;
16869 default: // 0, for example
16871 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16872 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16873 setPowerType(Powers(cEntry->powerType));
16874 break;
16878 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16879 if (!reapplyMods)
16880 UpdateEquipSpellsAtFormChange();
16882 UpdateAttackPowerAndDamage();
16883 UpdateAttackPowerAndDamage(true);
16886 // Return true is the bought item has a max count to force refresh of window by caller
16887 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16889 // cheating attempt
16890 if(count < 1) count = 1;
16892 if(!isAlive())
16893 return false;
16895 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16896 if( !pProto )
16898 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16899 return false;
16902 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
16903 if (!pCreature)
16905 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16906 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16907 return false;
16910 VendorItemData const* vItems = pCreature->GetVendorItems();
16911 if(!vItems || vItems->Empty())
16913 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16914 return false;
16917 size_t vendor_slot = vItems->FindItemSlot(item);
16918 if(vendor_slot >= vItems->GetItemCount())
16920 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16921 return false;
16924 VendorItem const* crItem = vItems->m_items[vendor_slot];
16926 // check current item amount if it limited
16927 if( crItem->maxcount != 0 )
16929 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16931 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16932 return false;
16936 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16938 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16939 return false;
16942 if(crItem->ExtendedCost)
16944 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16945 if(!iece)
16947 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16948 return false;
16951 // honor points price
16952 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16954 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16955 return false;
16958 // arena points price
16959 if(GetArenaPoints() < (iece->reqarenapoints * count))
16961 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16962 return false;
16965 // item base price
16966 for (uint8 i = 0; i < 5; ++i)
16968 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16970 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16971 return false;
16975 // check for personal arena rating requirement
16976 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16978 // probably not the proper equip err
16979 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16980 return false;
16984 uint32 price = pProto->BuyPrice * count;
16986 // reputation discount
16987 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16989 if( GetMoney() < price )
16991 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16992 return false;
16995 uint8 bag = 0; // init for case invalid bagGUID
16997 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16999 Bag *pBag;
17000 if( bagguid == GetGUID() )
17002 bag = INVENTORY_SLOT_BAG_0;
17004 else
17006 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17008 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17009 if( pBag )
17011 if( bagguid == pBag->GetGUID() )
17013 bag = i;
17014 break;
17021 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17023 ItemPosCountVec dest;
17024 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17025 if( msg != EQUIP_ERR_OK )
17027 SendEquipError( msg, NULL, NULL );
17028 return false;
17031 ModifyMoney( -(int32)price );
17032 if(crItem->ExtendedCost) // case for new honor system
17034 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17035 if(iece->reqhonorpoints)
17036 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17037 if(iece->reqarenapoints)
17038 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17039 for (uint8 i = 0; i < 5; ++i)
17041 if(iece->reqitem[i])
17042 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17046 if(Item *it = StoreNewItem( dest, item, true ))
17048 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17050 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17051 data << pCreature->GetGUID();
17052 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17053 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17054 data << (uint32)count;
17055 GetSession()->SendPacket(&data);
17057 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17060 else if( IsEquipmentPos( bag, slot ) )
17062 if(pProto->BuyCount * count != 1)
17064 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17065 return false;
17068 uint16 dest;
17069 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17070 if( msg != EQUIP_ERR_OK )
17072 SendEquipError( msg, NULL, NULL );
17073 return false;
17076 ModifyMoney( -(int32)price );
17077 if(crItem->ExtendedCost) // case for new honor system
17079 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17080 if(iece->reqhonorpoints)
17081 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17082 if(iece->reqarenapoints)
17083 ModifyArenaPoints( - int32(iece->reqarenapoints));
17084 for (uint8 i = 0; i < 5; ++i)
17086 if(iece->reqitem[i])
17087 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17091 if(Item *it = EquipNewItem( dest, item, true ))
17093 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17095 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17096 data << pCreature->GetGUID();
17097 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17098 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17099 data << (uint32)count;
17100 GetSession()->SendPacket(&data);
17102 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17104 AutoUnequipOffhandIfNeed();
17107 else
17109 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17110 return false;
17113 return crItem->maxcount!=0;
17116 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17118 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17119 // the personal rating of the arena team must match the required limit as well
17120 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17121 uint32 max_personal_rating = 0;
17122 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17124 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17126 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17127 uint32 t_rating = at->GetRating();
17128 p_rating = p_rating<t_rating? p_rating : t_rating;
17129 if(max_personal_rating < p_rating)
17130 max_personal_rating = p_rating;
17133 return max_personal_rating;
17136 void Player::UpdateHomebindTime(uint32 time)
17138 // GMs never get homebind timer online
17139 if (m_InstanceValid || isGameMaster())
17141 if(m_HomebindTimer) // instance valid, but timer not reset
17143 // hide reminder
17144 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17145 data << uint32(0);
17146 data << uint32(0);
17147 GetSession()->SendPacket(&data);
17149 // instance is valid, reset homebind timer
17150 m_HomebindTimer = 0;
17152 else if (m_HomebindTimer > 0)
17154 if (time >= m_HomebindTimer)
17156 // teleport to nearest graveyard
17157 RepopAtGraveyard();
17159 else
17160 m_HomebindTimer -= time;
17162 else
17164 // instance is invalid, start homebind timer
17165 m_HomebindTimer = 60000;
17166 // send message to player
17167 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17168 data << m_HomebindTimer;
17169 data << uint32(1);
17170 GetSession()->SendPacket(&data);
17171 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17175 void Player::UpdatePvP(bool state, bool ovrride)
17177 if(!state || ovrride)
17179 SetPvP(state);
17180 if(Pet* pet = GetPet())
17181 pet->SetPvP(state);
17182 if(Unit* charmed = GetCharm())
17183 charmed->SetPvP(state);
17185 pvpInfo.endTimer = 0;
17187 else
17189 if(pvpInfo.endTimer != 0)
17190 pvpInfo.endTimer = time(NULL);
17191 else
17193 SetPvP(state);
17195 if(Pet* pet = GetPet())
17196 pet->SetPvP(state);
17197 if(Unit* charmed = GetCharm())
17198 charmed->SetPvP(state);
17203 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17205 // init cooldown values
17206 uint32 cat = 0;
17207 int32 rec = -1;
17208 int32 catrec = -1;
17210 // some special item spells without correct cooldown in SpellInfo
17211 // cooldown information stored in item prototype
17212 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17214 if(itemId)
17216 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17218 for(int idx = 0; idx < 5; ++idx)
17220 if(proto->Spells[idx].SpellId == spellInfo->Id)
17222 cat = proto->Spells[idx].SpellCategory;
17223 rec = proto->Spells[idx].SpellCooldown;
17224 catrec = proto->Spells[idx].SpellCategoryCooldown;
17225 break;
17231 // if no cooldown found above then base at DBC data
17232 if(rec < 0 && catrec < 0)
17234 cat = spellInfo->Category;
17235 rec = spellInfo->RecoveryTime;
17236 catrec = spellInfo->CategoryRecoveryTime;
17239 time_t curTime = time(NULL);
17241 time_t catrecTime;
17242 time_t recTime;
17244 // overwrite time for selected category
17245 if(infinityCooldown)
17247 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17248 // but not allow ignore until reset or re-login
17249 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17250 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17252 else
17254 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17255 // prevent 0 cooldowns set by another way
17256 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17257 rec = GetAttackTime(RANGED_ATTACK);
17259 // Now we have cooldown data (if found any), time to apply mods
17260 if(rec > 0)
17261 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17263 if(catrec > 0)
17264 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17266 // replace negative cooldowns by 0
17267 if (rec < 0) rec = 0;
17268 if (catrec < 0) catrec = 0;
17270 // no cooldown after applying spell mods
17271 if( rec == 0 && catrec == 0)
17272 return;
17274 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17275 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17278 // self spell cooldown
17279 if(recTime > 0)
17280 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17282 // category spells
17283 if (cat && catrec > 0)
17285 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17286 if(i_scstore != sSpellCategoryStore.end())
17288 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17290 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17291 continue;
17293 AddSpellCooldown(*i_scset, itemId, catrecTime);
17299 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17301 SpellCooldown sc;
17302 sc.end = end_time;
17303 sc.itemid = itemid;
17304 m_spellCooldowns[spellid] = sc;
17307 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17309 // start cooldowns at server side, if any
17310 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17312 // Send activate cooldown timer (possible 0) at client side
17313 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17314 data << spellInfo->Id;
17315 data << GetGUID();
17316 SendDirectMessage(&data);
17319 void Player::UpdatePotionCooldown(Spell* spell)
17321 // no potion used i combat or still in combat
17322 if(!m_lastPotionId || isInCombat())
17323 return;
17325 // Call not from spell cast, send cooldown event for item spells if no in combat
17326 if(!spell)
17328 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17329 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17330 for(int idx = 0; idx < 5; ++idx)
17331 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17332 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17333 SendCooldownEvent(spellInfo,m_lastPotionId);
17335 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17336 else
17337 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17339 m_lastPotionId = 0;
17342 //slot to be excluded while counting
17343 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17345 if(!enchantmentcondition)
17346 return true;
17348 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17350 if(!Condition)
17351 return true;
17353 uint8 curcount[4] = {0, 0, 0, 0};
17355 //counting current equipped gem colors
17356 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17358 if(i == slot)
17359 continue;
17360 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17361 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17363 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17365 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17366 if(!enchant_id)
17367 continue;
17369 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17370 if(!enchantEntry)
17371 continue;
17373 uint32 gemid = enchantEntry->GemID;
17374 if(!gemid)
17375 continue;
17377 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17378 if(!gemProto)
17379 continue;
17381 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17382 if(!gemProperty)
17383 continue;
17385 uint8 GemColor = gemProperty->color;
17387 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17389 if(tmpcolormask & GemColor)
17390 ++curcount[b];
17396 bool activate = true;
17398 for(int i = 0; i < 5; ++i)
17400 if(!Condition->Color[i])
17401 continue;
17403 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17405 // if have <CompareColor> use them as count, else use <value> from Condition
17406 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17408 switch(Condition->Comparator[i])
17410 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17411 activate &= (_cur_gem < _cmp_gem) ? true : false;
17412 break;
17413 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17414 activate &= (_cur_gem > _cmp_gem) ? true : false;
17415 break;
17416 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17417 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17418 break;
17422 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");
17424 return activate;
17427 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17429 //cycle all equipped items
17430 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17432 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17433 if(slot == exceptslot)
17434 continue;
17436 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17438 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17439 continue;
17441 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17443 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17444 if(!enchant_id)
17445 continue;
17447 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17448 if(!enchantEntry)
17449 continue;
17451 uint32 condition = enchantEntry->EnchantmentCondition;
17452 if(condition)
17454 //was enchant active with/without item?
17455 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17456 //should it now be?
17457 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17459 // ignore item gem conditions
17460 //if state changed, (dis)apply enchant
17461 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17468 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17469 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17471 //cycle all equipped items
17472 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17474 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17475 if(slot == exceptslot)
17476 continue;
17478 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17480 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17481 continue;
17483 //cycle all (gem)enchants
17484 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17486 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17487 if(!enchant_id) //if no enchant go to next enchant(slot)
17488 continue;
17490 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17491 if(!enchantEntry)
17492 continue;
17494 //only metagems to be (de)activated, so only enchants with condition
17495 uint32 condition = enchantEntry->EnchantmentCondition;
17496 if(condition)
17497 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17502 void Player::LeaveBattleground(bool teleportToEntryPoint)
17504 if(BattleGround *bg = GetBattleGround())
17506 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17508 // call after remove to be sure that player resurrected for correct cast
17509 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17511 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17512 CastSpell(this, 26013, true); // Deserter
17517 bool Player::CanJoinToBattleground() const
17519 // check Deserter debuff
17520 if(GetDummyAura(26013))
17521 return false;
17523 return true;
17526 bool Player::CanReportAfkDueToLimit()
17528 // a player can complain about 15 people per 5 minutes
17529 if(m_bgAfkReportedCount >= 15)
17530 return false;
17531 ++m_bgAfkReportedCount;
17532 return true;
17535 ///This player has been blamed to be inactive in a battleground
17536 void Player::ReportedAfkBy(Player* reporter)
17538 BattleGround *bg = GetBattleGround();
17539 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17540 return;
17542 // check if player has 'Idle' or 'Inactive' debuff
17543 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17545 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17546 // 3 players have to complain to apply debuff
17547 if(m_bgAfkReporter.size() >= 3)
17549 // cast 'Idle' spell
17550 CastSpell(this, 43680, true);
17551 m_bgAfkReporter.clear();
17556 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17558 // gamemaster in GM mode see all, including ghosts
17559 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17560 return true;
17562 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17563 if (InBattleGround())
17565 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17566 return false;
17567 return true;
17570 // Live player see live player or dead player with not realized corpse
17571 if(pl->isAlive() || pl->m_deathTimer > 0)
17573 return isAlive() || m_deathTimer > 0;
17576 // Ghost see other friendly ghosts, that's for sure
17577 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17578 return true;
17580 // Dead player see live players near own corpse
17581 if(isAlive())
17583 Corpse *corpse = pl->GetCorpse();
17584 if(corpse)
17586 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17587 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17588 return true;
17592 // and not see any other
17593 return false;
17596 bool Player::IsVisibleGloballyFor( Player* u ) const
17598 if(!u)
17599 return false;
17601 // Always can see self
17602 if (u==this)
17603 return true;
17605 // Visible units, always are visible for all players
17606 if (GetVisibility() == VISIBILITY_ON)
17607 return true;
17609 // GMs are visible for higher gms (or players are visible for gms)
17610 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17611 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17613 // non faction visibility non-breakable for non-GMs
17614 if (GetVisibility() == VISIBILITY_OFF)
17615 return false;
17617 // non-gm stealth/invisibility not hide from global player lists
17618 return true;
17621 void Player::UpdateVisibilityOf(WorldObject* target)
17623 if(HaveAtClient(target))
17625 if(!target->isVisibleForInState(this,true))
17627 target->DestroyForPlayer(this);
17628 m_clientGUIDs.erase(target->GetGUID());
17630 #ifdef MANGOS_DEBUG
17631 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17632 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17633 #endif
17636 else
17638 if(target->isVisibleForInState(this,false))
17640 target->SendUpdateToPlayer(this);
17641 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17642 m_clientGUIDs.insert(target->GetGUID());
17644 #ifdef MANGOS_DEBUG
17645 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17646 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17647 #endif
17649 // target aura duration for caster show only if target exist at caster client
17650 // send data at target visibility change (adding to client)
17651 if(target!=this && target->isType(TYPEMASK_UNIT))
17652 SendAurasForTarget((Unit*)target);
17654 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17655 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17660 template<class T>
17661 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17663 s64.insert(target->GetGUID());
17666 template<>
17667 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17669 if(!target->IsTransport())
17670 s64.insert(target->GetGUID());
17673 template<class T>
17674 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17676 if(HaveAtClient(target))
17678 if(!target->isVisibleForInState(this,true))
17680 target->BuildOutOfRangeUpdateBlock(&data);
17681 m_clientGUIDs.erase(target->GetGUID());
17683 #ifdef MANGOS_DEBUG
17684 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17685 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));
17686 #endif
17689 else
17691 if(target->isVisibleForInState(this,false))
17693 visibleNow.insert(target);
17694 target->BuildUpdate(data_updates);
17695 target->BuildCreateUpdateBlockForPlayer(&data, this);
17696 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17698 #ifdef MANGOS_DEBUG
17699 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17700 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));
17701 #endif
17706 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17707 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17708 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17709 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17710 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17712 void Player::InitPrimaryProffesions()
17714 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17717 void Player::SendComboPoints()
17719 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17720 if (combotarget)
17722 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17723 data.append(combotarget->GetPackGUID());
17724 data << uint8(m_comboPoints);
17725 GetSession()->SendPacket(&data);
17729 void Player::AddComboPoints(Unit* target, int8 count)
17731 if(!count)
17732 return;
17734 // without combo points lost (duration checked in aura)
17735 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17737 if(target->GetGUID() == m_comboTarget)
17739 m_comboPoints += count;
17741 else
17743 if(m_comboTarget)
17744 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17745 target2->RemoveComboPointHolder(GetGUIDLow());
17747 m_comboTarget = target->GetGUID();
17748 m_comboPoints = count;
17750 target->AddComboPointHolder(GetGUIDLow());
17753 if (m_comboPoints > 5) m_comboPoints = 5;
17754 if (m_comboPoints < 0) m_comboPoints = 0;
17756 SendComboPoints();
17759 void Player::ClearComboPoints()
17761 if(!m_comboTarget)
17762 return;
17764 // without combopoints lost (duration checked in aura)
17765 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17767 m_comboPoints = 0;
17769 SendComboPoints();
17771 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17772 target->RemoveComboPointHolder(GetGUIDLow());
17774 m_comboTarget = 0;
17777 void Player::SetGroup(Group *group, int8 subgroup)
17779 if(group == NULL)
17780 m_group.unlink();
17781 else
17783 // never use SetGroup without a subgroup unless you specify NULL for group
17784 assert(subgroup >= 0);
17785 m_group.link(group, this);
17786 m_group.setSubGroup((uint8)subgroup);
17790 void Player::SendInitialPacketsBeforeAddToMap()
17792 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17793 data << uint32(0); // unknown, may be rest state time or experience
17794 GetSession()->SendPacket(&data);
17796 GetSocial()->SendSocialList();
17798 // Homebind
17799 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17800 data << m_homebindX << m_homebindY << m_homebindZ;
17801 data << (uint32) m_homebindMapId;
17802 data << (uint32) m_homebindZoneId;
17803 GetSession()->SendPacket(&data);
17805 // SMSG_SET_PROFICIENCY
17806 // SMSG_UPDATE_AURA_DURATION
17808 SendTalentsInfoData(false);
17809 SendInitialSpells();
17811 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17812 data << uint32(0); // count, for(count) uint32;
17813 GetSession()->SendPacket(&data);
17815 SendInitialActionButtons();
17816 m_reputationMgr.SendInitialReputations();
17817 m_achievementMgr.SendAllAchievementData();
17819 // update zone
17820 uint32 newzone, newarea;
17821 GetZoneAndAreaId(newzone,newarea);
17822 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17824 SendEquipmentSetList();
17826 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17827 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17828 data << (float)0.01666667f; // game speed
17829 data << uint32(0); // added in 3.1.2
17830 GetSession()->SendPacket( &data );
17832 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17833 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17834 m_movementInfo.flags |= MOVEMENTFLAG_FLYING2;
17836 m_mover = this;
17839 void Player::SendInitialPacketsAfterAddToMap()
17841 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17842 data << uint32(0x00000000); // on blizz it increments periodically
17843 GetSession()->SendPacket(&data);
17845 CastSpell(this, 836, true); // LOGINEFFECT
17847 // set some aura effects that send packet to player client after add player to map
17848 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17849 // same auras state lost at far teleport, send it one more time in this case also
17850 static const AuraType auratypes[] =
17852 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17853 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17854 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17856 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17858 Unit::AuraList const& auraList = GetAurasByType(*itr);
17859 if(!auraList.empty())
17860 auraList.front()->ApplyModifier(true,true);
17863 if(HasAuraType(SPELL_AURA_MOD_STUN))
17864 SetMovement(MOVE_ROOT);
17866 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17867 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17869 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
17870 data2.append(GetPackGUID());
17871 data2 << (uint32)2;
17872 SendMessageToSet(&data2,true);
17875 SendAurasForTarget(this);
17876 SendEnchantmentDurations(); // must be after add to map
17877 SendItemDurations(); // must be after add to map
17880 void Player::SendUpdateToOutOfRangeGroupMembers()
17882 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17883 return;
17884 if(Group* group = GetGroup())
17885 group->UpdatePlayerOutOfRange(this);
17887 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17888 m_auraUpdateMask = 0;
17889 if(Pet *pet = GetPet())
17890 pet->ResetAuraUpdateMask();
17893 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17895 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17896 data << uint32(mapid);
17897 data << uint8(reason); // transfer abort reason
17898 switch(reason)
17900 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17901 case TRANSFER_ABORT_DIFFICULTY:
17902 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17903 data << uint8(arg);
17904 break;
17906 GetSession()->SendPacket(&data);
17909 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17911 // type of warning, based on the time remaining until reset
17912 uint32 type;
17913 if(time > 3600)
17914 type = RAID_INSTANCE_WELCOME;
17915 else if(time > 900 && time <= 3600)
17916 type = RAID_INSTANCE_WARNING_HOURS;
17917 else if(time > 300 && time <= 900)
17918 type = RAID_INSTANCE_WARNING_MIN;
17919 else
17920 type = RAID_INSTANCE_WARNING_MIN_SOON;
17921 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17922 data << uint32(type);
17923 data << uint32(mapid);
17924 data << uint32(time);
17925 GetSession()->SendPacket(&data);
17928 void Player::ApplyEquipCooldown( Item * pItem )
17930 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
17932 _Spell const& spellData = pItem->GetProto()->Spells[i];
17934 // no spell
17935 if( !spellData.SpellId )
17936 continue;
17938 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17939 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17940 continue;
17942 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17944 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17945 data << pItem->GetGUID();
17946 data << uint32(spellData.SpellId);
17947 GetSession()->SendPacket(&data);
17951 void Player::resetSpells()
17953 // not need after this call
17954 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17956 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17957 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17960 // make full copy of map (spells removed and marked as deleted at another spell remove
17961 // and we can't use original map for safe iterative with visit each spell at loop end
17962 PlayerSpellMap smap = GetSpellMap();
17964 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17965 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17967 learnDefaultSpells();
17968 learnQuestRewardedSpells();
17971 void Player::learnDefaultSpells()
17973 // learn default race/class spells
17974 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17975 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
17977 uint32 tspell = *itr;
17978 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
17979 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
17980 addSpell(tspell,true,true,true,false);
17981 else // but send in normal spell in game learn case
17982 learnSpell(tspell,true);
17986 void Player::learnQuestRewardedSpells(Quest const* quest)
17988 uint32 spell_id = quest->GetRewSpellCast();
17990 // skip quests without rewarded spell
17991 if( !spell_id )
17992 return;
17994 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17995 if(!spellInfo)
17996 return;
17998 // check learned spells state
17999 bool found = false;
18000 for(int i=0; i < 3; ++i)
18002 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18004 found = true;
18005 break;
18009 // skip quests with not teaching spell or already known spell
18010 if(!found)
18011 return;
18013 // prevent learn non first rank unknown profession and second specialization for same profession)
18014 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18015 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18017 // not have first rank learned (unlearned prof?)
18018 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18019 if( !HasSpell(first_spell) )
18020 return;
18022 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18023 if(!learnedInfo)
18024 return;
18026 // specialization
18027 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18029 // search other specialization for same prof
18030 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18032 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18033 continue;
18035 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18036 if(!itrInfo)
18037 return;
18039 // compare only specializations
18040 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18041 continue;
18043 // compare same chain spells
18044 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18045 continue;
18047 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18048 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18049 return;
18054 CastSpell( this, spell_id, true);
18057 void Player::learnQuestRewardedSpells()
18059 // learn spells received from quest completing
18060 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18062 // skip no rewarded quests
18063 if(!itr->second.m_rewarded)
18064 continue;
18066 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18067 if( !quest )
18068 continue;
18070 learnQuestRewardedSpells(quest);
18074 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18076 uint32 raceMask = getRaceMask();
18077 uint32 classMask = getClassMask();
18078 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18080 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18081 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18082 continue;
18083 // Check race if set
18084 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18085 continue;
18086 // Check class if set
18087 if (pAbility->classmask && !(pAbility->classmask & classMask))
18088 continue;
18090 if (sSpellStore.LookupEntry(pAbility->spellId))
18092 // need unlearn spell
18093 if (skill_value < pAbility->req_skill_value)
18094 removeSpell(pAbility->spellId);
18095 // need learn
18096 else if (!IsInWorld())
18097 addSpell(pAbility->spellId,true,true,true,false);
18098 else
18099 learnSpell(pAbility->spellId,true);
18104 void Player::SendAurasForTarget(Unit *target)
18106 if(target->GetVisibleAuras()->empty()) // speedup things
18107 return;
18109 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18110 data.append(target->GetPackGUID());
18112 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18113 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18115 for(uint32 j = 0; j < 3; ++j)
18117 if(Aura *aura = target->GetAura(itr->second, j))
18119 data << uint8(aura->GetAuraSlot());
18120 data << uint32(aura->GetId());
18122 if(aura->GetId())
18124 uint8 auraFlags = aura->GetAuraFlags();
18125 // flags
18126 data << uint8(auraFlags);
18127 // level
18128 data << uint8(aura->GetAuraLevel());
18129 // charges
18130 data << uint8(aura->GetAuraCharges());
18132 if(!(auraFlags & AFLAG_NOT_CASTER))
18134 data << uint8(0); // packed GUID of someone (caster?)
18137 if(auraFlags & AFLAG_DURATION) // include aura duration
18139 data << uint32(aura->GetAuraMaxDuration());
18140 data << uint32(aura->GetAuraDuration());
18143 break;
18148 GetSession()->SendPacket(&data);
18151 void Player::SetDailyQuestStatus( uint32 quest_id )
18153 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18155 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18157 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18158 m_lastDailyQuestTime = time(NULL); // last daily quest time
18159 m_DailyQuestChanged = true;
18160 break;
18165 void Player::ResetDailyQuestStatus()
18167 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18168 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18170 // DB data deleted in caller
18171 m_DailyQuestChanged = false;
18172 m_lastDailyQuestTime = 0;
18175 BattleGround* Player::GetBattleGround() const
18177 if(GetBattleGroundId()==0)
18178 return NULL;
18180 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18183 bool Player::InArena() const
18185 BattleGround *bg = GetBattleGround();
18186 if(!bg || !bg->isArena())
18187 return false;
18189 return true;
18192 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18194 // get a template bg instead of running one
18195 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18196 if(!bg)
18197 return false;
18199 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18200 return false;
18202 return true;
18205 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18207 //returned to hardcoded version of this function, because there is no way to code it dynamic
18208 uint32 level = getLevel();
18209 if( bgTypeId == BATTLEGROUND_AV )
18210 level--;
18212 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18213 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18215 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18216 return QUEUE_ID_MAX_LEVEL_80;
18218 return BGQueueIdBasedOnLevel(queue_id);
18221 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18223 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18224 if(!vendor_faction || !vendor_faction->faction)
18225 return 1.0f;
18227 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18228 if(rank <= REP_NEUTRAL)
18229 return 1.0f;
18231 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18234 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18236 uint32 racemask = getRaceMask();
18237 uint32 classmask = getClassMask();
18239 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18240 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18241 if(lower==upper)
18242 return true;
18244 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18246 // skip wrong race skills
18247 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18248 continue;
18250 // skip wrong class skills
18251 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18252 continue;
18254 return true;
18257 return false;
18260 bool Player::HasQuestForGO(int32 GOId) const
18262 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18264 uint32 questid = GetQuestSlotQuestId(i);
18265 if ( questid == 0 )
18266 continue;
18268 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18269 if(qs_itr == mQuestStatus.end())
18270 continue;
18272 QuestStatusData const& qs = qs_itr->second;
18274 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18276 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18277 if(!qinfo)
18278 continue;
18280 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18281 continue;
18283 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18285 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18286 continue;
18288 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18289 return true;
18293 return false;
18296 void Player::UpdateForQuestWorldObjects()
18298 if(m_clientGUIDs.empty())
18299 return;
18301 UpdateData udata;
18302 WorldPacket packet;
18303 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18305 if(IS_GAMEOBJECT_GUID(*itr))
18307 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18308 if(obj)
18309 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18311 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18313 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18314 if(!obj)
18315 continue;
18316 // check if this unit requires quest specific flags
18318 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
18319 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(obj->GetEntry()); itr != map.upper_bound(obj->GetEntry()); ++itr)
18321 if(itr->second.questId != 0)
18323 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18324 break;
18330 udata.BuildPacket(&packet);
18331 GetSession()->SendPacket(&packet);
18334 void Player::SummonIfPossible(bool agree)
18336 if(!agree)
18338 m_summon_expire = 0;
18339 return;
18342 // expire and auto declined
18343 if(m_summon_expire < time(NULL))
18344 return;
18346 // stop taxi flight at summon
18347 if(isInFlight())
18349 GetMotionMaster()->MovementExpired();
18350 m_taxi.ClearTaxiDestinations();
18353 // drop flag at summon
18354 // 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
18355 if(BattleGround *bg = GetBattleGround())
18356 bg->EventPlayerDroppedFlag(this);
18358 m_summon_expire = 0;
18360 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18362 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18365 void Player::RemoveItemDurations( Item *item )
18367 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18369 if(*itr==item)
18371 m_itemDuration.erase(itr);
18372 break;
18377 void Player::AddItemDurations( Item *item )
18379 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18381 m_itemDuration.push_back(item);
18382 item->SendTimeUpdate(this);
18386 void Player::AutoUnequipOffhandIfNeed()
18388 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18389 if(!offItem)
18390 return;
18392 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18393 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18394 return;
18396 ItemPosCountVec off_dest;
18397 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18398 if( off_msg == EQUIP_ERR_OK )
18400 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18401 StoreItem( off_dest, offItem, true );
18403 else
18405 MailItemsInfo mi;
18406 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18407 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18408 CharacterDatabase.BeginTransaction();
18409 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18410 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18411 CharacterDatabase.CommitTransaction();
18413 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18414 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18418 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18420 if(spellInfo->EquippedItemClass < 0)
18421 return true;
18423 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18424 // for optimize check 2 used cases only
18425 switch(spellInfo->EquippedItemClass)
18427 case ITEM_CLASS_WEAPON:
18429 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18430 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18431 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18432 return true;
18433 break;
18435 case ITEM_CLASS_ARMOR:
18437 // tabard not have dependent spells
18438 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18439 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18440 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18441 return true;
18443 // shields can be equipped to offhand slot
18444 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18445 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18446 return true;
18448 // ranged slot can have some armor subclasses
18449 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18450 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18451 return true;
18453 break;
18455 default:
18456 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18457 break;
18460 return false;
18463 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18465 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18466 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18467 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18468 return true;
18470 // Check no reagent use mask
18471 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18472 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18473 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18474 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18475 return true;
18477 return false;
18480 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18482 AuraMap& auras = GetAuras();
18483 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18485 Aura* aura = itr->second;
18487 // skip passive (passive item dependent spells work in another way) and not self applied auras
18488 SpellEntry const* spellInfo = aura->GetSpellProto();
18489 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18491 ++itr;
18492 continue;
18495 // skip if not item dependent or have alternative item
18496 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18498 ++itr;
18499 continue;
18502 // no alt item, remove aura, restart check
18503 RemoveAurasDueToSpell(aura->GetId());
18504 itr = auras.begin();
18507 // currently casted spells can be dependent from item
18508 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18510 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18511 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18512 InterruptSpell(i);
18516 uint32 Player::GetResurrectionSpellId()
18518 // search priceless resurrection possibilities
18519 uint32 prio = 0;
18520 uint32 spell_id = 0;
18521 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18522 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18524 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18525 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18527 switch((*itr)->GetId())
18529 case 20707: spell_id = 3026; break; // rank 1
18530 case 20762: spell_id = 20758; break; // rank 2
18531 case 20763: spell_id = 20759; break; // rank 3
18532 case 20764: spell_id = 20760; break; // rank 4
18533 case 20765: spell_id = 20761; break; // rank 5
18534 case 27239: spell_id = 27240; break; // rank 6
18535 case 47883: spell_id = 47882; break; // rank 7
18536 default:
18537 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18538 continue;
18541 prio = 3;
18543 // Twisting Nether // prio: 2 (max)
18544 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18546 prio = 2;
18547 spell_id = 23700;
18551 // Reincarnation (passive spell) // prio: 1
18552 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18553 spell_id = 21169;
18555 return spell_id;
18558 // Used in triggers for check "Only to targets that grant experience or honor" req
18559 bool Player::isHonorOrXPTarget(Unit* pVictim)
18561 uint32 v_level = pVictim->getLevel();
18562 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18564 // Victim level less gray level
18565 if(v_level<=k_grey)
18566 return false;
18568 if(pVictim->GetTypeId() == TYPEID_UNIT)
18570 if (((Creature*)pVictim)->isTotem() ||
18571 ((Creature*)pVictim)->isPet() ||
18572 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18573 return false;
18575 return true;
18578 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18580 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18582 // prepare data for near group iteration (PvP and !PvP cases)
18583 uint32 xp = 0;
18584 bool honored_kill = false;
18586 if(Group *pGroup = GetGroup())
18588 uint32 count = 0;
18589 uint32 sum_level = 0;
18590 Player* member_with_max_level = NULL;
18591 Player* not_gray_member_with_max_level = NULL;
18593 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18595 if(member_with_max_level)
18597 /// not get Xp in PvP or no not gray players in group
18598 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18600 /// skip in check PvP case (for speed, not used)
18601 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18602 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18603 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18605 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18607 Player* pGroupGuy = itr->getSource();
18608 if(!pGroupGuy)
18609 continue;
18611 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18612 continue; // member (alive or dead) or his corpse at req. distance
18614 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18615 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18616 honored_kill = true;
18618 // xp and reputation only in !PvP case
18619 if(!PvP)
18621 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18623 // if is in dungeon then all receive full reputation at kill
18624 // rewarded any alive/dead/near_corpse group member
18625 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18627 // XP updated only for alive group member
18628 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18629 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18631 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18633 pGroupGuy->GiveXP(itr_xp, pVictim);
18634 if(Pet* pet = pGroupGuy->GetPet())
18635 pet->GivePetXP(itr_xp/2);
18638 // quest objectives updated only for alive group member or dead but with not released body
18639 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18641 // normal creature (not pet/etc) can be only in !PvP case
18642 if(pVictim->GetTypeId()==TYPEID_UNIT)
18643 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18649 else // if (!pGroup)
18651 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18653 // honor can be in PvP and !PvP (racial leader) cases
18654 if(RewardHonor(pVictim,1))
18655 honored_kill = true;
18657 // xp and reputation only in !PvP case
18658 if(!PvP)
18660 RewardReputation(pVictim,1);
18661 GiveXP(xp, pVictim);
18663 if(Pet* pet = GetPet())
18664 pet->GivePetXP(xp);
18666 // normal creature (not pet/etc) can be only in !PvP case
18667 if(pVictim->GetTypeId()==TYPEID_UNIT)
18668 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18671 return xp || honored_kill;
18674 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18676 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18678 // prepare data for near group iteration
18679 if(Group *pGroup = GetGroup())
18681 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18683 Player* pGroupGuy = itr->getSource();
18684 if(!pGroupGuy)
18685 continue;
18687 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18688 continue; // member (alive or dead) or his corpse at req. distance
18690 // quest objectives updated only for alive group member or dead but with not released body
18691 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18692 pGroupGuy->KilledMonster(creature_id, creature_guid);
18695 else // if (!pGroup)
18696 KilledMonster(creature_id, creature_guid);
18699 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18701 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18702 return true;
18704 if (isAlive())
18705 return false;
18707 Corpse* corpse = GetCorpse();
18708 if (!corpse)
18709 return false;
18711 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18714 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18716 Item* item = GetWeaponForAttack(attType,true);
18718 // unarmed only with base attack
18719 if(attType != BASE_ATTACK && !item)
18720 return 0;
18722 // weapon skill or (unarmed for base attack)
18723 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18724 return GetBaseSkillValue(skill);
18727 void Player::ResurectUsingRequestData()
18729 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18730 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18732 ResurrectPlayer(0.0f,false);
18734 if(GetMaxHealth() > m_resurrectHealth)
18735 SetHealth( m_resurrectHealth );
18736 else
18737 SetHealth( GetMaxHealth() );
18739 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18740 SetPower(POWER_MANA, m_resurrectMana );
18741 else
18742 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18744 SetPower(POWER_RAGE, 0 );
18746 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18748 SpawnCorpseBones();
18751 void Player::SetClientControl(Unit* target, uint8 allowMove)
18753 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18754 data.append(target->GetPackGUID());
18755 data << uint8(allowMove);
18756 GetSession()->SendPacket(&data);
18759 void Player::UpdateZoneDependentAuras( uint32 newZone )
18761 // remove new continent flight forms
18762 if( !IsAllowUseFlyMountsHere() )
18764 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18765 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18768 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18769 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18770 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18771 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18772 if( !HasAura(itr->second->spellId,0) )
18773 CastSpell(this,itr->second->spellId,true);
18776 void Player::UpdateAreaDependentAuras( uint32 newArea )
18778 // remove auras from spells with area limitations
18779 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18781 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18782 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18783 RemoveAura(iter);
18784 else
18785 ++iter;
18788 // some auras applied at subzone enter
18789 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18790 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18791 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18792 if( !HasAura(itr->second->spellId,0) )
18793 CastSpell(this,itr->second->spellId,true);
18796 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18798 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18799 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18801 return copseReclaimDelay[0];
18804 time_t now = time(NULL);
18805 // 0..2 full period
18806 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18807 return copseReclaimDelay[count];
18810 void Player::UpdateCorpseReclaimDelay()
18812 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18814 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18815 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18816 return;
18818 time_t now = time(NULL);
18819 if(now < m_deathExpireTime)
18821 // full and partly periods 1..3
18822 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18823 if(count < MAX_DEATH_COUNT)
18824 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18825 else
18826 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18828 else
18829 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18832 void Player::SendCorpseReclaimDelay(bool load)
18834 Corpse* corpse = GetCorpse();
18835 if(!corpse)
18836 return;
18838 uint32 delay;
18839 if(load)
18841 if(corpse->GetGhostTime() > m_deathExpireTime)
18842 return;
18844 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18846 uint32 count;
18847 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18848 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18850 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18851 if(count>=MAX_DEATH_COUNT)
18852 count = MAX_DEATH_COUNT-1;
18854 else
18855 count=0;
18857 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18859 time_t now = time(NULL);
18860 if(now >= expected_time)
18861 return;
18863 delay = expected_time-now;
18865 else
18866 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18868 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18869 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18870 data << uint32(delay*IN_MILISECONDS);
18871 GetSession()->SendPacket( &data );
18874 Player* Player::GetNextRandomRaidMember(float radius)
18876 Group *pGroup = GetGroup();
18877 if(!pGroup)
18878 return NULL;
18880 std::vector<Player*> nearMembers;
18881 nearMembers.reserve(pGroup->GetMembersCount());
18883 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18885 Player* Target = itr->getSource();
18887 // IsHostileTo check duel and controlled by enemy
18888 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18889 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18890 nearMembers.push_back(Target);
18893 if (nearMembers.empty())
18894 return NULL;
18896 uint32 randTarget = urand(0,nearMembers.size()-1);
18897 return nearMembers[randTarget];
18900 PartyResult Player::CanUninviteFromGroup() const
18902 const Group* grp = GetGroup();
18903 if(!grp)
18904 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18906 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18907 return PARTY_RESULT_YOU_NOT_LEADER;
18909 if(InBattleGround())
18910 return PARTY_RESULT_INVITE_RESTRICTED;
18912 return PARTY_RESULT_OK;
18915 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
18917 //we must move references from m_group to m_originalGroup
18918 SetOriginalGroup(GetGroup(), GetSubGroup());
18920 m_group.unlink();
18921 m_group.link(group, this);
18922 m_group.setSubGroup((uint8)subgroup);
18925 void Player::RemoveFromBattleGroundRaid()
18927 //remove existing reference
18928 m_group.unlink();
18929 if( Group* group = GetOriginalGroup() )
18931 m_group.link(group, this);
18932 m_group.setSubGroup(GetOriginalSubGroup());
18934 SetOriginalGroup(NULL);
18937 void Player::SetOriginalGroup(Group *group, int8 subgroup)
18939 if( group == NULL )
18940 m_originalGroup.unlink();
18941 else
18943 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18944 assert(subgroup >= 0);
18945 m_originalGroup.link(group, this);
18946 m_originalGroup.setSubGroup((uint8)subgroup);
18950 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18952 LiquidData liquid_status;
18953 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
18954 if (!res)
18956 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
18957 // Small hack for enable breath in WMO
18958 if (IsInWater())
18959 m_MirrorTimerFlags|=UNDERWATER_INWATER;
18960 return;
18963 // All liquids type - check under water position
18964 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
18966 if ( res & LIQUID_MAP_UNDER_WATER)
18967 m_MirrorTimerFlags |= UNDERWATER_INWATER;
18968 else
18969 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
18972 // Allow travel in dark water on taxi or transport
18973 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
18974 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
18975 else
18976 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
18978 // in lava check, anywhere in lava level
18979 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
18981 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18982 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
18983 else
18984 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
18986 // in slime check, anywhere in slime level
18987 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
18989 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
18990 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
18991 else
18992 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
18996 void Player::SetCanParry( bool value )
18998 if(m_canParry==value)
18999 return;
19001 m_canParry = value;
19002 UpdateParryPercentage();
19005 void Player::SetCanBlock( bool value )
19007 if(m_canBlock==value)
19008 return;
19010 m_canBlock = value;
19011 UpdateBlockPercentage();
19014 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19016 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19017 if(itr->pos == pos)
19018 return true;
19020 return false;
19023 bool Player::CanUseBattleGroundObject()
19025 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19026 // maybe gameobject code should handle that ForceReaction usage
19027 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19028 return ( //InBattleGround() && // in battleground - not need, check in other cases
19029 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19030 //player cannot use object when he is invulnerable (immune)
19031 !isTotalImmune() && // not totally immune
19032 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19033 !HasStealthAura() && // not stealthed
19034 !HasInvisibilityAura() && // not invisible
19035 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19036 isAlive() // live player
19040 bool Player::CanCaptureTowerPoint()
19042 return ( !HasStealthAura() && // not stealthed
19043 !HasInvisibilityAura() && // not invisible
19044 isAlive() // live player
19048 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19050 uint32 level = getLevel();
19052 if(level > GT_MAX_LEVEL)
19053 level = GT_MAX_LEVEL; // max level in this dbc
19055 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19056 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19057 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19059 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19060 return 0;
19062 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19064 if(!bsc) // shouldn't happen
19065 return 0xFFFFFFFF;
19067 float cost = 0;
19069 if(hairstyle != newhairstyle)
19070 cost += bsc->cost; // full price
19072 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19073 cost += bsc->cost * 0.5f; // +1/2 of price
19075 if(facialhair != newfacialhair)
19076 cost += bsc->cost * 0.75f; // +3/4 of price
19078 return uint32(cost);
19081 void Player::InitGlyphsForLevel()
19083 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19084 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19085 if(gs->Order)
19086 SetGlyphSlot(gs->Order - 1, gs->Id);
19088 uint32 level = getLevel();
19089 uint32 value = 0;
19091 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19092 if(level >= 15)
19093 value |= (0x01 | 0x02);
19094 if(level >= 30)
19095 value |= 0x08;
19096 if(level >= 50)
19097 value |= 0x04;
19098 if(level >= 70)
19099 value |= 0x10;
19100 if(level >= 80)
19101 value |= 0x20;
19103 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19106 void Player::EnterVehicle(Vehicle *vehicle)
19108 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19109 if(!ve)
19110 return;
19112 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19113 if(!veSeat)
19114 return;
19116 vehicle->SetCharmerGUID(GetGUID());
19117 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19118 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19119 vehicle->setFaction(getFaction());
19121 SetCharm(vehicle); // charm
19122 SetFarSightGUID(vehicle->GetGUID()); // set view
19124 SetClientControl(vehicle, 1); // redirect controls to vehicle
19126 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19127 GetSession()->SendPacket(&data);
19129 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19130 data.append(GetPackGUID());
19131 data << uint32(0); // counter?
19132 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19133 data << uint16(0); // special flags
19134 data << uint32(getMSTime()); // time
19135 data << vehicle->GetPositionX(); // x
19136 data << vehicle->GetPositionY(); // y
19137 data << vehicle->GetPositionZ(); // z
19138 data << vehicle->GetOrientation(); // o
19139 // transport part, TODO: load/calculate seat offsets
19140 data << uint64(vehicle->GetGUID()); // transport guid
19141 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19142 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19143 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19144 data << float(0); // transport orientation
19145 data << uint32(getMSTime()); // transport time
19146 data << uint8(0); // seat
19147 // end of transport part
19148 data << uint32(0); // fall time
19149 GetSession()->SendPacket(&data);
19151 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*10+1+1);
19152 data << uint64(vehicle->GetGUID());
19153 data << uint16(0);
19154 data << uint32(0);
19155 data << uint32(0x00000101);
19157 for(uint32 i = 0; i < 10; ++i)
19158 data << uint16(0) << uint8(0) << uint8(i+8);
19160 data << uint8(0);
19161 data << uint8(0);
19162 GetSession()->SendPacket(&data);
19165 void Player::ExitVehicle(Vehicle *vehicle)
19167 vehicle->SetCharmerGUID(0);
19168 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19169 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19170 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19172 SetCharm(NULL);
19173 SetFarSightGUID(0);
19175 SetClientControl(vehicle, 0);
19177 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19178 data.append(GetPackGUID());
19179 data << uint32(0); // counter?
19180 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19181 data << uint16(0x40); // special flags
19182 data << uint32(getMSTime()); // time
19183 data << vehicle->GetPositionX(); // x
19184 data << vehicle->GetPositionY(); // y
19185 data << vehicle->GetPositionZ(); // z
19186 data << vehicle->GetOrientation(); // o
19187 data << uint32(0); // fall time
19188 GetSession()->SendPacket(&data);
19190 data.Initialize(SMSG_PET_SPELLS, 8);
19191 data << uint64(0);
19192 GetSession()->SendPacket(&data);
19194 // maybe called at dummy aura remove?
19195 // CastSpell(this, 45472, true); // Parachute
19198 bool Player::isTotalImmune()
19200 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19202 uint32 immuneMask = 0;
19203 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19205 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19206 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19207 return true;
19209 return false;
19212 bool Player::HasTitle(uint32 bitIndex)
19214 if (bitIndex > 128)
19215 return false;
19217 uint32 fieldIndexOffset = bitIndex/32;
19218 uint32 flag = 1 << (bitIndex%32);
19219 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19222 void Player::SetTitle(CharTitlesEntry const* title)
19224 uint32 fieldIndexOffset = title->bit_index/32;
19225 uint32 flag = 1 << (title->bit_index%32);
19226 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
19229 void Player::ConvertRune(uint8 index, uint8 newType)
19231 SetCurrentRune(index, newType);
19233 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19234 data << uint8(index);
19235 data << uint8(newType);
19236 GetSession()->SendPacket(&data);
19239 void Player::ResyncRunes(uint8 count)
19241 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19242 for(uint32 i = 0; i < count; ++i)
19244 data << uint8(GetCurrentRune(i)); // rune type
19245 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19247 GetSession()->SendPacket(&data);
19250 void Player::AddRunePower(uint8 index)
19252 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19253 data << uint32(1 << index); // mask (0x00-0x3F probably)
19254 GetSession()->SendPacket(&data);
19257 void Player::InitRunes()
19259 if(getClass() != CLASS_DEATH_KNIGHT)
19260 return;
19262 m_runes = new Runes;
19264 m_runes->runeState = 0;
19266 for(uint32 i = 0; i < MAX_RUNES; ++i)
19268 SetBaseRune(i, i / 2); // init base types
19269 SetCurrentRune(i, i / 2); // init current types
19270 SetRuneCooldown(i, 0); // reset cooldowns
19271 m_runes->SetRuneState(i);
19274 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19275 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19278 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19280 Loot loot;
19281 loot.FillLoot (loot_id,store,this,true);
19283 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19284 for(uint32 i = 0; i < max_slot; ++i)
19286 LootItem* lootItem = loot.LootItemInSlot(i,this);
19288 ItemPosCountVec dest;
19289 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19290 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19291 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19292 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19293 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19294 if(msg != EQUIP_ERR_OK)
19296 SendEquipError( msg, NULL, NULL );
19297 continue;
19300 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19301 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19305 uint32 Player::CalculateTalentsPoints() const
19307 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19309 if(getClass() != CLASS_DEATH_KNIGHT)
19310 return base_talent;
19312 uint32 talentPointsForLevel =
19313 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19314 + m_questRewardTalentCount;
19316 if(talentPointsForLevel > base_talent)
19317 talentPointsForLevel = base_talent;
19319 return talentPointsForLevel;
19322 bool Player::IsAllowUseFlyMountsHere() const
19324 if (isGameMaster())
19325 return true;
19327 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19328 return v_map == 530 || v_map == 571 && HasSpell(54197);
19331 void Player::learnSpellHighRank(uint32 spellid)
19333 learnSpell(spellid,false);
19335 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19336 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19337 learnSpellHighRank(itr->second);
19340 void Player::_LoadSkills()
19342 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19344 // reset skill modifiers and set correct unlearn flags
19345 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19347 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19349 // set correct unlearn bit
19350 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19351 if(!id) continue;
19353 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19354 if(!pSkill) continue;
19356 // enable unlearn button for primary professions only
19357 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19358 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19359 else
19360 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19362 // set fixed skill ranges
19363 switch(GetSkillRangeType(pSkill,false))
19365 case SKILL_RANGE_LANGUAGE: // 300..300
19366 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19367 break;
19368 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19369 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19370 break;
19371 default:
19372 break;
19375 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19376 learnSkillRewardedSpells(id, vskill);
19379 // special settings
19380 if(getClass()==CLASS_DEATH_KNIGHT)
19382 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19383 if(base_level < 1)
19384 base_level = 1;
19385 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19386 if(base_skill < 1)
19387 base_skill = 1; // skill mast be known and then > 0 in any case
19389 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19390 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19391 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19392 SetSkill(SKILL_AXES, base_skill,base_skill);
19393 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19394 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19395 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19396 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19397 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19398 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19399 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19400 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19401 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19402 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19403 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19404 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19408 uint32 Player::GetPhaseMaskForSpawn() const
19410 uint32 phase = PHASEMASK_NORMAL;
19411 if(!isGameMaster())
19412 phase = GetPhaseMask();
19413 else
19415 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19416 if(!phases.empty())
19417 phase = phases.front()->GetMiscValue();
19420 // some aura phases include 1 normal map in addition to phase itself
19421 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19422 return n_phase;
19424 return PHASEMASK_NORMAL;
19427 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19429 ItemPrototype const* pProto = pItem->GetProto();
19431 // proto based limitations
19432 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19433 return res;
19435 // check unique-equipped on gems
19436 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19438 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19439 if(!enchant_id)
19440 continue;
19441 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19442 if(!enchantEntry)
19443 continue;
19445 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19446 if(!pGem)
19447 continue;
19449 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19450 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19451 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19453 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19454 return res;
19457 return EQUIP_ERR_OK;
19460 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19462 // check unique-equipped on item
19463 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19465 // there is an equip limit on this item
19466 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19467 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19470 // check unique-equipped limit
19471 if (itemProto->ItemLimitCategory)
19473 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19474 if(!limitEntry)
19475 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19477 if(limit_count > limitEntry->maxCount)
19478 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19480 // there is an equip limit on this item
19481 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19482 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19485 return EQUIP_ERR_OK;
19488 void Player::HandleFall(MovementInfo const& movementInfo)
19490 // calculate total z distance of the fall
19491 float z_diff = m_lastFallZ - movementInfo.z;
19492 sLog.outDebug("zDiff = %f", z_diff);
19494 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19495 // 14.57 can be calculated by resolving damageperc formula below to 0
19496 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19497 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19498 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19500 //Safe fall, fall height reduction
19501 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19503 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19505 if(damageperc >0 )
19507 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19509 float height = movementInfo.z;
19510 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19512 if (damage > 0)
19514 //Prevent fall damage from being more than the player maximum health
19515 if (damage > GetMaxHealth())
19516 damage = GetMaxHealth();
19518 // Gust of Wind
19519 if (GetDummyAura(43621))
19520 damage = GetMaxHealth()/2;
19522 EnvironmentalDamage(DAMAGE_FALL, damage);
19524 // recheck alive, might have died of EnvironmentalDamage
19525 if (isAlive())
19526 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19529 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19530 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);
19535 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19537 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19540 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19542 uint32 CurTalentPoints = GetFreeTalentPoints();
19544 if(CurTalentPoints == 0)
19545 return;
19547 if (talentRank >= MAX_TALENT_RANK)
19548 return;
19550 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19552 if(!talentInfo)
19553 return;
19555 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19557 if(!talentTabInfo)
19558 return;
19560 // prevent learn talent for different class (cheating)
19561 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19562 return;
19564 // find current max talent rank
19565 int32 curtalent_maxrank = 0;
19566 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19568 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19570 curtalent_maxrank = k + 1;
19571 break;
19575 // we already have same or higher talent rank learned
19576 if(curtalent_maxrank >= (talentRank + 1))
19577 return;
19579 // check if we have enough talent points
19580 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19581 return;
19583 // Check if it requires another talent
19584 if (talentInfo->DependsOn > 0)
19586 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19588 bool hasEnoughRank = false;
19589 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19591 if (depTalentInfo->RankID[i] != 0)
19592 if (HasSpell(depTalentInfo->RankID[i]))
19593 hasEnoughRank = true;
19595 if (!hasEnoughRank)
19596 return;
19600 // Find out how many points we have in this field
19601 uint32 spentPoints = 0;
19603 uint32 tTab = talentInfo->TalentTab;
19604 if (talentInfo->Row > 0)
19606 unsigned int numRows = sTalentStore.GetNumRows();
19607 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19609 // Someday, someone needs to revamp
19610 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19611 if (tmpTalent) // the way talents are tracked
19613 if (tmpTalent->TalentTab == tTab)
19615 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19617 if (tmpTalent->RankID[j] != 0)
19619 if (HasSpell(tmpTalent->RankID[j]))
19621 spentPoints += j + 1;
19630 // not have required min points spent in talent tree
19631 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19632 return;
19634 // spell not set in talent.dbc
19635 uint32 spellid = talentInfo->RankID[talentRank];
19636 if( spellid == 0 )
19638 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19639 return;
19642 // already known
19643 if(HasSpell(spellid))
19644 return;
19646 // learn! (other talent ranks will unlearned at learning)
19647 learnSpell(spellid, false);
19648 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19650 // update free talent points
19651 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19654 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19656 Pet *pet = GetPet();
19658 if(!pet)
19659 return;
19661 if(petGuid != pet->GetGUID())
19662 return;
19664 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19666 if(CurTalentPoints == 0)
19667 return;
19669 if (talentRank >= MAX_PET_TALENT_RANK)
19670 return;
19672 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19674 if(!talentInfo)
19675 return;
19677 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19679 if(!talentTabInfo)
19680 return;
19682 CreatureInfo const *ci = pet->GetCreatureInfo();
19684 if(!ci)
19685 return;
19687 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19689 if(!pet_family)
19690 return;
19692 if(pet_family->petTalentType < 0) // not hunter pet
19693 return;
19695 // prevent learn talent for different family (cheating)
19696 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19697 return;
19699 // find current max talent rank
19700 int32 curtalent_maxrank = 0;
19701 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19703 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19705 curtalent_maxrank = k + 1;
19706 break;
19710 // we already have same or higher talent rank learned
19711 if(curtalent_maxrank >= (talentRank + 1))
19712 return;
19714 // check if we have enough talent points
19715 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19716 return;
19718 // Check if it requires another talent
19719 if (talentInfo->DependsOn > 0)
19721 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19723 bool hasEnoughRank = false;
19724 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19726 if (depTalentInfo->RankID[i] != 0)
19727 if (pet->HasSpell(depTalentInfo->RankID[i]))
19728 hasEnoughRank = true;
19730 if (!hasEnoughRank)
19731 return;
19735 // Find out how many points we have in this field
19736 uint32 spentPoints = 0;
19738 uint32 tTab = talentInfo->TalentTab;
19739 if (talentInfo->Row > 0)
19741 unsigned int numRows = sTalentStore.GetNumRows();
19742 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19744 // Someday, someone needs to revamp
19745 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19746 if (tmpTalent) // the way talents are tracked
19748 if (tmpTalent->TalentTab == tTab)
19750 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19752 if (tmpTalent->RankID[j] != 0)
19754 if (pet->HasSpell(tmpTalent->RankID[j]))
19756 spentPoints += j + 1;
19765 // not have required min points spent in talent tree
19766 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19767 return;
19769 // spell not set in talent.dbc
19770 uint32 spellid = talentInfo->RankID[talentRank];
19771 if( spellid == 0 )
19773 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19774 return;
19777 // already known
19778 if(pet->HasSpell(spellid))
19779 return;
19781 // learn! (other talent ranks will unlearned at learning)
19782 pet->learnSpell(spellid);
19783 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19785 // update free talent points
19786 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19789 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19791 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19793 if(apply)
19794 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19795 else
19796 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(1LL << (ctEntry->BitIndex-1)));
19800 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19802 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19803 SetFallInformation(minfo.fallTime, minfo.z);
19806 void Player::UnsummonPetTemporaryIfAny()
19808 Pet* pet = GetPet();
19809 if(!pet)
19810 return;
19812 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19814 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19815 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19818 RemovePet(pet, PET_SAVE_AS_CURRENT);
19821 void Player::ResummonPetTemporaryUnSummonedIfAny()
19823 if(!m_temporaryUnsummonedPetNumber)
19824 return;
19826 // not resummon in not appropriate state
19827 if(IsPetNeedBeTemporaryUnsummoned())
19828 return;
19830 if(GetPetGUID())
19831 return;
19833 Pet* NewPet = new Pet;
19834 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
19835 delete NewPet;
19837 m_temporaryUnsummonedPetNumber = 0;
19840 bool Player::canSeeSpellClickOn(Creature const *c) const
19842 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
19843 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(c->GetEntry()); itr != map.upper_bound(c->GetEntry()); ++itr)
19845 if(itr->second.questId == 0 || GetQuestStatus(itr->second.questId) == QUEST_STATUS_INCOMPLETE)
19846 return true;
19848 return false;
19851 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
19853 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
19854 uint8 talentGroupCount = 1;
19855 *data << uint8(talentGroupCount); // talent group count (1 or 2)
19856 *data << uint8(0); // talent group index (0 or 1)
19858 if(talentGroupCount)
19860 uint8 talentIdCount = 0;
19861 size_t pos = data->wpos();
19862 *data << uint8(talentIdCount); // [PH], talentIdCount
19864 // find class talent tabs (all players have 3 talent tabs)
19865 uint32 const* talentTabIds = GetTalentTabPages(getClass());
19867 for(uint32 i = 0; i < 3; ++i)
19869 uint32 talentTabId = talentTabIds[i];
19871 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19873 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19874 if(!talentInfo)
19875 continue;
19877 // skip another tab talents
19878 if(talentInfo->TalentTab != talentTabId)
19879 continue;
19881 // find max talent rank
19882 int32 curtalent_maxrank = -1;
19883 for(int32 k = 4; k > -1; --k)
19885 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19887 curtalent_maxrank = k;
19888 break;
19892 // not learned talent
19893 if(curtalent_maxrank < 0)
19894 continue;
19896 *data << uint32(talentInfo->TalentID); // Talent.dbc
19897 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
19899 ++talentIdCount;
19903 data->put<uint8>(pos, talentIdCount); // put real count
19905 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
19907 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
19908 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
19912 void Player::BuildPetTalentsInfoData(WorldPacket *data)
19914 uint32 unspentTalentPoints = 0;
19915 size_t pointsPos = data->wpos();
19916 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
19918 uint8 talentIdCount = 0;
19919 size_t countPos = data->wpos();
19920 *data << uint8(talentIdCount); // [PH], talentIdCount
19922 Pet *pet = GetPet();
19923 if(!pet)
19924 return;
19926 unspentTalentPoints = pet->GetFreeTalentPoints();
19928 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
19930 CreatureInfo const *ci = pet->GetCreatureInfo();
19931 if(!ci)
19932 return;
19934 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19935 if(!pet_family || pet_family->petTalentType < 0)
19936 return;
19938 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
19940 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
19941 if(!talentTabInfo)
19942 continue;
19944 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19945 continue;
19947 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
19949 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
19950 if(!talentInfo)
19951 continue;
19953 // skip another tab talents
19954 if(talentInfo->TalentTab != talentTabId)
19955 continue;
19957 // find max talent rank
19958 int32 curtalent_maxrank = -1;
19959 for(int32 k = 4; k > -1; --k)
19961 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19963 curtalent_maxrank = k;
19964 break;
19968 // not learned talent
19969 if(curtalent_maxrank < 0)
19970 continue;
19972 *data << uint32(talentInfo->TalentID); // Talent.dbc
19973 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
19975 ++talentIdCount;
19978 data->put<uint8>(countPos, talentIdCount); // put real count
19980 break;
19984 void Player::SendTalentsInfoData(bool pet)
19986 if(GetSession()->PlayerLoading())
19987 return;
19989 WorldPacket data(SMSG_TALENTS_INFO, 50);
19990 data << uint8(pet ? 1 : 0);
19991 if(pet)
19992 BuildPetTalentsInfoData(&data);
19993 else
19994 BuildPlayerTalentsInfoData(&data);
19995 GetSession()->SendPacket(&data);
19998 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
20000 uint32 slotUsedMask = 0;
20001 size_t slotUsedMaskPos = data->wpos();
20002 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
20004 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20006 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
20008 if(!item)
20009 continue;
20011 slotUsedMask |= (1 << i);
20013 *data << uint32(item->GetEntry()); // item entry
20015 uint16 enchantmentMask = 0;
20016 size_t enchantmentMaskPos = data->wpos();
20017 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
20019 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
20021 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
20023 if(!enchId)
20024 continue;
20026 enchantmentMask |= (1 << j);
20028 *data << uint16(enchId); // enchantmentId?
20031 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
20033 *data << uint16(0); // ?
20034 *data << uint8(0); // PGUID!
20035 *data << uint32(0); // seed?
20038 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
20041 void Player::SendEquipmentSetList()
20043 uint32 count = 0;
20044 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
20045 size_t count_pos = data.wpos();
20046 data << uint32(count); // count placeholder
20047 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20049 if(itr->second.state==EQUIPMENT_SET_DELETED)
20050 continue;
20051 data.appendPackGUID(itr->second.Guid);
20052 data << uint32(itr->first);
20053 data << itr->second.Name;
20054 data << itr->second.IconName;
20055 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
20056 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
20058 ++count; // client have limit but it checked at loading and set
20060 data.put<uint32>(count_pos, count);
20061 GetSession()->SendPacket(&data);
20064 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
20066 if(eqset.Guid != 0)
20068 bool found = false;
20070 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20072 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
20074 found = true;
20075 break;
20079 if(!found) // something wrong...
20081 sLog.outError("Player %s tried to save equipment set "I64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
20082 return;
20086 EquipmentSet& eqslot = m_EquipmentSets[index];
20088 EquipmentSetUpdateState old_state = eqslot.state;
20090 eqslot = eqset;
20092 if(eqset.Guid == 0)
20094 eqslot.Guid = objmgr.GenerateEquipmentSetGuid();
20096 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
20097 data << uint32(index);
20098 data.appendPackGUID(eqslot.Guid);
20099 GetSession()->SendPacket(&data);
20102 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
20105 void Player::_SaveEquipmentSets()
20107 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
20109 uint32 index = itr->first;
20110 EquipmentSet& eqset = itr->second;
20111 switch(eqset.state)
20113 case EQUIPMENT_SET_UNCHANGED:
20114 ++itr;
20115 break; // nothing do
20116 case EQUIPMENT_SET_CHANGED:
20117 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='"I64FMTD"' AND setindex='%u'",
20118 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],
20119 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);
20120 eqset.state = EQUIPMENT_SET_UNCHANGED;
20121 ++itr;
20122 break;
20123 case EQUIPMENT_SET_NEW:
20124 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"I64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20125 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],
20126 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]);
20127 eqset.state = EQUIPMENT_SET_UNCHANGED;
20128 ++itr;
20129 break;
20130 case EQUIPMENT_SET_DELETED:
20131 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="I64FMTD, eqset.Guid);
20132 m_EquipmentSets.erase(itr++);
20133 break;
20138 void Player::DeleteEquipmentSet(uint64 setGuid)
20140 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
20142 if(itr->second.Guid == setGuid)
20144 itr->second.state = EQUIPMENT_SET_DELETED;
20145 break;