[7986] MaNGOS 0.13 release.
[getmangos.git] / src / game / Player.cpp
blob61830d18e68ca99ec0ce66cf492a04bd0eb06a32
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,true))
227 return false;
229 return true;
232 std::string PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations.empty())
235 return "";
237 std::ostringstream ss;
239 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
240 ss << m_TaxiDestinations[i] << " ";
242 return ss.str();
245 uint32 PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations.size() < 2)
248 return 0;
250 uint32 path;
251 uint32 cost;
253 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
255 return path;
258 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
260 ss << "'";
261 for(int i = 0; i < TaxiMaskSize; ++i)
262 ss << taxi.m_taximask[i] << " ";
263 ss << "'";
264 return ss;
267 //== Player ====================================================
269 UpdateMask Player::updateVisualBits;
271 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
273 m_transport = 0;
275 m_speakTime = 0;
276 m_speakCount = 0;
278 m_objectType |= TYPEMASK_PLAYER;
279 m_objectTypeId = TYPEID_PLAYER;
281 m_valuesCount = PLAYER_END;
283 m_session = session;
285 m_divider = 0;
287 m_ExtraFlags = 0;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER)
293 SetAcceptWhispers(true);
295 m_curSelection = 0;
296 m_lootGuid = 0;
298 m_comboTarget = 0;
299 m_comboPoints = 0;
301 m_usedTalentCount = 0;
302 m_questRewardTalentCount = 0;
304 m_regenTimer = 0;
305 m_weaponChangeTimer = 0;
307 m_zoneUpdateId = 0;
308 m_zoneUpdateTimer = 0;
310 m_areaUpdateId = 0;
312 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount = 0;
322 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
324 m_social = NULL;
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL);
328 m_groupUpdateMask = 0;
329 m_auraUpdateMask = 0;
331 duel = NULL;
333 m_GuildIdInvited = 0;
334 m_ArenaTeamIdInvited = 0;
336 m_atLoginFlags = AT_LOGIN_NONE;
338 mSemaphoreTeleport_Near = false;
339 mSemaphoreTeleport_Far = false;
341 pTrader = 0;
342 ClearTrade();
344 m_cinematic = 0;
346 PlayerTalkClass = new PlayerMenu( GetSession() );
347 m_currentBuybackSlot = BUYBACK_SLOT_START;
349 for ( int aX = 0 ; aX < 8 ; aX++ )
350 m_Tutorials[ aX ] = 0x00;
351 m_TutorialsChanged = false;
353 m_DailyQuestChanged = false;
354 m_lastDailyQuestTime = 0;
356 for (int i=0; i<MAX_TIMERS; ++i)
357 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
359 m_MirrorTimerFlags = UNDERWATER_NONE;
360 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
361 m_isInWater = false;
362 m_drunkTimer = 0;
363 m_drunk = 0;
364 m_restTime = 0;
365 m_deathTimer = 0;
366 m_deathExpireTime = 0;
368 m_swingErrorMsg = 0;
370 m_DetectInvTimer = 1*IN_MILISECONDS;
372 m_bgBattleGroundID = 0;
373 m_bgTypeID = BATTLEGROUND_TYPE_NONE;
374 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
376 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
377 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
379 m_bgTeam = 0;
381 m_logintime = time(NULL);
382 m_Last_tick = m_logintime;
383 m_WeaponProficiency = 0;
384 m_ArmorProficiency = 0;
385 m_canParry = false;
386 m_canBlock = false;
387 m_canDualWield = false;
388 m_canTitanGrip = false;
389 m_ammoDPS = 0.0f;
391 m_temporaryUnsummonedPetNumber = 0;
392 //cache for UNIT_CREATED_BY_SPELL to allow
393 //returning reagents for temporarily removed pets
394 //when dying/logging out
395 m_oldpetspell = 0;
397 ////////////////////Rest System/////////////////////
398 time_inn_enter=0;
399 inn_pos_mapid=0;
400 inn_pos_x=0;
401 inn_pos_y=0;
402 inn_pos_z=0;
403 m_rest_bonus=0;
404 rest_type=REST_TYPE_NO;
405 ////////////////////Rest System/////////////////////
407 m_mailsLoaded = false;
408 m_mailsUpdated = false;
409 unReadMails = 0;
410 m_nextMailDelivereTime = 0;
412 m_resetTalentsCost = 0;
413 m_resetTalentsTime = 0;
414 m_itemUpdateQueueBlocked = false;
416 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
417 m_forced_speed_changes[i] = 0;
419 m_stableSlots = 0;
421 /////////////////// Instance System /////////////////////
423 m_HomebindTimer = 0;
424 m_InstanceValid = true;
425 m_dungeonDifficulty = DIFFICULTY_NORMAL;
427 m_lastPotionId = 0;
429 for (int i = 0; i < BASEMOD_END; ++i)
431 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
432 m_auraBaseMod[i][PCT_MOD] = 1.0f;
435 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
436 m_baseRatingValue[i] = 0;
438 m_baseSpellDamage = 0;
439 m_baseSpellHealing = 0;
440 m_baseFeralAP = 0;
441 m_baseManaRegen = 0;
443 // Honor System
444 m_lastHonorUpdateTime = time(NULL);
446 // Player summoning
447 m_summon_expire = 0;
448 m_summon_mapid = 0;
449 m_summon_x = 0.0f;
450 m_summon_y = 0.0f;
451 m_summon_z = 0.0f;
453 //Default movement to run mode
454 m_unit_movement_flags = 0;
456 m_mover = this;
458 m_miniPet = 0;
459 m_bgAfkReportedTimer = 0;
460 m_contestedPvPTimer = 0;
462 m_declinedname = NULL;
463 m_runes = NULL;
465 m_lastFallTime = 0;
466 m_lastFallZ = 0;
469 Player::~Player ()
471 CleanupsBeforeDelete();
473 // it must be unloaded already in PlayerLogout and accessed only for loggined player
474 //m_social = NULL;
476 // Note: buy back item already deleted from DB when player was saved
477 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
479 if(m_items[i])
480 delete m_items[i];
482 CleanupChannels();
484 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
485 delete itr->second;
487 //all mailed items should be deleted, also all mail should be deallocated
488 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
489 delete *itr;
491 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
492 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
494 delete PlayerTalkClass;
496 if (m_transport)
498 m_transport->RemovePassenger(this);
501 for(size_t x = 0; x < ItemSetEff.size(); x++)
502 if(ItemSetEff[x])
503 delete ItemSetEff[x];
505 // clean up player-instance binds, may unload some instance saves
506 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
507 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
508 itr->second.save->RemovePlayer(this);
510 delete m_declinedname;
511 delete m_runes;
514 void Player::CleanupsBeforeDelete()
516 if(m_uint32Values) // only for fully created Object
518 TradeCancel(false);
519 DuelComplete(DUEL_INTERUPTED);
521 Unit::CleanupsBeforeDelete();
524 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
526 //FIXME: outfitId not used in player creating
528 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
530 m_name = name;
532 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
533 if(!info)
535 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
536 return false;
539 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
540 m_items[i] = NULL;
542 m_race = race;
543 m_class = class_;
545 SetMapId(info->mapId);
546 Relocate(info->positionX,info->positionY,info->positionZ);
548 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
549 if(!cEntry)
551 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
552 return false;
555 uint8 powertype = cEntry->powerType;
557 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
558 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
560 switch(gender)
562 case GENDER_FEMALE:
563 SetDisplayId(info->displayId_f );
564 SetNativeDisplayId(info->displayId_f );
565 break;
566 case GENDER_MALE:
567 SetDisplayId(info->displayId_m );
568 SetNativeDisplayId(info->displayId_m );
569 break;
570 default:
571 sLog.outError("Invalid gender %u for player",gender);
572 return false;
573 break;
576 setFactionForRace(m_race);
578 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
580 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
581 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
582 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
583 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
584 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
585 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
587 // -1 is default value
588 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
590 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
591 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
592 SetByteValue(PLAYER_BYTES_3, 0, gender);
594 SetUInt32Value( PLAYER_GUILDID, 0 );
595 SetUInt32Value( PLAYER_GUILDRANK, 0 );
596 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
606 // set starting level
607 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
609 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
613 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
614 if(gm_level > start_level)
615 start_level = gm_level;
618 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
620 InitRunes();
622 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
626 // Played time
627 m_Last_tick = time(NULL);
628 m_Played_time[0] = 0;
629 m_Played_time[1] = 0;
631 // base stats and related field values
632 InitStatsForLevel();
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProfessions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 DealDamageMods(this,damage,&absorb);
851 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
852 data << uint64(GetGUID());
853 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
854 data << uint32(damage);
855 data << uint32(absorb);
856 data << uint32(resist);
857 SendMessageToSet(&data, true);
859 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
861 if(!isAlive())
863 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
865 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
866 DurabilityLossAll(0.10f,false);
867 // durability lost message
868 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
869 GetSession()->SendPacket(&data2);
872 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
876 int32 Player::getMaxTimer(MirrorTimerType timer)
878 switch (timer)
880 case FATIGUE_TIMER:
881 return MINUTE*IN_MILISECONDS;
882 case BREATH_TIMER:
884 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
885 return DISABLED_MIRROR_TIMER;
886 int32 UnderWaterTime = 3*MINUTE*IN_MILISECONDS;
887 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
888 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
889 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
890 return UnderWaterTime;
892 case FIRE_TIMER:
894 if (!isAlive())
895 return DISABLED_MIRROR_TIMER;
896 return 1*IN_MILISECONDS;
898 default:
899 return 0;
901 return 0;
904 void Player::UpdateMirrorTimers()
906 // Desync flags for update on next HandleDrowning
907 if (m_MirrorTimerFlags)
908 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
911 void Player::HandleDrowning(uint32 time_diff)
913 if (!m_MirrorTimerFlags)
914 return;
916 // In water
917 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
919 // Breath timer not activated - activate it
920 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
922 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
923 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
925 else // If activated - do tick
927 m_MirrorTimer[BREATH_TIMER]-=time_diff;
928 // Timer limit - need deal damage
929 if (m_MirrorTimer[BREATH_TIMER] < 0)
931 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
932 // Calculate and deal damage
933 // TODO: Check this formula
934 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
935 EnvironmentalDamage(DAMAGE_DROWNING, damage);
937 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
938 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
941 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
943 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
944 // Need breath regen
945 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
946 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
947 StopMirrorTimer(BREATH_TIMER);
948 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
949 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
952 // In dark water
953 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
955 // Fatigue timer not activated - activate it
956 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
958 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
959 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
961 else
963 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
964 // Timer limit - need deal damage or teleport ghost to graveyard
965 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
967 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
968 if (isAlive()) // Calculate and deal damage
970 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
971 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
973 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
974 RepopAtGraveyard();
976 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
977 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
980 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
982 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
983 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
984 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
985 StopMirrorTimer(FATIGUE_TIMER);
986 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
987 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
990 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
992 // Breath timer not activated - activate it
993 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
994 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
995 else
997 m_MirrorTimer[FIRE_TIMER]-=time_diff;
998 if (m_MirrorTimer[FIRE_TIMER] < 0)
1000 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1001 // Calculate and deal damage
1002 // TODO: Check this formula
1003 uint32 damage = urand(600, 700);
1004 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1005 EnvironmentalDamage(DAMAGE_LAVA, damage);
1006 else
1007 EnvironmentalDamage(DAMAGE_SLIME, damage);
1011 else
1012 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1014 // Recheck timers flag
1015 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1016 for (int i = 0; i< MAX_TIMERS; ++i)
1017 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1019 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1020 break;
1022 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1025 ///The player sobers by 256 every 10 seconds
1026 void Player::HandleSobering()
1028 m_drunkTimer = 0;
1030 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1031 SetDrunkValue(drunk);
1034 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1036 if(value >= 23000)
1037 return DRUNKEN_SMASHED;
1038 if(value >= 12800)
1039 return DRUNKEN_DRUNK;
1040 if(value & 0xFFFE)
1041 return DRUNKEN_TIPSY;
1042 return DRUNKEN_SOBER;
1045 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1047 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1049 m_drunk = newDrunkenValue;
1050 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1052 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1054 // special drunk invisibility detection
1055 if(newDrunkenState >= DRUNKEN_DRUNK)
1056 m_detectInvisibilityMask |= (1<<6);
1057 else
1058 m_detectInvisibilityMask &= ~(1<<6);
1060 if(newDrunkenState == oldDrunkenState)
1061 return;
1063 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1064 data << uint64(GetGUID());
1065 data << uint32(newDrunkenState);
1066 data << uint32(itemId);
1068 SendMessageToSet(&data, true);
1071 void Player::Update( uint32 p_time )
1073 if(!IsInWorld())
1074 return;
1076 // undelivered mail
1077 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1079 SendNewMail();
1080 ++unReadMails;
1082 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1083 m_nextMailDelivereTime = 0;
1086 Unit::Update( p_time );
1088 // update player only attacks
1089 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1091 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1094 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1096 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1099 time_t now = time (NULL);
1101 UpdatePvPFlag(now);
1103 UpdateContestedPvP(p_time);
1105 UpdateDuelFlag(now);
1107 CheckDuelDistance(now);
1109 UpdateAfkReport(now);
1111 // Update items that have just a limited lifetime
1112 if (now>m_Last_tick)
1113 UpdateItemDuration(uint32(now- m_Last_tick));
1115 if (!m_timedquests.empty())
1117 std::set<uint32>::iterator iter = m_timedquests.begin();
1118 while (iter != m_timedquests.end())
1120 QuestStatusData& q_status = mQuestStatus[*iter];
1121 if( q_status.m_timer <= p_time )
1123 uint32 quest_id = *iter;
1124 ++iter; // current iter will be removed in FailTimedQuest
1125 FailTimedQuest( quest_id );
1127 else
1129 q_status.m_timer -= p_time;
1130 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1131 ++iter;
1136 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1138 Unit *pVictim = getVictim();
1139 if (pVictim && !IsNonMeleeSpellCasted(false))
1141 // default combat reach 10
1142 // TODO add weapon,skill check
1144 float pldistance = ATTACK_DISTANCE;
1146 if (isAttackReady(BASE_ATTACK))
1148 if(!IsWithinDistInMap(pVictim, pldistance))
1150 setAttackTimer(BASE_ATTACK,100);
1151 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1153 SendAttackSwingNotInRange();
1154 m_swingErrorMsg = 1;
1157 //120 degrees of radiant range
1158 else if( !HasInArc( 2*M_PI/3, pVictim ))
1160 setAttackTimer(BASE_ATTACK,100);
1161 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1163 SendAttackSwingBadFacingAttack();
1164 m_swingErrorMsg = 2;
1167 else
1169 m_swingErrorMsg = 0; // reset swing error state
1171 // prevent base and off attack in same time, delay attack at 0.2 sec
1172 if(haveOffhandWeapon())
1174 uint32 off_att = getAttackTimer(OFF_ATTACK);
1175 if(off_att < ATTACK_DISPLAY_DELAY)
1176 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1178 AttackerStateUpdate(pVictim, BASE_ATTACK);
1179 resetAttackTimer(BASE_ATTACK);
1183 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1185 if(!IsWithinDistInMap(pVictim, pldistance))
1187 setAttackTimer(OFF_ATTACK,100);
1189 else if( !HasInArc( 2*M_PI/3, pVictim ))
1191 setAttackTimer(OFF_ATTACK,100);
1193 else
1195 // prevent base and off attack in same time, delay attack at 0.2 sec
1196 uint32 base_att = getAttackTimer(BASE_ATTACK);
1197 if(base_att < ATTACK_DISPLAY_DELAY)
1198 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1199 // do attack
1200 AttackerStateUpdate(pVictim, OFF_ATTACK);
1201 resetAttackTimer(OFF_ATTACK);
1205 Unit *owner = pVictim->GetOwner();
1206 Unit *u = owner ? owner : pVictim;
1207 if(u->IsPvP() && (!duel || duel->opponent != u))
1209 UpdatePvP(true);
1210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1215 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1217 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1219 int time_inn = time(NULL)-GetTimeInnEnter();
1220 if (time_inn >= 10) //freeze update
1222 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1223 //speed collect rest bonus (section/in hour)
1224 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1225 UpdateInnerTime(time(NULL));
1230 if(m_regenTimer > 0)
1232 if(p_time >= m_regenTimer)
1233 m_regenTimer = 0;
1234 else
1235 m_regenTimer -= p_time;
1238 if (m_weaponChangeTimer > 0)
1240 if(p_time >= m_weaponChangeTimer)
1241 m_weaponChangeTimer = 0;
1242 else
1243 m_weaponChangeTimer -= p_time;
1246 if (m_zoneUpdateTimer > 0)
1248 if(p_time >= m_zoneUpdateTimer)
1250 uint32 newzone, newarea;
1251 GetZoneAndAreaId(newzone,newarea);
1253 if( m_zoneUpdateId != newzone )
1254 UpdateZone(newzone,newarea); // also update area
1255 else
1257 // use area updates as well
1258 // needed for free far all arenas for example
1259 if( m_areaUpdateId != newarea )
1260 UpdateArea(newarea);
1262 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1265 else
1266 m_zoneUpdateTimer -= p_time;
1269 if (isAlive())
1271 RegenerateAll();
1274 if (m_deathState == JUST_DIED)
1276 KillPlayer();
1279 if(m_nextSave > 0)
1281 if(p_time >= m_nextSave)
1283 // m_nextSave reseted in SaveToDB call
1284 SaveToDB();
1285 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1287 else
1289 m_nextSave -= p_time;
1293 //Handle Water/drowning
1294 HandleDrowning(p_time);
1296 //Handle detect stealth players
1297 if (m_DetectInvTimer > 0)
1299 if (p_time >= m_DetectInvTimer)
1301 m_DetectInvTimer = 3000;
1302 HandleStealthedUnitsDetection();
1304 else
1305 m_DetectInvTimer -= p_time;
1308 // Played time
1309 if (now > m_Last_tick)
1311 uint32 elapsed = uint32(now - m_Last_tick);
1312 m_Played_time[0] += elapsed; // Total played time
1313 m_Played_time[1] += elapsed; // Level played time
1314 m_Last_tick = now;
1317 if (m_drunk)
1319 m_drunkTimer += p_time;
1321 if (m_drunkTimer > 10*IN_MILISECONDS)
1322 HandleSobering();
1325 // not auto-free ghost from body in instances
1326 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1328 if(p_time >= m_deathTimer)
1330 m_deathTimer = 0;
1331 BuildPlayerRepop();
1332 RepopAtGraveyard();
1334 else
1335 m_deathTimer -= p_time;
1338 UpdateEnchantTime(p_time);
1339 UpdateHomebindTime(p_time);
1341 // group update
1342 SendUpdateToOutOfRangeGroupMembers();
1344 Pet* pet = GetPet();
1345 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1347 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1348 return;
1352 void Player::setDeathState(DeathState s)
1354 uint32 ressSpellId = 0;
1356 bool cur = isAlive();
1358 if(s == JUST_DIED && cur)
1360 // drunken state is cleared on death
1361 SetDrunkValue(0);
1362 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1363 ClearComboPoints();
1365 clearResurrectRequestData();
1367 // remove form before other mods to prevent incorrect stats calculation
1368 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1370 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1371 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1373 // remove uncontrolled pets
1374 RemoveMiniPet();
1375 RemoveGuardians();
1377 // save value before aura remove in Unit::setDeathState
1378 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1380 // passive spell
1381 if(!ressSpellId)
1382 ressSpellId = GetResurrectionSpellId();
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1384 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1385 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1387 Unit::setDeathState(s);
1389 // restore resurrection spell id for player after aura remove
1390 if(s == JUST_DIED && cur && ressSpellId)
1391 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1393 if(isAlive() && !cur)
1395 //clear aura case after resurrection by another way (spells will be applied before next death)
1396 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1398 // restore default warrior stance
1399 if(getClass()== CLASS_WARRIOR)
1400 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1404 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1406 Field *fields = result->Fetch();
1408 *p_data << uint64(GetGUID());
1409 *p_data << m_name;
1411 *p_data << uint8(getRace());
1412 uint8 pClass = getClass();
1413 *p_data << uint8(pClass);
1414 *p_data << uint8(getGender());
1416 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1417 *p_data << uint8(bytes);
1418 *p_data << uint8(bytes >> 8);
1419 *p_data << uint8(bytes >> 16);
1420 *p_data << uint8(bytes >> 24);
1422 bytes = GetUInt32Value(PLAYER_BYTES_2);
1423 *p_data << uint8(bytes);
1425 *p_data << uint8(getLevel()); // player level
1426 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1427 uint32 zoneId = fields[10].GetUInt32();
1428 sLog.outDebug("Player::BuildEnumData: map:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1429 *p_data << uint32(zoneId);
1430 *p_data << uint32(GetMapId());
1432 *p_data << GetPositionX();
1433 *p_data << GetPositionY();
1434 *p_data << GetPositionZ();
1436 // guild id
1437 *p_data << uint32(fields[14].GetUInt32());
1439 uint32 char_flags = 0;
1440 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1441 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1442 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1443 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1444 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1445 char_flags |= CHARACTER_FLAG_GHOST;
1446 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1447 char_flags |= CHARACTER_FLAG_RENAME;
1448 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1450 if(!fields[15].GetCppString().empty())
1451 char_flags |= CHARACTER_FLAG_DECLINED;
1453 else
1454 char_flags |= CHARACTER_FLAG_DECLINED;
1456 *p_data << uint32(char_flags); // character flags
1457 // character customize (flags?)
1458 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1459 *p_data << uint8(1); // unknown
1461 // Pets info
1463 uint32 petDisplayId = 0;
1464 uint32 petLevel = 0;
1465 uint32 petFamily = 0;
1467 // show pet at selection character in character list only for non-ghost character
1468 if (result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1470 uint32 entry = fields[11].GetUInt32();
1471 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1472 if(cInfo)
1474 petDisplayId = fields[12].GetUInt32();
1475 petLevel = fields[13].GetUInt32();
1476 petFamily = cInfo->family;
1480 *p_data << uint32(petDisplayId);
1481 *p_data << uint32(petLevel);
1482 *p_data << uint32(petFamily);
1485 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1487 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1488 uint32 item_id = GetUInt32Value(visualbase);
1489 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1490 SpellItemEnchantmentEntry const *enchant = NULL;
1492 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1494 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1495 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1496 break;
1499 if (proto != NULL)
1501 *p_data << uint32(proto->DisplayInfoID);
1502 *p_data << uint8(proto->InventoryType);
1503 *p_data << uint32(enchant ? enchant->aura_id : 0);
1505 else
1507 *p_data << uint32(0);
1508 *p_data << uint8(0);
1509 *p_data << uint32(0); // enchant?
1512 *p_data << uint32(0); // first bag display id
1513 *p_data << uint8(0); // first bag inventory type
1514 *p_data << uint32(0); // enchant?
1517 bool Player::ToggleAFK()
1519 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1521 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1523 // afk player not allowed in battleground
1524 if(state && InBattleGround())
1525 LeaveBattleground();
1527 return state;
1530 bool Player::ToggleDND()
1532 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1534 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1537 uint8 Player::chatTag() const
1539 // it's bitmask
1540 // 0x8 - ??
1541 // 0x4 - gm
1542 // 0x2 - dnd
1543 // 0x1 - afk
1544 if(isGMChat())
1545 return 4;
1546 else if(isDND())
1547 return 3;
1548 if(isAFK())
1549 return 1;
1550 else
1551 return 0;
1554 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1556 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1558 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1559 return false;
1562 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1563 Pet* pet = GetPet();
1565 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1567 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1568 // don't let gm level > 1 either
1569 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1570 return false;
1572 // client without expansion support
1573 if(GetSession()->Expansion() < mEntry->Expansion())
1575 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1577 if(GetTransport())
1578 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1580 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1582 return false; // normal client can't teleport to this map...
1584 else
1586 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1589 // if we were on a transport, leave
1590 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1592 m_transport->RemovePassenger(this);
1593 m_transport = NULL;
1594 m_movementInfo.t_x = 0.0f;
1595 m_movementInfo.t_y = 0.0f;
1596 m_movementInfo.t_z = 0.0f;
1597 m_movementInfo.t_o = 0.0f;
1598 m_movementInfo.t_time = 0;
1601 // The player was ported to another map and looses the duel immediately.
1602 // We have to perform this check before the teleport, otherwise the
1603 // ObjectAccessor won't find the flag.
1604 if (duel && GetMapId()!=mapid)
1606 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1607 if (obj)
1608 DuelComplete(DUEL_FLED);
1611 // reset movement flags at teleport, because player will continue move with these flags after teleport
1612 SetUnitMovementFlags(0);
1614 if ((GetMapId() == mapid) && (!m_transport))
1616 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1618 //same map, only remove pet if out of range for new position
1619 if(pet && !pet->IsWithinDist3d(x,y,z, OWNER_MAX_DISTANCE))
1620 UnsummonPetTemporaryIfAny();
1623 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1624 CombatStop();
1626 // this will be used instead of the current location in SaveToDB
1627 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1628 SetFallInformation(0, z);
1630 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1631 // at client packet MSG_MOVE_TELEPORT_ACK
1632 SetSemaphoreTeleportNear(true);
1633 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1634 if(!GetSession()->PlayerLogout())
1636 WorldPacket data;
1637 BuildTeleportAckMsg(&data, x, y, z, orientation);
1638 GetSession()->SendPacket(&data);
1641 else
1643 // far teleport to another map
1644 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1645 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1647 // Check enter rights before map getting to avoid creating instance copy for player
1648 // this check not dependent from map instance copy and same for all instance copies of selected map
1649 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1650 return false;
1652 // If the map is not created, assume it is possible to enter it.
1653 // It will be created in the WorldPortAck.
1654 Map *map = MapManager::Instance().FindMap(mapid);
1655 if (!map || map->CanEnter(this))
1657 SetSelection(0);
1659 CombatStop();
1661 ResetContestedPvP();
1663 // remove player from battleground on far teleport (when changing maps)
1664 if(BattleGround const* bg = GetBattleGround())
1666 // Note: at battleground join battleground id set before teleport
1667 // and we already will found "current" battleground
1668 // just need check that this is targeted map or leave
1669 if(bg->GetMapId() != mapid)
1670 LeaveBattleground(false); // don't teleport to entry point
1673 // remove pet on map change
1674 if (pet)
1675 UnsummonPetTemporaryIfAny();
1677 // remove all dyn objects
1678 RemoveAllDynObjects();
1680 // stop spellcasting
1681 // not attempt interrupt teleportation spell at caster teleport
1682 if(!(options & TELE_TO_SPELL))
1683 if(IsNonMeleeSpellCasted(true))
1684 InterruptNonMeleeSpells(true);
1686 if(!GetSession()->PlayerLogout())
1688 // send transfer packets
1689 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1690 data << uint32(mapid);
1691 if (m_transport)
1693 data << m_transport->GetEntry() << GetMapId();
1695 GetSession()->SendPacket(&data);
1697 data.Initialize(SMSG_NEW_WORLD, (20));
1698 if (m_transport)
1700 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1702 else
1704 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1706 GetSession()->SendPacket( &data );
1707 SendSavedInstances();
1709 // remove from old map now
1710 if(oldmap) oldmap->Remove(this, false);
1713 // new final coordinates
1714 float final_x = x;
1715 float final_y = y;
1716 float final_z = z;
1717 float final_o = orientation;
1719 if(m_transport)
1721 final_x += m_movementInfo.t_x;
1722 final_y += m_movementInfo.t_y;
1723 final_z += m_movementInfo.t_z;
1724 final_o += m_movementInfo.t_o;
1727 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1728 SetFallInformation(0, final_z);
1729 // if the player is saved before worldportack (at logout for example)
1730 // this will be used instead of the current location in SaveToDB
1732 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1734 // move packet sent by client always after far teleport
1735 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1736 SetSemaphoreTeleportFar(true);
1738 else
1739 return false;
1741 return true;
1744 void Player::AddToWorld()
1746 ///- Do not add/remove the player from the object storage
1747 ///- It will crash when updating the ObjectAccessor
1748 ///- The player should only be added when logging in
1749 Unit::AddToWorld();
1751 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1753 if(m_items[i])
1754 m_items[i]->AddToWorld();
1758 void Player::RemoveFromWorld()
1760 // cleanup
1761 if(IsInWorld())
1763 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1764 Uncharm();
1765 UnsummonAllTotems();
1766 RemoveMiniPet();
1767 RemoveGuardians();
1770 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1772 if(m_items[i])
1773 m_items[i]->RemoveFromWorld();
1776 ///- Do not add/remove the player from the object storage
1777 ///- It will crash when updating the ObjectAccessor
1778 ///- The player should only be removed when logging out
1779 Unit::RemoveFromWorld();
1782 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1784 float addRage;
1786 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1788 if(attacker)
1790 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1792 // talent who gave more rage on attack
1793 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1795 else
1797 addRage = damage/rageconversion*2.5;
1799 // Berserker Rage effect
1800 if(HasAura(18499,0))
1801 addRage *= 1.3;
1804 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1806 ModifyPower(POWER_RAGE, uint32(addRage*10));
1809 void Player::RegenerateAll()
1811 if (m_regenTimer != 0)
1812 return;
1813 uint32 regenDelay = 2000;
1815 // Not in combat or they have regeneration
1816 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1817 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1819 RegenerateHealth();
1820 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1822 Regenerate(POWER_RAGE);
1823 if(getClass() == CLASS_DEATH_KNIGHT)
1824 Regenerate(POWER_RUNIC_POWER);
1828 Regenerate( POWER_ENERGY );
1830 Regenerate( POWER_MANA );
1832 if(getClass() == CLASS_DEATH_KNIGHT)
1833 Regenerate( POWER_RUNE );
1835 m_regenTimer = regenDelay;
1838 void Player::Regenerate(Powers power)
1840 uint32 curValue = GetPower(power);
1841 uint32 maxValue = GetMaxPower(power);
1843 float addvalue = 0.0f;
1845 switch (power)
1847 case POWER_MANA:
1849 bool recentCast = IsUnderLastManaUseEffect();
1850 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1851 if (recentCast)
1853 // Mangos Updates Mana in intervals of 2s, which is correct
1854 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1856 else
1858 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1860 } break;
1861 case POWER_RAGE: // Regenerate rage
1863 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1864 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1865 } break;
1866 case POWER_ENERGY: // Regenerate energy (rogue)
1867 addvalue = 20;
1868 break;
1869 case POWER_RUNIC_POWER:
1871 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1872 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1873 } break;
1874 case POWER_RUNE:
1876 for(uint32 i = 0; i < MAX_RUNES; ++i)
1877 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1878 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1879 } break;
1880 case POWER_FOCUS:
1881 case POWER_HAPPINESS:
1882 case POWER_HEALTH:
1883 break;
1886 // Mana regen calculated in Player::UpdateManaRegen()
1887 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1888 if(power != POWER_MANA)
1890 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1891 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1892 if ((*i)->GetModifier()->m_miscvalue == power)
1893 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1896 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1898 curValue += uint32(addvalue);
1899 if (curValue > maxValue)
1900 curValue = maxValue;
1902 else
1904 if(curValue <= uint32(addvalue))
1905 curValue = 0;
1906 else
1907 curValue -= uint32(addvalue);
1909 SetPower(power, curValue);
1912 void Player::RegenerateHealth()
1914 uint32 curValue = GetHealth();
1915 uint32 maxValue = GetMaxHealth();
1917 if (curValue >= maxValue) return;
1919 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1921 float addvalue = 0.0f;
1923 // polymorphed case
1924 if ( IsPolymorphed() )
1925 addvalue = GetMaxHealth()/3;
1926 // normal regen case (maybe partly in combat case)
1927 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1929 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1930 if (!isInCombat())
1932 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1933 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1934 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1936 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1937 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1939 if(!IsStandState())
1940 addvalue *= 1.5;
1943 // always regeneration bonus (including combat)
1944 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1946 if(addvalue < 0)
1947 addvalue = 0;
1949 ModifyHealth(int32(addvalue));
1952 bool Player::CanInteractWithNPCs(bool alive) const
1954 if(alive && !isAlive())
1955 return false;
1956 if(isInFlight())
1957 return false;
1959 return true;
1962 Creature*
1963 Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
1965 // unit checks
1966 if (!guid)
1967 return NULL;
1969 if(!IsInWorld())
1970 return NULL;
1972 // exist (we need look pets also for some interaction (quest/etc)
1973 Creature *unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
1974 if (!unit)
1975 return NULL;
1977 // player check
1978 if(!CanInteractWithNPCs(!unit->isSpiritService()))
1979 return NULL;
1981 // appropriate npc type
1982 if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
1983 return NULL;
1985 // alive or spirit healer
1986 if(!unit->isAlive() && (!unit->isSpiritService() || isAlive() ))
1987 return NULL;
1989 // not allow interaction under control, but allow with own pets
1990 if(unit->GetCharmerGUID())
1991 return NULL;
1993 // not enemy
1994 if( unit->IsHostileTo(this))
1995 return NULL;
1997 // not unfriendly
1998 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
1999 if(factionTemplate->faction)
2000 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2001 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2002 return NULL;
2004 // not too far
2005 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2006 return NULL;
2008 return unit;
2011 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
2013 if(GameObject *go = GetMap()->GetGameObject(guid))
2015 if(go->GetGoType() == type)
2017 float maxdist;
2018 switch(type)
2020 // TODO: find out how the client calculates the maximal usage distance to spellless working
2021 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2022 case GAMEOBJECT_TYPE_GUILD_BANK:
2023 case GAMEOBJECT_TYPE_MAILBOX:
2024 maxdist = 10.0f;
2025 break;
2026 case GAMEOBJECT_TYPE_FISHINGHOLE:
2027 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2028 break;
2029 default:
2030 maxdist = INTERACTION_DISTANCE;
2031 break;
2034 if (go->IsWithinDistInMap(this, maxdist))
2035 return go;
2037 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,
2038 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2041 return NULL;
2044 bool Player::IsUnderWater() const
2046 return IsInWater() &&
2047 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2050 void Player::SetInWater(bool apply)
2052 if(m_isInWater==apply)
2053 return;
2055 //define player in water by opcodes
2056 //move player's guid into HateOfflineList of those mobs
2057 //which can't swim and move guid back into ThreatList when
2058 //on surface.
2059 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2060 m_isInWater = apply;
2062 // remove auras that need water/land
2063 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2065 getHostilRefManager().updateThreatTables();
2068 void Player::SetGameMaster(bool on)
2070 if(on)
2072 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2073 setFaction(35);
2074 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2076 if (Pet* pet = GetPet())
2078 pet->setFaction(35);
2079 pet->getHostilRefManager().setOnlineOfflineState(false);
2082 for (int8 i = 0; i < MAX_TOTEM; ++i)
2083 if(m_TotemSlot[i])
2084 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2085 totem->setFaction(35);
2087 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2088 ResetContestedPvP();
2090 getHostilRefManager().setOnlineOfflineState(false);
2091 CombatStopWithPets();
2093 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2095 else
2097 // restore phase
2098 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2099 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2101 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2102 setFactionForRace(getRace());
2103 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2105 if (Pet* pet = GetPet())
2107 pet->setFaction(getFaction());
2108 pet->getHostilRefManager().setOnlineOfflineState(true);
2111 for (int8 i = 0; i < MAX_TOTEM; ++i)
2112 if(m_TotemSlot[i])
2113 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
2114 totem->setFaction(getFaction());
2116 // restore FFA PvP Server state
2117 if(sWorld.IsFFAPvPRealm())
2118 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
2120 // restore FFA PvP area state, remove not allowed for GM mounts
2121 UpdateArea(m_areaUpdateId);
2123 getHostilRefManager().setOnlineOfflineState(true);
2126 ObjectAccessor::UpdateVisibilityForPlayer(this);
2129 void Player::SetGMVisible(bool on)
2131 if(on)
2133 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2135 // Reapply stealth/invisibility if active or show if not any
2136 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2137 SetVisibility(VISIBILITY_GROUP_STEALTH);
2138 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2139 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2140 else
2141 SetVisibility(VISIBILITY_ON);
2143 else
2145 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2147 SetAcceptWhispers(false);
2148 SetGameMaster(true);
2150 SetVisibility(VISIBILITY_OFF);
2154 bool Player::IsGroupVisibleFor(Player* p) const
2156 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2158 default: return IsInSameGroupWith(p);
2159 case 1: return IsInSameRaidWith(p);
2160 case 2: return GetTeam()==p->GetTeam();
2164 bool Player::IsInSameGroupWith(Player const* p) const
2166 return p==this || GetGroup() != NULL &&
2167 GetGroup() == p->GetGroup() &&
2168 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2171 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2172 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2173 void Player::UninviteFromGroup()
2175 Group* group = GetGroupInvite();
2176 if(!group)
2177 return;
2179 group->RemoveInvite(this);
2181 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2183 if(group->IsCreated())
2185 group->Disband(true);
2186 objmgr.RemoveGroup(group);
2188 else
2189 group->RemoveAllInvites();
2191 delete group;
2195 void Player::RemoveFromGroup(Group* group, uint64 guid)
2197 if(group)
2199 if (group->RemoveMember(guid, 0) <= 1)
2201 // group->Disband(); already disbanded in RemoveMember
2202 objmgr.RemoveGroup(group);
2203 delete group;
2204 // removemember sets the player's group pointer to NULL
2209 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2211 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2212 data << uint64(victim ? victim->GetGUID() : 0); // guid
2213 data << uint32(GivenXP+RestXP); // given experience
2214 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2215 if(victim)
2217 data << uint32(GivenXP); // experience without rested bonus
2218 data << float(1); // 1 - none 0 - 100% group bonus output
2220 data << uint8(0); // new 2.4.0
2221 GetSession()->SendPacket(&data);
2224 void Player::GiveXP(uint32 xp, Unit* victim)
2226 if ( xp < 1 )
2227 return;
2229 if(!isAlive())
2230 return;
2232 uint32 level = getLevel();
2234 // XP to money conversion processed in Player::RewardQuest
2235 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2236 return;
2238 // handle SPELL_AURA_MOD_XP_PCT auras
2239 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2240 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2241 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2243 // XP resting bonus for kill
2244 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2246 SendLogXPGain(xp,victim,rested_bonus_xp);
2248 uint32 curXP = GetUInt32Value(PLAYER_XP);
2249 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2250 uint32 newXP = curXP + xp + rested_bonus_xp;
2252 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2254 newXP -= nextLvlXP;
2256 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2257 GiveLevel(level + 1);
2259 level = getLevel();
2260 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2263 SetUInt32Value(PLAYER_XP, newXP);
2266 // Update player to next level
2267 // Current player experience not update (must be update by caller)
2268 void Player::GiveLevel(uint32 level)
2270 if ( level == getLevel() )
2271 return;
2273 PlayerLevelInfo info;
2274 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2276 PlayerClassLevelInfo classInfo;
2277 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2279 // send levelup info to client
2280 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2281 data << uint32(level);
2282 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2283 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2284 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2285 data << uint32(0);
2286 data << uint32(0);
2287 data << uint32(0);
2288 data << uint32(0);
2289 data << uint32(0);
2290 data << uint32(0);
2291 // end for
2292 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2293 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2295 GetSession()->SendPacket(&data);
2297 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(level));
2299 //update level, max level of skills
2300 if(getLevel()!= level)
2301 m_Played_time[1] = 0; // Level Played Time reset
2302 SetLevel(level);
2303 UpdateSkillsForLevel ();
2305 // save base values (bonuses already included in stored stats
2306 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2307 SetCreateStat(Stats(i), info.stats[i]);
2309 SetCreateHealth(classInfo.basehealth);
2310 SetCreateMana(classInfo.basemana);
2312 InitTalentForLevel();
2313 InitTaxiNodesForLevel();
2314 InitGlyphsForLevel();
2316 UpdateAllStats();
2318 // set current level health and mana/energy to maximum after applying all mods.
2319 SetHealth(GetMaxHealth());
2320 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2321 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2322 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2323 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2324 SetPower(POWER_FOCUS, 0);
2325 SetPower(POWER_HAPPINESS, 0);
2327 // update level to hunter/summon pet
2328 if (Pet* pet = GetPet())
2329 pet->SynchronizeLevelWithOwner();
2331 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2334 void Player::InitTalentForLevel()
2336 uint32 level = getLevel();
2337 // talents base at level diff ( talents = level - 9 but some can be used already)
2338 if(level < 10)
2340 // Remove all talent points
2341 if(m_usedTalentCount > 0) // Free any used talents
2343 resetTalents(true);
2344 SetFreeTalentPoints(0);
2347 else
2349 uint32 talentPointsForLevel = CalculateTalentsPoints();
2351 // if used more that have then reset
2352 if(m_usedTalentCount > talentPointsForLevel)
2354 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2355 resetTalents(true);
2356 else
2357 SetFreeTalentPoints(0);
2359 // else update amount of free points
2360 else
2361 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2365 void Player::InitStatsForLevel(bool reapplyMods)
2367 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2368 _RemoveAllStatBonuses();
2370 PlayerClassLevelInfo classInfo;
2371 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2373 PlayerLevelInfo info;
2374 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2376 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2377 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, objmgr.GetXPForLevel(getLevel()));
2379 UpdateSkillsForLevel ();
2381 // set default cast time multiplier
2382 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2384 // reset size before reapply auras
2385 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2387 // save base values (bonuses already included in stored stats
2388 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2389 SetCreateStat(Stats(i), info.stats[i]);
2391 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2392 SetStat(Stats(i), info.stats[i]);
2394 SetCreateHealth(classInfo.basehealth);
2396 //set create powers
2397 SetCreateMana(classInfo.basemana);
2399 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2401 InitStatBuffMods();
2403 //reset rating fields values
2404 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2405 SetUInt32Value(index, 0);
2407 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2408 for (int i = 0; i < 7; ++i)
2410 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2411 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2412 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2415 //reset attack power, damage and attack speed fields
2416 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2417 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2418 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2420 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2421 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2422 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2423 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2424 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2425 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2427 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2428 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2429 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2430 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2431 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2432 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2434 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2435 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2436 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2437 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2439 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2440 for (uint8 i = 0; i < 7; ++i)
2441 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2443 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2444 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2445 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2447 // Dodge percentage
2448 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2450 // set armor (resistance 0) to original value (create_agility*2)
2451 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2452 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2453 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2454 // set other resistance to original value (0)
2455 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2457 SetResistance(SpellSchools(i), 0);
2458 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2459 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2462 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2463 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2464 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2466 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2467 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2469 // Reset no reagent cost field
2470 for(int i = 0; i < 3; ++i)
2471 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2472 // Init data for form but skip reapply item mods for form
2473 InitDataForForm(reapplyMods);
2475 // save new stats
2476 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2477 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2479 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2481 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2482 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2484 // cleanup unit flags (will be re-applied if need at aura load).
2485 RemoveFlag( UNIT_FIELD_FLAGS,
2486 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2487 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2488 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2489 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2490 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2491 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2493 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2495 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2496 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2498 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2499 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2501 // restore if need some important flags
2502 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2504 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2505 _ApplyAllStatBonuses();
2507 // set current level health and mana/energy to maximum after applying all mods.
2508 SetHealth(GetMaxHealth());
2509 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2510 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2511 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2512 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2513 SetPower(POWER_FOCUS, 0);
2514 SetPower(POWER_HAPPINESS, 0);
2515 SetPower(POWER_RUNIC_POWER, 0);
2517 // update level to hunter/summon pet
2518 if (Pet* pet = GetPet())
2519 pet->SynchronizeLevelWithOwner();
2522 void Player::SendInitialSpells()
2524 time_t curTime = time(NULL);
2525 time_t infTime = curTime + MONTH/2;
2527 uint16 spellCount = 0;
2529 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2530 data << uint8(0);
2532 size_t countPos = data.wpos();
2533 data << uint16(spellCount); // spell count placeholder
2535 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2537 if(itr->second->state == PLAYERSPELL_REMOVED)
2538 continue;
2540 if(!itr->second->active || itr->second->disabled)
2541 continue;
2543 data << uint16(itr->first);
2544 data << uint16(0); // it's not slot id
2546 spellCount +=1;
2549 data.put<uint16>(countPos,spellCount); // write real count value
2551 uint16 spellCooldowns = m_spellCooldowns.size();
2552 data << uint16(spellCooldowns);
2553 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2555 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2556 if(!sEntry)
2557 continue;
2559 // not send infinity cooldown
2560 if(itr->second.end > infTime)
2561 continue;
2563 data << uint16(itr->first);
2565 time_t cooldown = 0;
2566 if(itr->second.end > curTime)
2567 cooldown = (itr->second.end-curTime)*IN_MILISECONDS;
2569 data << uint16(itr->second.itemid); // cast item id
2570 data << uint16(sEntry->Category); // spell category
2571 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2573 data << uint32(0); // cooldown
2574 data << uint32(cooldown); // category cooldown
2576 else
2578 data << uint32(cooldown); // cooldown
2579 data << uint32(0); // category cooldown
2583 GetSession()->SendPacket(&data);
2585 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2588 void Player::RemoveMail(uint32 id)
2590 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2592 if ((*itr)->messageID == id)
2594 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2595 m_mail.erase(itr);
2596 return;
2601 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2603 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2604 data << (uint32) mailId;
2605 data << (uint32) mailAction;
2606 data << (uint32) mailError;
2607 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2608 data << (uint32) equipError;
2609 else if( mailAction == MAIL_ITEM_TAKEN )
2611 data << (uint32) item_guid; // item guid low?
2612 data << (uint32) item_count; // item count?
2614 GetSession()->SendPacket(&data);
2617 void Player::SendNewMail()
2619 // deliver undelivered mail
2620 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2621 data << (uint32) 0;
2622 GetSession()->SendPacket(&data);
2625 void Player::UpdateNextMailTimeAndUnreads()
2627 // calculate next delivery time (min. from non-delivered mails
2628 // and recalculate unReadMail
2629 time_t cTime = time(NULL);
2630 m_nextMailDelivereTime = 0;
2631 unReadMails = 0;
2632 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2634 if((*itr)->deliver_time > cTime)
2636 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2637 m_nextMailDelivereTime = (*itr)->deliver_time;
2639 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2640 ++unReadMails;
2644 void Player::AddNewMailDeliverTime(time_t deliver_time)
2646 if(deliver_time <= time(NULL)) // ready now
2648 ++unReadMails;
2649 SendNewMail();
2651 else // not ready and no have ready mails
2653 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2654 m_nextMailDelivereTime = deliver_time;
2658 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2660 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2661 if (!spellInfo)
2663 // do character spell book cleanup (all characters)
2664 if(!IsInWorld() && !learning) // spell load case
2666 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2667 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2669 else
2670 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2672 return false;
2675 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2677 // do character spell book cleanup (all characters)
2678 if(!IsInWorld() && !learning) // spell load case
2680 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2681 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2683 else
2684 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2686 return false;
2689 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2691 bool dependent_set = false;
2692 bool disabled_case = false;
2693 bool superceded_old = false;
2695 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2696 if (itr != m_spells.end())
2698 uint32 next_active_spell_id = 0;
2699 // fix activate state for non-stackable low rank (and find next spell for !active case)
2700 if(!SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2702 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2703 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2705 if(HasSpell(next_itr->second))
2707 // high rank already known so this must !active
2708 active = false;
2709 next_active_spell_id = next_itr->second;
2710 break;
2715 // not do anything if already known in expected state
2716 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2717 itr->second->dependent == dependent && itr->second->disabled == disabled)
2719 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2720 itr->second->state = PLAYERSPELL_UNCHANGED;
2722 return false;
2725 // dependent spell known as not dependent, overwrite state
2726 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2728 itr->second->dependent = dependent;
2729 if (itr->second->state != PLAYERSPELL_NEW)
2730 itr->second->state = PLAYERSPELL_CHANGED;
2731 dependent_set = true;
2734 // update active state for known spell
2735 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2737 itr->second->active = active;
2739 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2740 itr->second->state = PLAYERSPELL_UNCHANGED;
2741 else if(itr->second->state != PLAYERSPELL_NEW)
2742 itr->second->state = PLAYERSPELL_CHANGED;
2744 if(active)
2746 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2747 CastSpell (this,spell_id,true);
2749 else if(IsInWorld())
2751 if(next_active_spell_id)
2753 // update spell ranks in spellbook and action bar
2754 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2755 data << uint16(spell_id);
2756 data << uint16(next_active_spell_id);
2757 GetSession()->SendPacket( &data );
2759 else
2761 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2762 data << uint16(spell_id);
2763 GetSession()->SendPacket(&data);
2767 return active; // learn (show in spell book if active now)
2770 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2772 if(itr->second->state != PLAYERSPELL_NEW)
2773 itr->second->state = PLAYERSPELL_CHANGED;
2774 itr->second->disabled = disabled;
2776 if(disabled)
2777 return false;
2779 disabled_case = true;
2781 else switch(itr->second->state)
2783 case PLAYERSPELL_UNCHANGED: // known saved spell
2784 return false;
2785 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2787 delete itr->second;
2788 m_spells.erase(itr);
2789 state = PLAYERSPELL_CHANGED;
2790 break; // need re-add
2792 default: // known not saved yet spell (new or modified)
2794 // can be in case spell loading but learned at some previous spell loading
2795 if(!IsInWorld() && !learning && !dependent_set)
2796 itr->second->state = PLAYERSPELL_UNCHANGED;
2798 return false;
2803 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2805 // talent: unlearn all other talent ranks (high and low)
2806 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2808 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2810 for(int i=0; i < MAX_TALENT_RANK; ++i)
2812 // skip learning spell and no rank spell case
2813 uint32 rankSpellId = talentInfo->RankID[i];
2814 if(!rankSpellId || rankSpellId==spell_id)
2815 continue;
2817 removeSpell(rankSpellId);
2821 // non talent spell: learn low ranks (recursive call)
2822 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2824 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
2825 addSpell(prev_spell,active,true,true,disabled);
2826 else // at normal learning
2827 learnSpell(prev_spell,true);
2830 PlayerSpell *newspell = new PlayerSpell;
2831 newspell->state = state;
2832 newspell->active = active;
2833 newspell->dependent = dependent;
2834 newspell->disabled = disabled;
2836 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2837 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2839 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
2841 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
2842 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
2843 if(!i_spellInfo) continue;
2845 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
2847 if(itr2->second->active)
2849 if(spellmgr.IsHighRankOfSpell(spell_id,itr2->first))
2851 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2853 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2854 data << uint16(itr2->first);
2855 data << uint16(spell_id);
2856 GetSession()->SendPacket( &data );
2859 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2860 itr2->second->active = false;
2861 if(itr2->second->state != PLAYERSPELL_NEW)
2862 itr2->second->state = PLAYERSPELL_CHANGED;
2863 superceded_old = true; // new spell replace old in action bars and spell book.
2865 else if(spellmgr.IsHighRankOfSpell(itr2->first,spell_id))
2867 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2869 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2870 data << uint16(spell_id);
2871 data << uint16(itr2->first);
2872 GetSession()->SendPacket( &data );
2875 // mark new spell as disable (not learned yet for client and will not learned)
2876 newspell->active = false;
2877 if(newspell->state != PLAYERSPELL_NEW)
2878 newspell->state = PLAYERSPELL_CHANGED;
2885 m_spells[spell_id] = newspell;
2887 // return false if spell disabled
2888 if (newspell->disabled)
2889 return false;
2892 uint32 talentCost = GetTalentSpellCost(spell_id);
2894 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2895 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2896 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2898 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2899 CastSpell(this, spell_id, true);
2901 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2902 else if (IsPassiveSpell(spell_id))
2904 if(IsNeedCastPassiveSpellAtLearn(spellInfo))
2905 CastSpell(this, spell_id, true);
2907 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2909 CastSpell(this, spell_id, true);
2910 return false;
2913 // update used talent points count
2914 m_usedTalentCount += talentCost;
2916 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2917 if(uint32 freeProfs = GetFreePrimaryProfessionPoints())
2919 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2920 SetFreePrimaryProfessions(freeProfs-1);
2923 // add dependent skills
2924 uint16 maxskill = GetMaxSkillValueForLevel();
2926 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2928 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2929 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2931 if(spellLearnSkill)
2933 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2934 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2936 if(skill_value < spellLearnSkill->value)
2937 skill_value = spellLearnSkill->value;
2939 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2941 if(skill_max_value < new_skill_max_value)
2942 skill_max_value = new_skill_max_value;
2944 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2946 else
2948 // not ranked skills
2949 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2951 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2952 if(!pSkill)
2953 continue;
2955 if(HasSkill(pSkill->id))
2956 continue;
2958 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2959 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2960 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
2962 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2964 case SKILL_RANGE_LANGUAGE:
2965 SetSkill(pSkill->id, 300, 300 );
2966 break;
2967 case SKILL_RANGE_LEVEL:
2968 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2969 break;
2970 case SKILL_RANGE_MONO:
2971 SetSkill(pSkill->id, 1, 1 );
2972 break;
2973 default:
2974 break;
2980 // learn dependent spells
2981 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2982 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2984 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2986 if(!itr2->second.autoLearned)
2988 if(!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
2989 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
2990 else // at normal learning
2991 learnSpell(itr2->second.spell,true);
2995 if(!GetSession()->PlayerLoading())
2997 // not ranked skills
2998 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3000 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3004 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3007 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3008 return active && !disabled && !superceded_old;
3011 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3013 bool need_cast = false;
3015 switch(spellInfo->Id)
3017 // some spells not have stance data expected cast at form change or present
3018 case 5420: need_cast = (m_form == FORM_TREE); break;
3019 case 5419: need_cast = (m_form == FORM_TRAVEL); break;
3020 case 7376: need_cast = (m_form == FORM_DEFENSIVESTANCE); break;
3021 case 7381: need_cast = (m_form == FORM_BERSERKERSTANCE); break;
3022 case 21156: need_cast = (m_form == FORM_BATTLESTANCE); break;
3023 case 21178: need_cast = (m_form == FORM_BEAR || m_form == FORM_DIREBEAR); break;
3024 case 33948: need_cast = (m_form == FORM_FLIGHT); break;
3025 case 34764: need_cast = (m_form == FORM_FLIGHT); break;
3026 case 40121: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3027 case 40122: need_cast = (m_form == FORM_FLIGHT_EPIC); break;
3028 // another spells have proper stance data
3029 default: need_cast = !spellInfo->Stances || m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))); break;
3032 //Check CasterAuraStates
3033 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3036 void Player::learnSpell(uint32 spell_id, bool dependent)
3038 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3040 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3041 bool active = disabled ? itr->second->active : true;
3043 bool learning = addSpell(spell_id,active,true,dependent,false);
3045 // learn all disabled higher ranks (recursive)
3046 if(disabled)
3048 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3049 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3051 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3052 if (iter != m_spells.end() && iter->second->disabled)
3053 learnSpell(i->second,false);
3057 // prevent duplicated entires in spell book, also not send if not in world (loading)
3058 if(!learning || !IsInWorld ())
3059 return;
3061 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3062 data << uint32(spell_id);
3063 GetSession()->SendPacket(&data);
3066 void Player::removeSpell(uint32 spell_id, bool disabled, bool update_action_bar_for_low_rank)
3068 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3069 if (itr == m_spells.end())
3070 return;
3072 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
3073 return;
3075 // unlearn non talent higher ranks (recursive)
3076 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
3077 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3078 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3079 removeSpell(itr2->second,disabled);
3081 bool cur_active = itr->second->active;
3082 bool cur_dependent = itr->second->dependent;
3084 if (disabled)
3086 itr->second->disabled = disabled;
3087 if(itr->second->state != PLAYERSPELL_NEW)
3088 itr->second->state = PLAYERSPELL_CHANGED;
3090 else
3092 if(itr->second->state == PLAYERSPELL_NEW)
3094 delete itr->second;
3095 m_spells.erase(itr);
3097 else
3098 itr->second->state = PLAYERSPELL_REMOVED;
3101 RemoveAurasDueToSpell(spell_id);
3103 // remove pet auras
3104 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
3105 RemovePetAura(petSpell);
3107 // free talent points
3108 uint32 talentCosts = GetTalentSpellCost(spell_id);
3109 if(talentCosts > 0)
3111 if(talentCosts < m_usedTalentCount)
3112 m_usedTalentCount -= talentCosts;
3113 else
3114 m_usedTalentCount = 0;
3117 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3118 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3120 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3121 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3122 SetFreePrimaryProfessions(freeProfs);
3125 // remove dependent skill
3126 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
3127 if(spellLearnSkill)
3129 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
3130 if(!prev_spell) // first rank, remove skill
3131 SetSkill(spellLearnSkill->skill,0,0);
3132 else
3134 // search prev. skill setting by spell ranks chain
3135 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
3136 while(!prevSkill && prev_spell)
3138 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
3139 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
3142 if(!prevSkill) // not found prev skill setting, remove skill
3143 SetSkill(spellLearnSkill->skill,0,0);
3144 else // set to prev. skill setting values
3146 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3147 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3149 if(skill_value > prevSkill->value)
3150 skill_value = prevSkill->value;
3152 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3154 if(skill_max_value > new_skill_max_value)
3155 skill_max_value = new_skill_max_value;
3157 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3162 else
3164 // not ranked skills
3165 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
3166 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
3168 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
3170 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3171 if(!pSkill)
3172 continue;
3174 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3175 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3176 (pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0 )
3178 // not reset skills for professions and racial abilities
3179 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3180 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
3181 continue;
3183 SetSkill(pSkill->id, 0, 0 );
3188 // remove dependent spells
3189 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
3190 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
3192 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
3193 removeSpell(itr2->second.spell, disabled);
3195 // activate lesser rank in spellbook/action bar, and cast it if need
3196 bool prev_activate = false;
3198 if(uint32 prev_id = spellmgr.GetPrevSpellInChain (spell_id))
3200 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3202 // if talent then lesser rank also talent and need learn
3203 if(talentCosts)
3204 learnSpell (prev_id,false);
3205 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3206 else if(cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
3208 // need manually update dependence state (learn spell ignore like attempts)
3209 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3210 if (prev_itr != m_spells.end())
3212 if(prev_itr->second->dependent != cur_dependent)
3214 prev_itr->second->dependent = cur_dependent;
3215 if(prev_itr->second->state != PLAYERSPELL_NEW)
3216 prev_itr->second->state = PLAYERSPELL_CHANGED;
3219 // now re-learn if need re-activate
3220 if(cur_active && !prev_itr->second->active)
3222 if(addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3224 if(update_action_bar_for_low_rank)
3226 // downgrade spell ranks in spellbook and action bar
3227 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
3228 data << uint16(spell_id);
3229 data << uint16(prev_id);
3230 GetSession()->SendPacket( &data );
3231 prev_activate = true;
3239 // remove from spell book if not replaced by lesser rank
3240 if(!prev_activate)
3242 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3243 data << uint16(spell_id);
3244 GetSession()->SendPacket(&data);
3249 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3251 m_spellCooldowns.erase(spell_id);
3253 if(update)
3255 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3256 data << uint32(spell_id);
3257 data << uint64(GetGUID());
3258 SendDirectMessage(&data);
3262 void Player::RemoveArenaSpellCooldowns()
3264 // remove cooldowns on spells that has < 15 min CD
3265 SpellCooldowns::iterator itr, next;
3266 // iterate spell cooldowns
3267 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3269 next = itr;
3270 ++next;
3271 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3272 // check if spellentry is present and if the cooldown is less than 15 mins
3273 if( entry &&
3274 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3275 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3277 // notify player
3278 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3279 data << uint32(itr->first);
3280 data << uint64(GetGUID());
3281 GetSession()->SendPacket(&data);
3282 // remove cooldown
3283 m_spellCooldowns.erase(itr);
3288 void Player::RemoveAllSpellCooldown()
3290 if(!m_spellCooldowns.empty())
3292 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3294 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
3295 data << uint32(itr->first);
3296 data << uint64(GetGUID());
3297 GetSession()->SendPacket(&data);
3299 m_spellCooldowns.clear();
3303 void Player::_LoadSpellCooldowns(QueryResult *result)
3305 // some cooldowns can be already set at aura loading...
3307 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3309 if(result)
3311 time_t curTime = time(NULL);
3315 Field *fields = result->Fetch();
3317 uint32 spell_id = fields[0].GetUInt32();
3318 uint32 item_id = fields[1].GetUInt32();
3319 time_t db_time = (time_t)fields[2].GetUInt64();
3321 if(!sSpellStore.LookupEntry(spell_id))
3323 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3324 continue;
3327 // skip outdated cooldown
3328 if(db_time <= curTime)
3329 continue;
3331 AddSpellCooldown(spell_id, item_id, db_time);
3333 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3335 while( result->NextRow() );
3337 delete result;
3341 void Player::_SaveSpellCooldowns()
3343 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3345 time_t curTime = time(NULL);
3346 time_t infTime = curTime + MONTH/2;
3348 // remove outdated and save active
3349 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3351 if(itr->second.end <= curTime)
3352 m_spellCooldowns.erase(itr++);
3353 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3355 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" UI64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3356 ++itr;
3358 else
3359 ++itr;
3363 uint32 Player::resetTalentsCost() const
3365 // The first time reset costs 1 gold
3366 if(m_resetTalentsCost < 1*GOLD)
3367 return 1*GOLD;
3368 // then 5 gold
3369 else if(m_resetTalentsCost < 5*GOLD)
3370 return 5*GOLD;
3371 // After that it increases in increments of 5 gold
3372 else if(m_resetTalentsCost < 10*GOLD)
3373 return 10*GOLD;
3374 else
3376 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3377 if(months > 0)
3379 // This cost will be reduced by a rate of 5 gold per month
3380 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3381 // to a minimum of 10 gold.
3382 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3384 else
3386 // After that it increases in increments of 5 gold
3387 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3388 // until it hits a cap of 50 gold.
3389 if(new_cost > 50*GOLD)
3390 new_cost = 50*GOLD;
3391 return new_cost;
3396 bool Player::resetTalents(bool no_cost)
3398 // not need after this call
3399 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3401 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3402 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3405 uint32 talentPointsForLevel = CalculateTalentsPoints();
3407 if (m_usedTalentCount == 0)
3409 SetFreeTalentPoints(talentPointsForLevel);
3410 return false;
3413 uint32 cost = 0;
3415 if(!no_cost)
3417 cost = resetTalentsCost();
3419 if (GetMoney() < cost)
3421 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3422 return false;
3426 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3428 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3430 if (!talentInfo) continue;
3432 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3434 if(!talentTabInfo)
3435 continue;
3437 // unlearn only talents for character class
3438 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3439 // to prevent unexpected lost normal learned spell skip another class talents
3440 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3441 continue;
3443 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3445 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3447 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3449 ++itr;
3450 continue;
3453 // remove learned spells (all ranks)
3454 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3456 // unlearn if first rank is talent or learned by talent
3457 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3459 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3460 itr = GetSpellMap().begin();
3461 continue;
3463 else
3464 ++itr;
3469 SetFreeTalentPoints(talentPointsForLevel);
3471 if(!no_cost)
3473 ModifyMoney(-(int32)cost);
3474 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3475 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3477 m_resetTalentsCost = cost;
3478 m_resetTalentsTime = time(NULL);
3481 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3482 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3483 /* when prev line will dropped use next line
3484 if(Pet* pet = GetPet())
3486 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3487 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3492 if(m_canTitanGrip)
3494 m_canTitanGrip = false;
3495 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3496 AutoUnequipOffhandIfNeed();
3499 return true;
3502 Mail* Player::GetMail(uint32 id)
3504 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3506 if ((*itr)->messageID == id)
3508 return (*itr);
3511 return NULL;
3514 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3516 if(target == this)
3518 Object::_SetCreateBits(updateMask, target);
3520 else
3522 for(uint16 index = 0; index < m_valuesCount; index++)
3524 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3525 updateMask->SetBit(index);
3530 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3532 if(target == this)
3534 Object::_SetUpdateBits(updateMask, target);
3536 else
3538 Object::_SetUpdateBits(updateMask, target);
3539 *updateMask &= updateVisualBits;
3543 void Player::InitVisibleBits()
3545 updateVisualBits.SetCount(PLAYER_END);
3547 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3548 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3549 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3550 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3551 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3552 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3553 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3554 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3555 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3556 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3557 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3558 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3559 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3560 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3561 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3562 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3563 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3564 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3565 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3566 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3567 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3568 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3569 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3570 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3571 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3572 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3573 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3574 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3575 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3576 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3577 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3578 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3579 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3580 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3581 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3582 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3583 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3584 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3585 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3586 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3587 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3588 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3589 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3590 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3591 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3592 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3593 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3594 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3595 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3596 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3597 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3598 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3599 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3600 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3601 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3603 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3604 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3605 updateVisualBits.SetBit(PLAYER_FLAGS);
3606 updateVisualBits.SetBit(PLAYER_GUILDID);
3607 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3608 updateVisualBits.SetBit(PLAYER_BYTES);
3609 updateVisualBits.SetBit(PLAYER_BYTES_2);
3610 updateVisualBits.SetBit(PLAYER_BYTES_3);
3611 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3612 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3614 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3615 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3616 updateVisualBits.SetBit(i);
3618 // Players visible items are not inventory stuff
3619 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3621 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3623 // item creator
3624 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3625 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3627 // item entry
3628 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3630 // item enchantments
3631 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3632 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3634 // random properties
3635 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3636 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3637 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3640 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3643 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3645 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3647 if(m_items[i] == NULL)
3648 continue;
3650 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3653 if(target == this)
3655 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3657 if(m_items[i] == NULL)
3658 continue;
3660 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3662 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3664 if(m_items[i] == NULL)
3665 continue;
3667 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3671 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3674 void Player::DestroyForPlayer( Player *target ) const
3676 Unit::DestroyForPlayer( target );
3678 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3680 if(m_items[i] == NULL)
3681 continue;
3683 m_items[i]->DestroyForPlayer( target );
3686 if(target == this)
3688 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3690 if(m_items[i] == NULL)
3691 continue;
3693 m_items[i]->DestroyForPlayer( target );
3695 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3697 if(m_items[i] == NULL)
3698 continue;
3700 m_items[i]->DestroyForPlayer( target );
3705 bool Player::HasSpell(uint32 spell) const
3707 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3708 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3709 !itr->second->disabled);
3712 bool Player::HasActiveSpell(uint32 spell) const
3714 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3715 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3716 itr->second->active && !itr->second->disabled);
3719 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3721 if (!trainer_spell)
3722 return TRAINER_SPELL_RED;
3724 if (!trainer_spell->learnedSpell)
3725 return TRAINER_SPELL_RED;
3727 // known spell
3728 if(HasSpell(trainer_spell->learnedSpell))
3729 return TRAINER_SPELL_GRAY;
3731 // check race/class requirement
3732 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3733 return TRAINER_SPELL_RED;
3735 // check level requirement
3736 if(getLevel() < trainer_spell->reqLevel)
3737 return TRAINER_SPELL_RED;
3739 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3741 // check prev.rank requirement
3742 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3743 return TRAINER_SPELL_RED;
3745 // check additional spell requirement
3746 if(spell_chain->req && !HasSpell(spell_chain->req))
3747 return TRAINER_SPELL_RED;
3750 // check skill requirement
3751 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3752 return TRAINER_SPELL_RED;
3754 // exist, already checked at loading
3755 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3757 // secondary prof. or not prof. spell
3758 uint32 skill = spell->EffectMiscValue[1];
3760 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3761 return TRAINER_SPELL_GREEN;
3763 // check primary prof. limit
3764 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3765 return TRAINER_SPELL_GREEN_DISABLED;
3767 return TRAINER_SPELL_GREEN;
3770 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3772 uint32 guid = GUID_LOPART(playerguid);
3774 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3775 // bones will be deleted by corpse/bones deleting thread shortly
3776 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3778 // remove from guild
3779 uint32 guildId = GetGuildIdFromDB(playerguid);
3780 if(guildId != 0)
3782 Guild* guild = objmgr.GetGuildById(guildId);
3783 if(guild)
3784 guild->DelMember(guid);
3787 // remove from arena teams
3788 LeaveAllArenaTeams(playerguid);
3790 // the player was uninvited already on logout so just remove from group
3791 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3792 if(resultGroup)
3794 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3795 delete resultGroup;
3796 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3797 if(group)
3799 RemoveFromGroup(group, playerguid);
3803 // remove signs from petitions (also remove petitions if owner);
3804 RemovePetitionsAndSigns(playerguid, 10);
3806 // return back all mails with COD and Item 0 1 2 3 4 5 6
3807 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);
3808 if(resultMail)
3812 Field *fields = resultMail->Fetch();
3814 uint32 mail_id = fields[0].GetUInt32();
3815 uint16 mailTemplateId= fields[1].GetUInt16();
3816 uint32 sender = fields[2].GetUInt32();
3817 std::string subject = fields[3].GetCppString();
3818 uint32 itemTextId = fields[4].GetUInt32();
3819 uint32 money = fields[5].GetUInt32();
3820 bool has_items = fields[6].GetBool();
3822 //we can return mail now
3823 //so firstly delete the old one
3824 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3826 MailItemsInfo mi;
3827 if(has_items)
3829 // data needs to be at first place for Item::LoadFromDB
3830 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);
3831 if(resultItems)
3835 Field *fields2 = resultItems->Fetch();
3837 uint32 item_guidlow = fields2[1].GetUInt32();
3838 uint32 item_template = fields2[2].GetUInt32();
3840 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3841 if(!itemProto)
3843 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3844 continue;
3847 Item *pItem = NewItemOrBag(itemProto);
3848 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3850 pItem->FSetState(ITEM_REMOVED);
3851 pItem->SaveToDB(); // it also deletes item object !
3852 continue;
3855 mi.AddItem(item_guidlow, item_template, pItem);
3857 while (resultItems->NextRow());
3859 delete resultItems;
3863 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3865 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3867 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3869 while (resultMail->NextRow());
3871 delete resultMail;
3874 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3875 // Get guids of character's pets, will deleted in transaction
3876 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3878 // NOW we can finally clear other DB data related to character
3879 CharacterDatabase.BeginTransaction();
3880 if (resultPets)
3884 Field *fields3 = resultPets->Fetch();
3885 uint32 petguidlow = fields3[0].GetUInt32();
3886 Pet::DeleteFromDB(petguidlow);
3887 } while (resultPets->NextRow());
3888 delete resultPets;
3891 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3892 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3893 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3894 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3895 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3896 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3897 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3898 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3899 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3900 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3901 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3902 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3903 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3904 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3905 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3906 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3907 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3908 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3909 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3910 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3911 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3912 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3913 CharacterDatabase.CommitTransaction();
3915 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3916 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3919 void Player::SetMovement(PlayerMovementType pType)
3921 WorldPacket data;
3922 switch(pType)
3924 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3925 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3926 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3927 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3928 default:
3929 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3930 return;
3932 data.append(GetPackGUID());
3933 data << uint32(0);
3934 GetSession()->SendPacket( &data );
3937 /* Preconditions:
3938 - a resurrectable corpse must not be loaded for the player (only bones)
3939 - the player must be in world
3941 void Player::BuildPlayerRepop()
3943 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3944 data.append(GetPackGUID());
3945 GetSession()->SendPacket(&data);
3947 if(getRace() == RACE_NIGHTELF)
3948 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)
3949 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3951 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3952 // there must be SMSG.STOP_MIRROR_TIMER
3953 // there we must send 888 opcode
3955 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3956 if(GetCorpse())
3958 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3959 assert(false);
3962 // create a corpse and place it at the player's location
3963 CreateCorpse();
3964 Corpse *corpse = GetCorpse();
3965 if(!corpse)
3967 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3968 return;
3970 GetMap()->Add(corpse);
3972 // convert player body to ghost
3973 SetHealth( 1 );
3975 SetMovement(MOVE_WATER_WALK);
3976 if(!GetSession()->isLogingOut())
3977 SetMovement(MOVE_UNROOT);
3979 // BG - remove insignia related
3980 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3982 SendCorpseReclaimDelay();
3984 // to prevent cheating
3985 corpse->ResetGhostTime();
3987 StopMirrorTimers(); //disable timers(bars)
3989 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3991 // set and clear other
3992 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3995 void Player::SendDelayResponse(const uint32 ml_seconds)
3997 //FIXME: is this delay time arg really need? 50msec by default in code
3998 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3999 data << (uint32)time(NULL);
4000 data << (uint32)0;
4001 GetSession()->SendPacket( &data );
4004 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4006 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4007 data << uint32(-1);
4008 data << float(0);
4009 data << float(0);
4010 data << float(0);
4011 GetSession()->SendPacket(&data);
4013 // speed change, land walk
4015 // remove death flag + set aura
4016 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4017 if(getRace() == RACE_NIGHTELF)
4018 RemoveAurasDueToSpell(20584); // speed bonuses
4019 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4021 setDeathState(ALIVE);
4023 SetMovement(MOVE_LAND_WALK);
4024 SetMovement(MOVE_UNROOT);
4026 m_deathTimer = 0;
4028 // set health/powers (0- will be set in caller)
4029 if(restore_percent>0.0f)
4031 SetHealth(uint32(GetMaxHealth()*restore_percent));
4032 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4033 SetPower(POWER_RAGE, 0);
4034 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4037 // trigger update zone for alive state zone updates
4038 uint32 newzone, newarea;
4039 GetZoneAndAreaId(newzone,newarea);
4040 UpdateZone(newzone,newarea);
4042 // update visibility
4043 ObjectAccessor::UpdateVisibilityForPlayer(this);
4045 if(!applySickness)
4046 return;
4048 //Characters from level 1-10 are not affected by resurrection sickness.
4049 //Characters from level 11-19 will suffer from one minute of sickness
4050 //for each level they are above 10.
4051 //Characters level 20 and up suffer from ten minutes of sickness.
4052 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4054 if(int32(getLevel()) >= startLevel)
4056 // set resurrection sickness
4057 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4059 // not full duration
4060 if(int32(getLevel()) < startLevel+9)
4062 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4064 for(int i =0; i < 3; ++i)
4066 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4068 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4069 Aur->SendAuraUpdate(false);
4076 void Player::KillPlayer()
4078 SetMovement(MOVE_ROOT);
4080 StopMirrorTimers(); //disable timers(bars)
4082 setDeathState(CORPSE);
4083 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4085 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4086 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4088 // 6 minutes until repop at graveyard
4089 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4091 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4093 // don't create corpse at this moment, player might be falling
4095 // update visibility
4096 ObjectAccessor::UpdateObjectVisibility(this);
4099 void Player::CreateCorpse()
4101 // prevent existence 2 corpse for player
4102 SpawnCorpseBones();
4104 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4106 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4107 SetPvPDeath(false);
4109 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4111 delete corpse;
4112 return;
4115 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4116 _pb = GetUInt32Value(PLAYER_BYTES);
4117 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4119 uint8 race = (uint8)(_uf);
4120 uint8 skin = (uint8)(_pb);
4121 uint8 face = (uint8)(_pb >> 8);
4122 uint8 hairstyle = (uint8)(_pb >> 16);
4123 uint8 haircolor = (uint8)(_pb >> 24);
4124 uint8 facialhair = (uint8)(_pb2);
4126 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4127 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4129 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4130 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4132 uint32 flags = CORPSE_FLAG_UNK2;
4133 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4134 flags |= CORPSE_FLAG_HIDE_HELM;
4135 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4136 flags |= CORPSE_FLAG_HIDE_CLOAK;
4137 if(InBattleGround() && !InArena())
4138 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4139 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4141 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4143 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4145 uint32 iDisplayID;
4146 uint16 iIventoryType;
4147 uint32 _cfi;
4148 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4150 if(m_items[i])
4152 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4153 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4155 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4156 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4160 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4161 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4162 assert(entry);
4163 if(entry->map_type != MAP_BATTLEGROUND)
4164 corpse->SaveToDB();
4166 // register for player, but not show
4167 ObjectAccessor::Instance().AddCorpse(corpse);
4170 void Player::SpawnCorpseBones()
4172 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4173 SaveToDB(); // prevent loading as ghost without corpse
4176 Corpse* Player::GetCorpse() const
4178 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4181 void Player::DurabilityLossAll(double percent, bool inventory)
4183 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4184 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4185 DurabilityLoss(pItem,percent);
4187 if(inventory)
4189 // bags not have durability
4190 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4192 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4193 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4194 DurabilityLoss(pItem,percent);
4196 // keys not have durability
4197 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4199 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4200 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4201 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4202 if(Item* pItem = GetItemByPos( i, j ))
4203 DurabilityLoss(pItem,percent);
4207 void Player::DurabilityLoss(Item* item, double percent)
4209 if(!item )
4210 return;
4212 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4214 if(!pMaxDurability)
4215 return;
4217 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4219 if(pDurabilityLoss < 1 )
4220 pDurabilityLoss = 1;
4222 DurabilityPointsLoss(item,pDurabilityLoss);
4225 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4227 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4228 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4229 DurabilityPointsLoss(pItem,points);
4231 if(inventory)
4233 // bags not have durability
4234 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4236 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4237 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4238 DurabilityPointsLoss(pItem,points);
4240 // keys not have durability
4241 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4243 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4244 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4245 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4246 if(Item* pItem = GetItemByPos( i, j ))
4247 DurabilityPointsLoss(pItem,points);
4251 void Player::DurabilityPointsLoss(Item* item, int32 points)
4253 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4254 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4255 int32 pNewDurability = pOldDurability - points;
4257 if (pNewDurability < 0)
4258 pNewDurability = 0;
4259 else if (pNewDurability > pMaxDurability)
4260 pNewDurability = pMaxDurability;
4262 if (pOldDurability != pNewDurability)
4264 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4265 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4266 _ApplyItemMods(item,item->GetSlot(), false);
4268 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4270 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4271 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4272 _ApplyItemMods(item,item->GetSlot(), true);
4274 item->SetState(ITEM_CHANGED, this);
4278 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4280 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4281 DurabilityPointsLoss(pItem,1);
4284 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4286 uint32 TotalCost = 0;
4287 // equipped, backpack, bags itself
4288 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4289 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4291 // bank, buyback and keys not repaired
4293 // items in inventory bags
4294 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4295 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4296 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4297 return TotalCost;
4300 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4302 Item* item = GetItemByPos(pos);
4304 uint32 TotalCost = 0;
4305 if(!item)
4306 return TotalCost;
4308 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4309 if(!maxDurability)
4310 return TotalCost;
4312 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4314 if(cost)
4316 uint32 LostDurability = maxDurability - curDurability;
4317 if(LostDurability>0)
4319 ItemPrototype const *ditemProto = item->GetProto();
4321 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4322 if(!dcost)
4324 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4325 return TotalCost;
4328 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4329 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4330 if(!dQualitymodEntry)
4332 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4333 return TotalCost;
4336 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4337 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4339 costs = uint32(costs * discountMod);
4341 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4342 costs = 1;
4344 if (guildBank)
4346 if (GetGuildId()==0)
4348 DEBUG_LOG("You are not member of a guild");
4349 return TotalCost;
4352 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4353 if (!pGuild)
4354 return TotalCost;
4356 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4358 DEBUG_LOG("You do not have rights to withdraw for repairs");
4359 return TotalCost;
4362 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4364 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4365 return TotalCost;
4368 if (pGuild->GetGuildBankMoney() < costs)
4370 DEBUG_LOG("There is not enough money in bank");
4371 return TotalCost;
4374 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4375 TotalCost = costs;
4377 else if (GetMoney() < costs)
4379 DEBUG_LOG("You do not have enough money");
4380 return TotalCost;
4382 else
4383 ModifyMoney( -int32(costs) );
4387 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4388 item->SetState(ITEM_CHANGED, this);
4390 // reapply mods for total broken and repaired item if equipped
4391 if(IsEquipmentPos(pos) && !curDurability)
4392 _ApplyItemMods(item,pos & 255, true);
4393 return TotalCost;
4396 void Player::RepopAtGraveyard()
4398 // note: this can be called also when the player is alive
4399 // for example from WorldSession::HandleMovementOpcodes
4401 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4403 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4404 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4406 ResurrectPlayer(0.5f);
4407 SpawnCorpseBones();
4410 WorldSafeLocsEntry const *ClosestGrave = NULL;
4412 // Special handle for battleground maps
4413 if( BattleGround *bg = GetBattleGround() )
4414 ClosestGrave = bg->GetClosestGraveYard(this);
4415 else
4416 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4418 // stop countdown until repop
4419 m_deathTimer = 0;
4421 // if no grave found, stay at the current location
4422 // and don't show spirit healer location
4423 if(ClosestGrave)
4425 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4426 if(isDead()) // not send if alive, because it used in TeleportTo()
4428 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4429 data << ClosestGrave->map_id;
4430 data << ClosestGrave->x;
4431 data << ClosestGrave->y;
4432 data << ClosestGrave->z;
4433 GetSession()->SendPacket(&data);
4438 void Player::JoinedChannel(Channel *c)
4440 m_channels.push_back(c);
4443 void Player::LeftChannel(Channel *c)
4445 m_channels.remove(c);
4448 void Player::CleanupChannels()
4450 while(!m_channels.empty())
4452 Channel* ch = *m_channels.begin();
4453 m_channels.erase(m_channels.begin()); // remove from player's channel list
4454 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4455 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4456 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4459 sLog.outDebug("Player: channels cleaned up!");
4462 void Player::UpdateLocalChannels(uint32 newZone )
4464 if(m_channels.empty())
4465 return;
4467 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4468 if(!current_zone)
4469 return;
4471 ChannelMgr* cMgr = channelMgr(GetTeam());
4472 if(!cMgr)
4473 return;
4475 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4477 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4479 next = i; ++next;
4481 // skip non built-in channels
4482 if(!(*i)->IsConstant())
4483 continue;
4485 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4486 if(!ch)
4487 continue;
4489 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4490 continue;
4492 // new channel
4493 char new_channel_name_buf[100];
4494 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4495 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4497 if((*i)!=new_channel)
4499 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4501 // leave old channel
4502 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4503 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4504 LeftChannel(*i); // remove from player's channel list
4505 cMgr->LeftChannel(name); // delete if empty
4508 sLog.outDebug("Player: channels cleaned up!");
4511 void Player::LeaveLFGChannel()
4513 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4515 if((*i)->IsLFG())
4517 (*i)->Leave(GetGUID());
4518 break;
4523 void Player::UpdateDefense()
4525 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4527 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4529 // update dependent from defense skill part
4530 UpdateDefenseBonusesMod();
4534 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4536 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4538 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4539 return;
4542 float val = 1.0f;
4544 switch(modType)
4546 case FLAT_MOD:
4547 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4548 break;
4549 case PCT_MOD:
4550 if(amount <= -100.0f)
4551 amount = -200.0f;
4553 val = (100.0f + amount) / 100.0f;
4554 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4555 break;
4558 if(!CanModifyStats())
4559 return;
4561 switch(modGroup)
4563 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4564 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4565 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4566 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4567 default: break;
4571 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4573 if(modGroup >= BASEMOD_END || modType > MOD_END)
4575 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4576 return 0.0f;
4579 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4580 return 0.0f;
4582 return m_auraBaseMod[modGroup][modType];
4585 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4587 if(modGroup >= BASEMOD_END)
4589 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4590 return 0.0f;
4593 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4594 return 0.0f;
4596 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4599 uint32 Player::GetShieldBlockValue() const
4601 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4603 value = (value < 0) ? 0 : value;
4605 return uint32(value);
4608 float Player::GetMeleeCritFromAgility()
4610 uint32 level = getLevel();
4611 uint32 pclass = getClass();
4613 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4615 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4616 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4617 if (critBase==NULL || critRatio==NULL)
4618 return 0.0f;
4620 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4621 return crit*100.0f;
4624 float Player::GetDodgeFromAgility()
4626 // Table for base dodge values
4627 float dodge_base[MAX_CLASSES] = {
4628 0.0075f, // Warrior
4629 0.00652f, // Paladin
4630 -0.0545f, // Hunter
4631 -0.0059f, // Rogue
4632 0.03183f, // Priest
4633 0.0114f, // DK
4634 0.0167f, // Shaman
4635 0.034575f, // Mage
4636 0.02011f, // Warlock
4637 0.0f, // ??
4638 -0.0187f // Druid
4640 // Crit/agility to dodge/agility coefficient multipliers
4641 float crit_to_dodge[MAX_CLASSES] = {
4642 1.1f, // Warrior
4643 1.0f, // Paladin
4644 1.6f, // Hunter
4645 2.0f, // Rogue
4646 1.0f, // Priest
4647 1.0f, // DK?
4648 1.0f, // Shaman
4649 1.0f, // Mage
4650 1.0f, // Warlock
4651 0.0f, // ??
4652 1.7f // Druid
4655 uint32 level = getLevel();
4656 uint32 pclass = getClass();
4658 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4660 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4661 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4662 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4663 return 0.0f;
4665 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4666 return dodge*100.0f;
4669 float Player::GetSpellCritFromIntellect()
4671 uint32 level = getLevel();
4672 uint32 pclass = getClass();
4674 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4676 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4677 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4678 if (critBase==NULL || critRatio==NULL)
4679 return 0.0f;
4681 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4682 return crit*100.0f;
4685 float Player::GetRatingCoefficient(CombatRating cr) const
4687 uint32 level = getLevel();
4689 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4691 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4692 if (Rating == NULL)
4693 return 1.0f; // By default use minimum coefficient (not must be called)
4695 return Rating->ratio;
4698 float Player::GetRatingBonusValue(CombatRating cr) const
4700 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4703 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4705 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4706 if (melee>33.0f) melee = 33.0f;
4707 return uint32 (melee * damage /100.0f);
4710 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4712 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4713 if (ranged>33.0f) ranged=33.0f;
4714 return uint32 (ranged * damage /100.0f);
4717 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4719 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4720 // In wow script resilience limited to 33%
4721 if (spell>33.0f)
4722 spell = 33.0f;
4723 return uint32 (spell * damage / 100.0f);
4726 uint32 Player::GetDotDamageReduction(uint32 damage) const
4728 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4729 // Dot resilience not limited (limit it by 100%)
4730 if (spellDot > 100.0f)
4731 spellDot = 100.0f;
4732 return uint32 (spellDot * damage / 100.0f);
4735 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4737 switch (attType)
4739 case BASE_ATTACK:
4740 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4741 case OFF_ATTACK:
4742 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4743 default:
4744 break;
4746 return 0.0f;
4749 float Player::OCTRegenHPPerSpirit()
4751 uint32 level = getLevel();
4752 uint32 pclass = getClass();
4754 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4756 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4757 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4758 if (baseRatio==NULL || moreRatio==NULL)
4759 return 0.0f;
4761 // Formula from PaperDollFrame script
4762 float spirit = GetStat(STAT_SPIRIT);
4763 float baseSpirit = spirit;
4764 if (baseSpirit>50) baseSpirit = 50;
4765 float moreSpirit = spirit - baseSpirit;
4766 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4767 return regen;
4770 float Player::OCTRegenMPPerSpirit()
4772 uint32 level = getLevel();
4773 uint32 pclass = getClass();
4775 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4777 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4778 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4779 if (moreRatio==NULL)
4780 return 0.0f;
4782 // Formula get from PaperDollFrame script
4783 float spirit = GetStat(STAT_SPIRIT);
4784 float regen = spirit * moreRatio->ratio;
4785 return regen;
4788 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4790 m_baseRatingValue[cr]+=(apply ? value : -value);
4792 int32 amount = uint32(m_baseRatingValue[cr]);
4793 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4794 // stat used stored in miscValueB for this aura
4795 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4796 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4797 if ((*i)->GetMiscValue() & (1<<cr))
4798 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4799 if (amount < 0)
4800 amount = 0;
4801 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4803 float RatingCoeffecient = GetRatingCoefficient(cr);
4804 float RatingChange = 0.0f;
4806 bool affectStats = CanModifyStats();
4808 switch (cr)
4810 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4811 case CR_DEFENSE_SKILL:
4812 UpdateDefenseBonusesMod();
4813 break;
4814 case CR_DODGE:
4815 UpdateDodgePercentage();
4816 break;
4817 case CR_PARRY:
4818 UpdateParryPercentage();
4819 break;
4820 case CR_BLOCK:
4821 UpdateBlockPercentage();
4822 break;
4823 case CR_HIT_MELEE:
4824 UpdateMeleeHitChances();
4825 break;
4826 case CR_HIT_RANGED:
4827 UpdateRangedHitChances();
4828 break;
4829 case CR_HIT_SPELL:
4830 UpdateSpellHitChances();
4831 break;
4832 case CR_CRIT_MELEE:
4833 if(affectStats)
4835 UpdateCritPercentage(BASE_ATTACK);
4836 UpdateCritPercentage(OFF_ATTACK);
4838 break;
4839 case CR_CRIT_RANGED:
4840 if(affectStats)
4841 UpdateCritPercentage(RANGED_ATTACK);
4842 break;
4843 case CR_CRIT_SPELL:
4844 if(affectStats)
4845 UpdateAllSpellCritChances();
4846 break;
4847 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4848 case CR_HIT_TAKEN_RANGED:
4849 break;
4850 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4851 break;
4852 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4853 case CR_CRIT_TAKEN_RANGED:
4854 break;
4855 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4856 break;
4857 case CR_HASTE_MELEE:
4858 RatingChange = value / RatingCoeffecient;
4859 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4860 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4861 break;
4862 case CR_HASTE_RANGED:
4863 RatingChange = value / RatingCoeffecient;
4864 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4865 break;
4866 case CR_HASTE_SPELL:
4867 RatingChange = value / RatingCoeffecient;
4868 ApplyCastTimePercentMod(RatingChange,apply);
4869 break;
4870 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4871 case CR_WEAPON_SKILL_OFFHAND:
4872 case CR_WEAPON_SKILL_RANGED:
4873 break;
4874 case CR_EXPERTISE:
4875 if(affectStats)
4877 UpdateExpertise(BASE_ATTACK);
4878 UpdateExpertise(OFF_ATTACK);
4880 break;
4881 case CR_ARMOR_PENETRATION:
4882 break;
4886 void Player::SetRegularAttackTime()
4888 for(int i = 0; i < MAX_ATTACK; ++i)
4890 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4891 if(tmpitem && !tmpitem->IsBroken())
4893 ItemPrototype const *proto = tmpitem->GetProto();
4894 if(proto->Delay)
4895 SetAttackTime(WeaponAttackType(i), proto->Delay);
4896 else
4897 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4902 //skill+step, checking for max value
4903 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4905 if(!skill_id)
4906 return false;
4908 uint16 i=0;
4909 for (; i < PLAYER_MAX_SKILLS; ++i)
4910 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4911 break;
4913 if(i>=PLAYER_MAX_SKILLS)
4914 return false;
4916 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4917 uint32 value = SKILL_VALUE(data);
4918 uint32 max = SKILL_MAX(data);
4920 if ((!max) || (!value) || (value >= max))
4921 return false;
4923 if (value*512 < max*urand(0,512))
4925 uint32 new_value = value+step;
4926 if(new_value > max)
4927 new_value = max;
4929 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4930 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4931 return true;
4934 return false;
4937 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4939 if ( SkillValue >= GrayLevel )
4940 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4941 if ( SkillValue >= GreenLevel )
4942 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4943 if ( SkillValue >= YellowLevel )
4944 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4945 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4948 bool Player::UpdateCraftSkill(uint32 spellid)
4950 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4952 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4953 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4955 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4957 if(_spell_idx->second->skillId)
4959 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4961 // Alchemy Discoveries here
4962 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4963 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4965 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4966 learnSpell(discoveredSpell,false);
4969 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4971 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4972 _spell_idx->second->max_value,
4973 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4974 _spell_idx->second->min_value),
4975 craft_skill_gain);
4978 return false;
4981 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4983 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4985 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4987 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4988 switch (SkillId)
4990 case SKILL_HERBALISM:
4991 case SKILL_LOCKPICKING:
4992 case SKILL_JEWELCRAFTING:
4993 case SKILL_INSCRIPTION:
4994 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4995 case SKILL_SKINNING:
4996 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4997 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4998 else
4999 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5000 case SKILL_MINING:
5001 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5002 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5003 else
5004 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5006 return false;
5009 bool Player::UpdateFishingSkill()
5011 sLog.outDebug("UpdateFishingSkill");
5013 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5015 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5017 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5019 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5022 // levels sync. with spell requirement for skill levels to learn
5023 // bonus abilities in sSkillLineAbilityStore
5024 // Used only to avoid scan DBC at each skill grow
5025 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5027 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5029 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5030 if ( !SkillId )
5031 return false;
5033 if(Chance <= 0) // speedup in 0 chance case
5035 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5036 return false;
5039 uint16 i=0;
5040 for (; i < PLAYER_MAX_SKILLS; ++i)
5041 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5042 if ( i >= PLAYER_MAX_SKILLS )
5043 return false;
5045 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5046 uint16 SkillValue = SKILL_VALUE(data);
5047 uint16 MaxValue = SKILL_MAX(data);
5049 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5050 return false;
5052 int32 Roll = irand(1,1000);
5054 if ( Roll <= Chance )
5056 uint32 new_value = SkillValue+step;
5057 if(new_value > MaxValue)
5058 new_value = MaxValue;
5060 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5061 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5063 if((SkillValue < *bsl && new_value >= *bsl))
5065 learnSkillRewardedSpells( SkillId, new_value);
5066 break;
5069 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5070 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5071 return true;
5074 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5075 return false;
5078 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5080 // no skill gain in pvp
5081 Unit *pVictim = getVictim();
5082 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5083 return;
5085 if(IsInFeralForm())
5086 return; // always maximized SKILL_FERAL_COMBAT in fact
5088 if(m_form == FORM_TREE)
5089 return; // use weapon but not skill up
5091 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5093 switch(attType)
5095 case BASE_ATTACK:
5097 Item *tmpitem = GetWeaponForAttack(attType,true);
5099 if (!tmpitem)
5100 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5101 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5102 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5103 break;
5105 case OFF_ATTACK:
5106 case RANGED_ATTACK:
5108 Item *tmpitem = GetWeaponForAttack(attType,true);
5109 if (tmpitem)
5110 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5111 break;
5114 UpdateAllCritPercentages();
5117 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5119 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5120 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5121 uint32 moblevel = pVictim->getLevelForTarget(this);
5122 if(moblevel < greylevel)
5123 return;
5125 if (moblevel > plevel + 5)
5126 moblevel = plevel + 5;
5128 uint32 lvldif = moblevel - greylevel;
5129 if(lvldif < 3)
5130 lvldif = 3;
5132 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5133 if(skilldif <= 0)
5134 return;
5136 float chance = float(3 * lvldif * skilldif) / plevel;
5137 if(!defence)
5139 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5140 chance *= 0.1f * GetStat(STAT_INTELLECT);
5143 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5145 if(roll_chance_f(chance))
5147 if(defence)
5148 UpdateDefense();
5149 else
5150 UpdateWeaponSkill(attType);
5152 else
5153 return;
5156 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5158 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5159 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5161 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5162 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5163 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5165 if(talent) // permanent bonus stored in high part
5166 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5167 else // temporary/item bonus stored in low part
5168 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5169 return;
5173 void Player::UpdateSkillsForLevel()
5175 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5176 uint32 maxSkill = GetMaxSkillValueForLevel();
5178 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5180 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5181 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5183 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5185 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5186 if(!pSkill)
5187 continue;
5189 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5190 continue;
5192 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5193 uint32 max = SKILL_MAX(data);
5194 uint32 val = SKILL_VALUE(data);
5196 /// update only level dependent max skill values
5197 if(max!=1)
5199 /// miximize skill always
5200 if(alwaysMaxSkill)
5201 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5202 /// update max skill value if current max skill not maximized
5203 else if(max != maxconfskill)
5204 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5209 void Player::UpdateSkillsToMaxSkillsForLevel()
5211 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5212 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5214 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5215 if( IsProfessionOrRidingSkill(pskill))
5216 continue;
5217 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5219 uint32 max = SKILL_MAX(data);
5221 if(max > 1)
5222 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5224 if(pskill == SKILL_DEFENSE)
5225 UpdateDefenseBonusesMod();
5229 // This functions sets a skill line value (and adds if doesn't exist yet)
5230 // To "remove" a skill line, set it's values to zero
5231 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5233 if(!id)
5234 return;
5236 uint16 i=0;
5237 for (; i < PLAYER_MAX_SKILLS; ++i)
5238 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5240 if(i<PLAYER_MAX_SKILLS) //has skill
5242 if(currVal)
5244 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5245 learnSkillRewardedSpells(id, currVal);
5246 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5247 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5249 else //remove
5251 // clear skill fields
5252 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5253 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5254 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5256 // remove all spells that related to this skill
5257 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5258 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5259 if (pAbility->skillId==id)
5260 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5263 else if(currVal) //add
5265 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5266 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5268 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5269 if(!pSkill)
5271 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5272 return;
5274 // enable unlearn button for primary professions only
5275 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5276 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5277 else
5278 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5279 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5280 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5281 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5283 // apply skill bonuses
5284 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5286 // temporary bonuses
5287 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5288 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5289 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5290 (*j)->ApplyModifier(true);
5292 // permanent bonuses
5293 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5294 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5295 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5296 (*j)->ApplyModifier(true);
5298 // Learn all spells for skill
5299 learnSkillRewardedSpells(id, currVal);
5300 return;
5305 bool Player::HasSkill(uint32 skill) const
5307 if(!skill)return false;
5308 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5310 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5312 return true;
5315 return false;
5318 uint16 Player::GetSkillValue(uint32 skill) const
5320 if(!skill)
5321 return 0;
5323 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5325 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5327 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5329 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5330 result += SKILL_TEMP_BONUS(bonus);
5331 result += SKILL_PERM_BONUS(bonus);
5332 return result < 0 ? 0 : result;
5335 return 0;
5338 uint16 Player::GetMaxSkillValue(uint32 skill) const
5340 if(!skill)return 0;
5341 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5343 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5345 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5347 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5348 result += SKILL_TEMP_BONUS(bonus);
5349 result += SKILL_PERM_BONUS(bonus);
5350 return result < 0 ? 0 : result;
5353 return 0;
5356 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5358 if(!skill)return 0;
5359 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5361 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5363 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5366 return 0;
5369 uint16 Player::GetBaseSkillValue(uint32 skill) const
5371 if(!skill)return 0;
5372 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5374 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5376 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5377 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5378 return result < 0 ? 0 : result;
5381 return 0;
5384 uint16 Player::GetPureSkillValue(uint32 skill) const
5386 if(!skill)return 0;
5387 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5389 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5391 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5394 return 0;
5397 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5399 if(!skill)
5400 return 0;
5402 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5404 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5406 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5410 return 0;
5413 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5415 if(!skill)
5416 return 0;
5418 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5420 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5422 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5426 return 0;
5429 void Player::SendInitialActionButtons() const
5431 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5433 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5434 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5436 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5437 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5439 data << uint16(itr->second.action);
5440 data << uint8(itr->second.misc);
5441 data << uint8(itr->second.type);
5443 else
5445 data << uint32(0);
5449 GetSession()->SendPacket( &data );
5450 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5453 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5455 if(button >= MAX_ACTION_BUTTONS)
5457 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5458 return false;
5461 // check cheating with adding non-known spells to action bar
5462 if(type==ACTION_BUTTON_SPELL)
5464 if(!sSpellStore.LookupEntry(action))
5466 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5467 return false;
5470 if(!HasSpell(action))
5472 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5473 return false;
5477 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5479 if (buttonItr==m_actionButtons.end())
5480 { // just add new button
5481 m_actionButtons[button] = ActionButton(action,type,misc);
5483 else
5484 { // change state of current button
5485 ActionButtonUpdateState uState = buttonItr->second.uState;
5486 buttonItr->second = ActionButton(action,type,misc);
5487 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5490 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5491 return true;
5494 void Player::removeActionButton(uint8 button)
5496 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5497 if (buttonItr==m_actionButtons.end())
5498 return;
5500 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5501 m_actionButtons.erase(buttonItr); // new and not saved
5502 else
5503 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5505 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5508 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5510 // prevent crash when a bad coord is sent by the client
5511 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5513 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5514 return false;
5517 Map *m = GetMap();
5519 const float old_x = GetPositionX();
5520 const float old_y = GetPositionY();
5521 const float old_z = GetPositionZ();
5522 const float old_r = GetOrientation();
5524 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5526 if (teleport || old_x != x || old_y != y || old_z != z)
5527 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5528 else
5529 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5531 // move and update visible state if need
5532 m->PlayerRelocation(this, x, y, z, orientation);
5534 // reread after Map::Relocation
5535 m = GetMap();
5536 x = GetPositionX();
5537 y = GetPositionY();
5538 z = GetPositionZ();
5540 // group update
5541 if(GetGroup() && (old_x != x || old_y != y))
5542 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5545 // code block for underwater state update
5546 UpdateUnderwaterState(m, x, y, z);
5548 CheckExploreSystem();
5550 return true;
5553 void Player::SaveRecallPosition()
5555 m_recallMap = GetMapId();
5556 m_recallX = GetPositionX();
5557 m_recallY = GetPositionY();
5558 m_recallZ = GetPositionZ();
5559 m_recallO = GetOrientation();
5562 void Player::SendMessageToSet(WorldPacket *data, bool self)
5564 GetMap()->MessageBroadcast(this, data, self);
5567 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5569 GetMap()->MessageDistBroadcast(this, data, dist, self);
5572 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5574 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5577 void Player::SendDirectMessage(WorldPacket *data)
5579 GetSession()->SendPacket(data);
5582 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5584 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5585 data << uint32(CinematicSequenceId);
5586 SendDirectMessage(&data);
5589 void Player::SendMovieStart(uint32 MovieId)
5591 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5592 data << uint32(MovieId);
5593 SendDirectMessage(&data);
5596 void Player::CheckExploreSystem()
5598 if (!isAlive())
5599 return;
5601 if (isInFlight())
5602 return;
5604 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5605 if(areaFlag==0xffff)
5606 return;
5607 int offset = areaFlag / 32;
5609 if(offset >= 128)
5611 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);
5612 return;
5615 uint32 val = (uint32)(1 << (areaFlag % 32));
5616 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5618 if( !(currFields & val) )
5620 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5622 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5624 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5625 if(!p)
5627 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5629 else if(p->area_level > 0)
5631 uint32 area = p->ID;
5632 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5634 SendExplorationExperience(area,0);
5636 else
5638 int32 diff = int32(getLevel()) - p->area_level;
5639 uint32 XP = 0;
5640 if (diff < -5)
5642 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5644 else if (diff > 5)
5646 int32 exploration_percent = (100-((diff-5)*5));
5647 if (exploration_percent > 100)
5648 exploration_percent = 100;
5649 else if (exploration_percent < 0)
5650 exploration_percent = 0;
5652 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5654 else
5656 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5659 GiveXP( XP, NULL );
5660 SendExplorationExperience(area,XP);
5662 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5667 uint32 Player::TeamForRace(uint8 race)
5669 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5670 if(!rEntry)
5672 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5673 return ALLIANCE;
5676 switch(rEntry->TeamID)
5678 case 7: return ALLIANCE;
5679 case 1: return HORDE;
5682 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5683 return ALLIANCE;
5686 uint32 Player::getFactionForRace(uint8 race)
5688 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5689 if(!rEntry)
5691 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5692 return 0;
5695 return rEntry->FactionID;
5698 void Player::setFactionForRace(uint8 race)
5700 m_team = TeamForRace(race);
5701 setFaction( getFactionForRace(race) );
5704 ReputationRank Player::GetReputationRank(uint32 faction) const
5706 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5707 return GetReputationMgr().GetRank(factionEntry);
5710 //Calculate total reputation percent player gain with quest/creature level
5711 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5713 float percent = 100.0f;
5715 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5717 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5718 percent *= rate;
5720 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5722 if (!for_quest)
5723 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5725 percent += rep > 0 ? repMod : -repMod;
5727 if (percent <= 0.0f)
5728 return 0;
5730 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5733 //Calculates how many reputation points player gains in victim's enemy factions
5734 void Player::RewardReputation(Unit *pVictim, float rate)
5736 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5737 return;
5739 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5741 if(!Rep)
5742 return;
5744 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5746 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5747 donerep1 = int32(donerep1*rate);
5748 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5749 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5750 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5751 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5753 // Wiki: Team factions value divided by 2
5754 if (factionEntry1 && Rep->is_teamaward1)
5756 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5757 if(team1_factionEntry)
5758 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5762 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5764 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5765 donerep2 = int32(donerep2*rate);
5766 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5767 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5768 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5769 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5771 // Wiki: Team factions value divided by 2
5772 if (factionEntry2 && Rep->is_teamaward2)
5774 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5775 if(team2_factionEntry)
5776 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5781 //Calculate how many reputation points player gain with the quest
5782 void Player::RewardReputation(Quest const *pQuest)
5784 // quest reputation reward/loss
5785 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5787 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5789 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5790 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5791 if(factionEntry)
5792 GetReputationMgr().ModifyReputation(factionEntry, rep);
5796 // TODO: implement reputation spillover
5799 void Player::UpdateArenaFields(void)
5801 /* arena calcs go here */
5804 void Player::UpdateHonorFields()
5806 /// called when rewarding honor and at each save
5807 uint64 now = time(NULL);
5808 uint64 today = uint64(time(NULL) / DAY) * DAY;
5810 if(m_lastHonorUpdateTime < today)
5812 uint64 yesterday = today - DAY;
5814 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5816 // update yesterday's contribution
5817 if(m_lastHonorUpdateTime >= yesterday )
5819 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5821 // this is the first update today, reset today's contribution
5822 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5823 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5825 else
5827 // no honor/kills yesterday or today, reset
5828 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5829 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5833 m_lastHonorUpdateTime = now;
5836 ///Calculate the amount of honor gained based on the victim
5837 ///and the size of the group for which the honor is divided
5838 ///An exact honor value can also be given (overriding the calcs)
5839 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5841 // do not reward honor in arenas, but enable onkill spellproc
5842 if(InArena())
5844 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5845 return false;
5847 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5848 return false;
5850 return true;
5853 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5854 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5855 return false;
5857 uint64 victim_guid = 0;
5858 uint32 victim_rank = 0;
5860 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5861 UpdateHonorFields();
5863 if(honor <= 0)
5865 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5866 return false;
5868 victim_guid = uVictim->GetGUID();
5870 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5872 Player *pVictim = (Player *)uVictim;
5874 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5875 return false;
5877 float f = 1; //need for total kills (?? need more info)
5878 uint32 k_grey = 0;
5879 uint32 k_level = getLevel();
5880 uint32 v_level = pVictim->getLevel();
5883 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5884 // [0] Just name
5885 // [1..14] Alliance honor titles and player name
5886 // [15..28] Horde honor titles and player name
5887 // [29..38] Other title and player name
5888 // [39+] Nothing
5889 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5890 // Get Killer titles, CharTitlesEntry::bit_index
5891 // Ranks:
5892 // title[1..14] -> rank[5..18]
5893 // title[15..28] -> rank[5..18]
5894 // title[other] -> 0
5895 if (victim_title == 0)
5896 victim_guid = 0; // Don't show HK: <rank> message, only log.
5897 else if (victim_title < 15)
5898 victim_rank = victim_title + 4;
5899 else if (victim_title < 29)
5900 victim_rank = victim_title - 14 + 4;
5901 else
5902 victim_guid = 0; // Don't show HK: <rank> message, only log.
5905 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5907 if(v_level<=k_grey)
5908 return false;
5910 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5912 int32 v_rank =1; //need more info
5914 honor = ((f * diff_level * (190 + v_rank*10))/6);
5915 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5917 // count the number of playerkills in one day
5918 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5919 // and those in a lifetime
5920 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5921 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5922 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5923 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5925 else
5927 Creature *cVictim = (Creature *)uVictim;
5929 if (!cVictim->isRacialLeader())
5930 return false;
5932 honor = 100; // ??? need more info
5933 victim_rank = 19; // HK: Leader
5937 if (uVictim != NULL)
5939 honor *= sWorld.getRate(RATE_HONOR);
5941 if(groupsize > 1)
5942 honor /= groupsize;
5944 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5947 // honor - for show honor points in log
5948 // victim_guid - for show victim name in log
5949 // victim_rank [1..4] HK: <dishonored rank>
5950 // victim_rank [5..19] HK: <alliance\horde rank>
5951 // victim_rank [0,20+] HK: <>
5952 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5953 data << (uint32) honor;
5954 data << (uint64) victim_guid;
5955 data << (uint32) victim_rank;
5957 GetSession()->SendPacket(&data);
5959 // add honor points
5960 ModifyHonorPoints(int32(honor));
5962 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5963 return true;
5966 void Player::ModifyHonorPoints( int32 value )
5968 if(value < 0)
5970 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5971 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5972 else
5973 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5975 else
5976 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5979 void Player::ModifyArenaPoints( int32 value )
5981 if(value < 0)
5983 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5984 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5985 else
5986 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5988 else
5989 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5992 uint32 Player::GetGuildIdFromDB(uint64 guid)
5994 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5995 if(!result)
5996 return 0;
5998 uint32 id = result->Fetch()[0].GetUInt32();
5999 delete result;
6000 return id;
6003 uint32 Player::GetRankFromDB(uint64 guid)
6005 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6006 if( result )
6008 uint32 v = result->Fetch()[0].GetUInt32();
6009 delete result;
6010 return v;
6012 else
6013 return 0;
6016 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6018 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);
6019 if(!result)
6020 return 0;
6022 uint32 id = (*result)[0].GetUInt32();
6023 delete result;
6024 return id;
6027 uint32 Player::GetZoneIdFromDB(uint64 guid)
6029 uint32 guidLow = GUID_LOPART(guid);
6030 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6031 if (!result)
6032 return 0;
6033 Field* fields = result->Fetch();
6034 uint32 zone = fields[0].GetUInt32();
6035 delete result;
6037 if (!zone)
6039 // stored zone is zero, use generic and slow zone detection
6040 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6041 if( !result )
6042 return 0;
6043 fields = result->Fetch();
6044 uint32 map = fields[0].GetUInt32();
6045 float posx = fields[1].GetFloat();
6046 float posy = fields[2].GetFloat();
6047 float posz = fields[3].GetFloat();
6048 delete result;
6050 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6052 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6055 return zone;
6058 void Player::UpdateArea(uint32 newArea)
6060 // FFA_PVP flags are area and not zone id dependent
6061 // so apply them accordingly
6062 m_areaUpdateId = newArea;
6064 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6066 if(area && (area->flags & AREA_FLAG_ARENA))
6068 if(!isGameMaster())
6069 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6071 else
6073 // remove ffa flag only if not ffapvp realm
6074 // removal in sanctuaries and capitals is handled in zone update
6075 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6076 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6079 UpdateAreaDependentAuras(newArea);
6082 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6084 if(m_zoneUpdateId != newZone)
6085 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6087 m_zoneUpdateId = newZone;
6088 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6090 // zone changed, so area changed as well, update it
6091 UpdateArea(newArea);
6093 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6094 if(!zone)
6095 return;
6097 if (sWorld.getConfig(CONFIG_WEATHER))
6099 Weather *wth = sWorld.FindWeather(zone->ID);
6100 if(wth)
6102 wth->SendWeatherUpdateToPlayer(this);
6104 else
6106 if(!sWorld.AddWeather(zone->ID))
6108 // send fine weather packet to remove old zone's weather
6109 Weather::SendFineWeatherUpdateToPlayer(this);
6114 // in PvP, any not controlled zone (except zone->team == 6, default case)
6115 // in PvE, only opposition team capital
6116 switch(zone->team)
6118 case AREATEAM_ALLY:
6119 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6120 break;
6121 case AREATEAM_HORDE:
6122 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6123 break;
6124 case AREATEAM_NONE:
6125 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6126 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6127 break;
6128 default: // 6 in fact
6129 pvpInfo.inHostileArea = false;
6130 break;
6133 if(pvpInfo.inHostileArea) // in hostile area
6135 if(!IsPvP() || pvpInfo.endTimer != 0)
6136 UpdatePvP(true, true);
6138 else // in friendly area
6140 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6141 pvpInfo.endTimer = time(0); // start toggle-off
6144 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6146 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6147 if(sWorld.IsFFAPvPRealm())
6148 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6150 else
6152 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6155 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6157 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6158 SetRestType(REST_TYPE_IN_CITY);
6159 InnEnter(time(0),GetMapId(),0,0,0);
6161 if(sWorld.IsFFAPvPRealm())
6162 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6164 else // anywhere else
6166 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6168 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6170 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6172 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6173 SetRestType(REST_TYPE_NO);
6175 if(sWorld.IsFFAPvPRealm())
6176 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6179 else // not in tavern (leave city then)
6181 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6182 SetRestType(REST_TYPE_NO);
6184 // Set player to FFA PVP when not in rested environment.
6185 if(sWorld.IsFFAPvPRealm())
6186 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6191 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6192 // if player resurrected at teleport this will be applied in resurrect code
6193 if(isAlive())
6194 DestroyZoneLimitedItem( true, newZone );
6196 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6197 AutoUnequipOffhandIfNeed();
6199 // recent client version not send leave/join channel packets for built-in local channels
6200 UpdateLocalChannels( newZone );
6202 // group update
6203 if(GetGroup())
6204 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6206 UpdateZoneDependentAuras(newZone);
6209 //If players are too far way of duel flag... then player loose the duel
6210 void Player::CheckDuelDistance(time_t currTime)
6212 if(!duel)
6213 return;
6215 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6216 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6217 if(!obj)
6218 return;
6220 if(duel->outOfBound == 0)
6222 if(!IsWithinDistInMap(obj, 50))
6224 duel->outOfBound = currTime;
6226 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6227 GetSession()->SendPacket(&data);
6230 else
6232 if(IsWithinDistInMap(obj, 40))
6234 duel->outOfBound = 0;
6236 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6237 GetSession()->SendPacket(&data);
6239 else if(currTime >= (duel->outOfBound+10))
6241 DuelComplete(DUEL_FLED);
6246 void Player::DuelComplete(DuelCompleteType type)
6248 // duel not requested
6249 if(!duel)
6250 return;
6252 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6253 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6254 GetSession()->SendPacket(&data);
6255 duel->opponent->GetSession()->SendPacket(&data);
6257 if(type != DUEL_INTERUPTED)
6259 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6260 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6261 data << duel->opponent->GetName();
6262 data << GetName();
6263 SendMessageToSet(&data,true);
6266 if (type == DUEL_WON)
6268 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6269 if (duel->opponent)
6270 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6273 // cool-down duel spell
6274 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6276 data<<GetGUID();
6277 data<<uint8(0x0);
6279 data<<(uint32)7266;
6280 data<<uint32(0x0);
6281 GetSession()->SendPacket(&data);
6282 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6283 data<<duel->opponent->GetGUID();
6284 data<<uint8(0x0);
6285 data<<(uint32)7266;
6286 data<<uint32(0x0);
6287 duel->opponent->GetSession()->SendPacket(&data);*/
6289 //Remove Duel Flag object
6290 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6291 if(obj)
6292 duel->initiator->RemoveGameObject(obj,true);
6294 /* remove auras */
6295 std::vector<uint32> auras2remove;
6296 AuraMap const& vAuras = duel->opponent->GetAuras();
6297 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6299 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6300 auras2remove.push_back(i->second->GetId());
6303 for(size_t i=0; i<auras2remove.size(); ++i)
6304 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6306 auras2remove.clear();
6307 AuraMap const& auras = GetAuras();
6308 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6310 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6311 auras2remove.push_back(i->second->GetId());
6313 for(size_t i=0; i<auras2remove.size(); ++i)
6314 RemoveAurasDueToSpell(auras2remove[i]);
6316 // cleanup combo points
6317 if(GetComboTarget()==duel->opponent->GetGUID())
6318 ClearComboPoints();
6319 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6320 ClearComboPoints();
6322 if(duel->opponent->GetComboTarget()==GetGUID())
6323 duel->opponent->ClearComboPoints();
6324 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6325 duel->opponent->ClearComboPoints();
6327 //cleanups
6328 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6329 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6330 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6331 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6333 delete duel->opponent->duel;
6334 duel->opponent->duel = NULL;
6335 delete duel;
6336 duel = NULL;
6339 //---------------------------------------------------------//
6341 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6343 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6344 return;
6346 // not apply/remove mods for broken item
6347 if(item->IsBroken())
6348 return;
6350 ItemPrototype const *proto = item->GetProto();
6352 if(!proto)
6353 return;
6355 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6357 uint32 attacktype = Player::GetAttackBySlot(slot);
6358 if(attacktype < MAX_ATTACK)
6359 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6361 _ApplyItemBonuses(proto,slot,apply);
6363 if( slot==EQUIPMENT_SLOT_RANGED )
6364 _ApplyAmmoBonuses();
6366 ApplyItemEquipSpell(item,apply);
6367 ApplyEnchantment(item, apply);
6369 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6370 CorrectMetaGemEnchants(slot, apply);
6372 sLog.outDebug("_ApplyItemMods complete.");
6375 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6377 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6378 return;
6380 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : 0;
6381 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(getLevel()) : 0;
6383 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6385 uint32 statType = 0;
6386 int32 val = 0;
6387 // If set ScalingStatDistribution need get stats and values from it
6388 if (ssd && ssv)
6390 if (ssd->StatMod[i] < 0)
6391 continue;
6392 statType = ssd->StatMod[i];
6393 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6395 else
6397 if (i >= proto->StatsCount)
6398 continue;
6399 statType = proto->ItemStat[i].ItemStatType;
6400 val = proto->ItemStat[i].ItemStatValue;
6403 if(val == 0)
6404 continue;
6406 switch (statType)
6408 case ITEM_MOD_MANA:
6409 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6410 break;
6411 case ITEM_MOD_HEALTH: // modify HP
6412 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6413 break;
6414 case ITEM_MOD_AGILITY: // modify agility
6415 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6416 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6417 break;
6418 case ITEM_MOD_STRENGTH: //modify strength
6419 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6420 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6421 break;
6422 case ITEM_MOD_INTELLECT: //modify intellect
6423 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6424 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6425 break;
6426 case ITEM_MOD_SPIRIT: //modify spirit
6427 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6428 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6429 break;
6430 case ITEM_MOD_STAMINA: //modify stamina
6431 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6432 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6433 break;
6434 case ITEM_MOD_DEFENSE_SKILL_RATING:
6435 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6436 break;
6437 case ITEM_MOD_DODGE_RATING:
6438 ApplyRatingMod(CR_DODGE, int32(val), apply);
6439 break;
6440 case ITEM_MOD_PARRY_RATING:
6441 ApplyRatingMod(CR_PARRY, int32(val), apply);
6442 break;
6443 case ITEM_MOD_BLOCK_RATING:
6444 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6445 break;
6446 case ITEM_MOD_HIT_MELEE_RATING:
6447 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6448 break;
6449 case ITEM_MOD_HIT_RANGED_RATING:
6450 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6451 break;
6452 case ITEM_MOD_HIT_SPELL_RATING:
6453 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6454 break;
6455 case ITEM_MOD_CRIT_MELEE_RATING:
6456 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6457 break;
6458 case ITEM_MOD_CRIT_RANGED_RATING:
6459 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6460 break;
6461 case ITEM_MOD_CRIT_SPELL_RATING:
6462 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6463 break;
6464 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6465 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6466 break;
6467 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6468 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6469 break;
6470 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6471 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6472 break;
6473 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6474 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6475 break;
6476 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6477 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6478 break;
6479 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6480 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6481 break;
6482 case ITEM_MOD_HASTE_MELEE_RATING:
6483 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6484 break;
6485 case ITEM_MOD_HASTE_RANGED_RATING:
6486 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6487 break;
6488 case ITEM_MOD_HASTE_SPELL_RATING:
6489 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6490 break;
6491 case ITEM_MOD_HIT_RATING:
6492 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6493 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6494 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6495 break;
6496 case ITEM_MOD_CRIT_RATING:
6497 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6498 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6499 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6500 break;
6501 case ITEM_MOD_HIT_TAKEN_RATING:
6502 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6503 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6504 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6505 break;
6506 case ITEM_MOD_CRIT_TAKEN_RATING:
6507 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6508 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6509 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6510 break;
6511 case ITEM_MOD_RESILIENCE_RATING:
6512 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6513 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6514 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6515 break;
6516 case ITEM_MOD_HASTE_RATING:
6517 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6518 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6519 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6520 break;
6521 case ITEM_MOD_EXPERTISE_RATING:
6522 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6523 break;
6524 case ITEM_MOD_ATTACK_POWER:
6525 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6526 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6527 break;
6528 case ITEM_MOD_RANGED_ATTACK_POWER:
6529 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6530 break;
6531 case ITEM_MOD_FERAL_ATTACK_POWER:
6532 ApplyFeralAPBonus(int32(val), apply);
6533 break;
6534 case ITEM_MOD_SPELL_HEALING_DONE:
6535 ApplySpellHealingBonus(int32(val), apply);
6536 break;
6537 case ITEM_MOD_SPELL_DAMAGE_DONE:
6538 ApplySpellDamageBonus(int32(val), apply);
6539 break;
6540 case ITEM_MOD_MANA_REGENERATION:
6541 ApplyManaRegenBonus(int32(val), apply);
6542 break;
6543 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6544 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6545 break;
6546 case ITEM_MOD_SPELL_POWER:
6547 ApplySpellHealingBonus(int32(val), apply);
6548 ApplySpellDamageBonus(int32(val), apply);
6549 break;
6553 // If set ScalingStatValue armor get it or use item armor
6554 uint32 armor = proto->Armor;
6555 if (ssv)
6557 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6558 armor = ssvarmor;
6560 // Add armor bonus from ArmorDamageModifier if > 0
6561 if (proto->ArmorDamageModifier > 0)
6562 armor+=proto->ArmorDamageModifier;
6563 if (armor)
6564 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6566 if (proto->Block)
6567 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6569 if (proto->HolyRes)
6570 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6572 if (proto->FireRes)
6573 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6575 if (proto->NatureRes)
6576 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6578 if (proto->FrostRes)
6579 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6581 if (proto->ShadowRes)
6582 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6584 if (proto->ArcaneRes)
6585 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6587 WeaponAttackType attType = BASE_ATTACK;
6588 float damage = 0.0f;
6590 if( slot == EQUIPMENT_SLOT_RANGED && (
6591 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6592 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6594 attType = RANGED_ATTACK;
6596 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6598 attType = OFF_ATTACK;
6601 float minDamage = proto->Damage[0].DamageMin;
6602 float maxDamage = proto->Damage[0].DamageMax;
6603 int32 extraDPS = 0;
6604 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6605 if (ssv)
6607 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6609 float average = extraDPS * proto->Delay / 1000.0f;
6610 minDamage = 0.7f * average;
6611 maxDamage = 1.3f * average;
6614 if (minDamage > 0 )
6616 damage = apply ? minDamage : BASE_MINDAMAGE;
6617 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6618 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6621 if (maxDamage > 0 )
6623 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6624 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6627 // Apply feral bonus from ScalingStatValue if set
6628 if (ssv)
6630 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6631 ApplyFeralAPBonus(feral_bonus, apply);
6633 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6634 if(getClass() == CLASS_DRUID)
6636 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6637 if (feral_bonus > 0)
6638 ApplyFeralAPBonus(feral_bonus, apply);
6641 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6642 return;
6644 if (proto->Delay)
6646 if(slot == EQUIPMENT_SLOT_RANGED)
6647 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6648 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6649 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6650 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6651 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6654 if(CanModifyStats() && (damage || proto->Delay))
6655 UpdateDamagePhysical(attType);
6658 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6660 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6661 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6662 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6664 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6665 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6666 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6668 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6669 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6670 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6673 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6675 // generic not weapon specific case processes in aura code
6676 if(aura->GetSpellProto()->EquippedItemClass == -1)
6677 return;
6679 BaseModGroup mod = BASEMOD_END;
6680 switch(attackType)
6682 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6683 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6684 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6685 default: return;
6688 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6690 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6694 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6696 // ignore spell mods for not wands
6697 Modifier const* modifier = aura->GetModifier();
6698 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6699 return;
6701 // generic not weapon specific case processes in aura code
6702 if(aura->GetSpellProto()->EquippedItemClass == -1)
6703 return;
6705 UnitMods unitMod = UNIT_MOD_END;
6706 switch(attackType)
6708 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6709 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6710 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6711 default: return;
6714 UnitModifierType unitModType = TOTAL_VALUE;
6715 switch(modifier->m_auraname)
6717 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6718 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6719 default: return;
6722 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6724 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6728 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6730 if(!item)
6731 return;
6733 ItemPrototype const *proto = item->GetProto();
6734 if(!proto)
6735 return;
6737 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6739 _Spell const& spellData = proto->Spells[i];
6741 // no spell
6742 if(!spellData.SpellId )
6743 continue;
6745 // wrong triggering type
6746 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6747 continue;
6749 // check if it is valid spell
6750 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6751 if(!spellproto)
6752 continue;
6754 ApplyEquipSpell(spellproto,item,apply,form_change);
6758 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6760 if(apply)
6762 // Cannot be used in this stance/form
6763 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6764 return;
6766 if(form_change) // check aura active state from other form
6768 bool found = false;
6769 for (int k=0; k < 3; ++k)
6771 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6772 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6774 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6776 found = true;
6777 break;
6780 if(found)
6781 break;
6784 if(found) // and skip re-cast already active aura at form change
6785 return;
6788 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6790 CastSpell(this,spellInfo,true,item);
6792 else
6794 if(form_change) // check aura compatibility
6796 // Cannot be used in this stance/form
6797 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6798 return; // and remove only not compatible at form change
6801 if(item)
6802 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6803 else
6804 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6808 void Player::UpdateEquipSpellsAtFormChange()
6810 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6812 if(m_items[i] && !m_items[i]->IsBroken())
6814 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6815 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6819 // item set bonuses not dependent from item broken state
6820 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6822 ItemSetEffect* eff = ItemSetEff[setindex];
6823 if(!eff)
6824 continue;
6826 for(uint32 y=0;y<8; ++y)
6828 SpellEntry const* spellInfo = eff->spells[y];
6829 if(!spellInfo)
6830 continue;
6832 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6833 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6838 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6840 if(!item || item->IsBroken())
6841 return;
6843 ItemPrototype const *proto = item->GetProto();
6844 if(!proto)
6845 return;
6847 if (!Target || Target == this )
6848 return;
6850 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6852 _Spell const& spellData = proto->Spells[i];
6854 // no spell
6855 if(!spellData.SpellId )
6856 continue;
6858 // wrong triggering type
6859 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6860 continue;
6862 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6863 if(!spellInfo)
6865 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6866 continue;
6869 // not allow proc extra attack spell at extra attack
6870 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6871 return;
6873 float chance = spellInfo->procChance;
6875 if(spellData.SpellPPMRate)
6877 uint32 WeaponSpeed = GetAttackTime(attType);
6878 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6880 else if(chance > 100.0f)
6882 chance = GetWeaponProcChance();
6885 if (roll_chance_f(chance))
6886 CastSpell(Target, spellInfo->Id, true, item);
6889 // item combat enchantments
6890 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6892 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6893 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6894 if(!pEnchant) continue;
6895 for (int s=0;s<3;s++)
6897 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6898 continue;
6900 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6901 if (!spellInfo)
6903 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6904 continue;
6907 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6908 if (roll_chance_f(chance))
6910 if(IsPositiveSpell(pEnchant->spellid[s]))
6911 CastSpell(this, pEnchant->spellid[s], true, item);
6912 else
6913 CastSpell(Target, pEnchant->spellid[s], true, item);
6919 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6921 ItemPrototype const* proto = item->GetProto();
6922 // special learning case
6923 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6925 uint32 learn_spell_id = proto->Spells[0].SpellId;
6926 uint32 learning_spell_id = proto->Spells[1].SpellId;
6928 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6929 if(!spellInfo)
6931 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6932 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6933 return;
6936 Spell *spell = new Spell(this, spellInfo, false);
6937 spell->m_CastItem = item;
6938 spell->m_cast_count = cast_count; //set count of casts
6939 spell->m_currentBasePoints[0] = learning_spell_id;
6940 spell->prepare(&targets);
6941 return;
6944 // use triggered flag only for items with many spell casts and for not first cast
6945 int count = 0;
6947 // item spells casted at use
6948 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6950 _Spell const& spellData = proto->Spells[i];
6952 // no spell
6953 if(!spellData.SpellId)
6954 continue;
6956 // wrong triggering type
6957 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6958 continue;
6960 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6961 if(!spellInfo)
6963 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6964 continue;
6967 Spell *spell = new Spell(this, spellInfo, (count > 0));
6968 spell->m_CastItem = item;
6969 spell->m_cast_count = cast_count; // set count of casts
6970 spell->m_glyphIndex = glyphIndex; // glyph index
6971 spell->prepare(&targets);
6973 ++count;
6976 // Item enchantments spells casted at use
6977 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6979 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6980 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6981 if(!pEnchant) continue;
6982 for (int s=0;s<3;s++)
6984 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6985 continue;
6987 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6988 if (!spellInfo)
6990 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6991 continue;
6994 Spell *spell = new Spell(this, spellInfo, (count > 0));
6995 spell->m_CastItem = item;
6996 spell->m_cast_count = cast_count; // set count of casts
6997 spell->m_glyphIndex = glyphIndex; // glyph index
6998 spell->prepare(&targets);
7000 ++count;
7005 void Player::_RemoveAllItemMods()
7007 sLog.outDebug("_RemoveAllItemMods start.");
7009 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7011 if(m_items[i])
7013 ItemPrototype const *proto = m_items[i]->GetProto();
7014 if(!proto)
7015 continue;
7017 // item set bonuses not dependent from item broken state
7018 if(proto->ItemSet)
7019 RemoveItemsSetItem(this,proto);
7021 if(m_items[i]->IsBroken())
7022 continue;
7024 ApplyItemEquipSpell(m_items[i],false);
7025 ApplyEnchantment(m_items[i], false);
7029 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7031 if(m_items[i])
7033 if(m_items[i]->IsBroken())
7034 continue;
7035 ItemPrototype const *proto = m_items[i]->GetProto();
7036 if(!proto)
7037 continue;
7039 uint32 attacktype = Player::GetAttackBySlot(i);
7040 if(attacktype < MAX_ATTACK)
7041 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7043 _ApplyItemBonuses(proto,i, false);
7045 if( i == EQUIPMENT_SLOT_RANGED )
7046 _ApplyAmmoBonuses();
7050 sLog.outDebug("_RemoveAllItemMods complete.");
7053 void Player::_ApplyAllItemMods()
7055 sLog.outDebug("_ApplyAllItemMods start.");
7057 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7059 if(m_items[i])
7061 if(m_items[i]->IsBroken())
7062 continue;
7064 ItemPrototype const *proto = m_items[i]->GetProto();
7065 if(!proto)
7066 continue;
7068 uint32 attacktype = Player::GetAttackBySlot(i);
7069 if(attacktype < MAX_ATTACK)
7070 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7072 _ApplyItemBonuses(proto,i, true);
7074 if( i == EQUIPMENT_SLOT_RANGED )
7075 _ApplyAmmoBonuses();
7079 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7081 if(m_items[i])
7083 ItemPrototype const *proto = m_items[i]->GetProto();
7084 if(!proto)
7085 continue;
7087 // item set bonuses not dependent from item broken state
7088 if(proto->ItemSet)
7089 AddItemsSetItem(this,m_items[i]);
7091 if(m_items[i]->IsBroken())
7092 continue;
7094 ApplyItemEquipSpell(m_items[i],true);
7095 ApplyEnchantment(m_items[i], true);
7099 sLog.outDebug("_ApplyAllItemMods complete.");
7102 void Player::_ApplyAmmoBonuses()
7104 // check ammo
7105 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7106 if(!ammo_id)
7107 return;
7109 float currentAmmoDPS;
7111 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7112 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7113 currentAmmoDPS = 0.0f;
7114 else
7115 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7117 if(currentAmmoDPS == GetAmmoDPS())
7118 return;
7120 m_ammoDPS = currentAmmoDPS;
7122 if(CanModifyStats())
7123 UpdateDamagePhysical(RANGED_ATTACK);
7126 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7128 if(!ammo_proto)
7129 return false;
7131 // check ranged weapon
7132 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7133 if(!weapon || weapon->IsBroken() )
7134 return false;
7136 ItemPrototype const* weapon_proto = weapon->GetProto();
7137 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7138 return false;
7140 // check ammo ws. weapon compatibility
7141 switch(weapon_proto->SubClass)
7143 case ITEM_SUBCLASS_WEAPON_BOW:
7144 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7145 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7146 return false;
7147 break;
7148 case ITEM_SUBCLASS_WEAPON_GUN:
7149 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7150 return false;
7151 break;
7152 default:
7153 return false;
7156 return true;
7159 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7160 Called by remove insignia spell effect */
7161 void Player::RemovedInsignia(Player* looterPlr)
7163 if (!GetBattleGroundId())
7164 return;
7166 // If not released spirit, do it !
7167 if(m_deathTimer > 0)
7169 m_deathTimer = 0;
7170 BuildPlayerRepop();
7171 RepopAtGraveyard();
7174 Corpse *corpse = GetCorpse();
7175 if (!corpse)
7176 return;
7178 // We have to convert player corpse to bones, not to be able to resurrect there
7179 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7180 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7181 if (!bones)
7182 return;
7184 // Now we must make bones lootable, and send player loot
7185 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7187 // We store the level of our player in the gold field
7188 // We retrieve this information at Player::SendLoot()
7189 bones->loot.gold = getLevel();
7190 bones->lootRecipient = looterPlr;
7191 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7194 void Player::SendLootRelease( uint64 guid )
7196 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7197 data << uint64(guid) << uint8(1);
7198 SendDirectMessage( &data );
7201 void Player::SendLoot(uint64 guid, LootType loot_type)
7203 if (uint64 lguid = GetLootGUID())
7204 m_session->DoLootRelease(lguid);
7206 Loot *loot = 0;
7207 PermissionTypes permission = ALL_PERMISSION;
7209 sLog.outDebug("Player::SendLoot");
7210 if (IS_GAMEOBJECT_GUID(guid))
7212 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7213 GameObject *go = GetMap()->GetGameObject(guid);
7215 // not check distance for GO in case owned GO (fishing bobber case, for example)
7216 // And permit out of range GO with no owner in case fishing hole
7217 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7219 SendLootRelease(guid);
7220 return;
7223 loot = &go->loot;
7225 if (go->getLootState() == GO_READY)
7227 uint32 lootid = go->GetLootId();
7229 if (lootid)
7231 sLog.outDebug(" if(lootid)");
7232 loot->clear();
7233 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7236 if (loot_type == LOOT_FISHING)
7237 go->getFishLoot(loot,this);
7239 go->SetLootState(GO_ACTIVATED);
7242 else if (IS_ITEM_GUID(guid))
7244 Item *item = GetItemByGuid( guid );
7246 if (!item)
7248 SendLootRelease(guid);
7249 return;
7252 loot = &item->loot;
7254 if (!item->m_lootGenerated)
7256 item->m_lootGenerated = true;
7257 loot->clear();
7259 switch(loot_type)
7261 case LOOT_DISENCHANTING:
7262 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7263 break;
7264 case LOOT_PROSPECTING:
7265 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7266 break;
7267 case LOOT_MILLING:
7268 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7269 break;
7270 default:
7271 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7272 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7273 break;
7277 else if (IS_CORPSE_GUID(guid)) // remove insignia
7279 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7281 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7283 SendLootRelease(guid);
7284 return;
7287 loot = &bones->loot;
7289 if (!bones->lootForBody)
7291 bones->lootForBody = true;
7292 uint32 pLevel = bones->loot.gold;
7293 bones->loot.clear();
7294 // It may need a better formula
7295 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7296 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7299 if (bones->lootRecipient != this)
7300 permission = NONE_PERMISSION;
7302 else
7304 Creature *creature = GetMap()->GetCreature(guid);
7306 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7307 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7309 SendLootRelease(guid);
7310 return;
7313 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7315 SendLootRelease(guid);
7316 return;
7319 loot = &creature->loot;
7321 if (loot_type == LOOT_PICKPOCKETING)
7323 if (!creature->lootForPickPocketed)
7325 creature->lootForPickPocketed = true;
7326 loot->clear();
7328 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7329 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7331 // Generate extra money for pick pocket loot
7332 const uint32 a = urand(0, creature->getLevel()/2);
7333 const uint32 b = urand(0, getLevel()/2);
7334 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7337 else
7339 // the player whose group may loot the corpse
7340 Player *recipient = creature->GetLootRecipient();
7341 if (!recipient)
7343 creature->SetLootRecipient(this);
7344 recipient = this;
7347 if (creature->lootForPickPocketed)
7349 creature->lootForPickPocketed = false;
7350 loot->clear();
7353 if (!creature->lootForBody)
7355 creature->lootForBody = true;
7356 loot->clear();
7358 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7359 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7361 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7363 if (Group* group = recipient->GetGroup())
7365 group->UpdateLooterGuid(creature,true);
7367 switch (group->GetLootMethod())
7369 case GROUP_LOOT:
7370 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7371 group->GroupLoot(recipient->GetGUID(), loot, creature);
7372 break;
7373 case NEED_BEFORE_GREED:
7374 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7375 break;
7376 case MASTER_LOOT:
7377 group->MasterLoot(recipient->GetGUID(), loot, creature);
7378 break;
7379 default:
7380 break;
7385 // possible only if creature->lootForBody && loot->empty() at spell cast check
7386 if (loot_type == LOOT_SKINNING)
7388 loot->clear();
7389 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7391 // set group rights only for loot_type != LOOT_SKINNING
7392 else
7394 if(Group* group = GetGroup())
7396 if (group == recipient->GetGroup())
7398 if (group->GetLootMethod() == FREE_FOR_ALL)
7399 permission = ALL_PERMISSION;
7400 else if (group->GetLooterGuid() == GetGUID())
7402 if (group->GetLootMethod() == MASTER_LOOT)
7403 permission = MASTER_PERMISSION;
7404 else
7405 permission = ALL_PERMISSION;
7407 else
7408 permission = GROUP_PERMISSION;
7410 else
7411 permission = NONE_PERMISSION;
7413 else if (recipient == this)
7414 permission = ALL_PERMISSION;
7415 else
7416 permission = NONE_PERMISSION;
7421 SetLootGUID(guid);
7423 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7424 switch(loot_type)
7426 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7427 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7428 default: break;
7431 // need know merged fishing/corpse loot type for achievements
7432 loot->loot_type = loot_type;
7434 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7436 data << uint64(guid);
7437 data << uint8(loot_type);
7438 data << LootView(*loot, this, permission);
7440 SendDirectMessage(&data);
7442 // add 'this' player as one of the players that are looting 'loot'
7443 if (permission != NONE_PERMISSION)
7444 loot->AddLooter(GetGUID());
7446 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7447 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7450 void Player::SendNotifyLootMoneyRemoved()
7452 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7453 GetSession()->SendPacket( &data );
7456 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7458 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7459 data << uint8(lootSlot);
7460 GetSession()->SendPacket( &data );
7463 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7465 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7466 data << Field;
7467 data << Value;
7468 GetSession()->SendPacket(&data);
7471 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7473 // data depends on zoneid/mapid...
7474 BattleGround* bg = GetBattleGround();
7475 uint16 NumberOfFields = 0;
7476 uint32 mapid = GetMapId();
7478 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7480 // may be exist better way to do this...
7481 switch(zoneid)
7483 case 0:
7484 case 1:
7485 case 4:
7486 case 8:
7487 case 10:
7488 case 11:
7489 case 12:
7490 case 36:
7491 case 38:
7492 case 40:
7493 case 41:
7494 case 51:
7495 case 267:
7496 case 1519:
7497 case 1537:
7498 case 2257:
7499 case 2918:
7500 NumberOfFields = 8;
7501 break;
7502 case 139:
7503 NumberOfFields = 41;
7504 break;
7505 case 1377:
7506 NumberOfFields = 15;
7507 break;
7508 case 2597:
7509 NumberOfFields = 83;
7510 break;
7511 case 3277:
7512 NumberOfFields = 16;
7513 break;
7514 case 3358:
7515 case 3820:
7516 NumberOfFields = 40;
7517 break;
7518 case 3483:
7519 NumberOfFields = 27;
7520 break;
7521 case 3518:
7522 NumberOfFields = 39;
7523 break;
7524 case 3519:
7525 NumberOfFields = 38;
7526 break;
7527 case 3521:
7528 NumberOfFields = 37;
7529 break;
7530 case 3698:
7531 case 3702:
7532 case 3968:
7533 NumberOfFields = 11;
7534 break;
7535 case 3703:
7536 NumberOfFields = 11;
7537 break;
7538 default:
7539 NumberOfFields = 12;
7540 break;
7543 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7544 data << uint32(mapid); // mapid
7545 data << uint32(zoneid); // zone id
7546 data << uint32(areaid); // area id, new 2.1.0
7547 data << uint16(NumberOfFields); // count of uint64 blocks
7548 data << uint32(0x8d8) << uint32(0x0); // 1
7549 data << uint32(0x8d7) << uint32(0x0); // 2
7550 data << uint32(0x8d6) << uint32(0x0); // 3
7551 data << uint32(0x8d5) << uint32(0x0); // 4
7552 data << uint32(0x8d4) << uint32(0x0); // 5
7553 data << uint32(0x8d3) << uint32(0x0); // 6
7554 // 7 1 - Arena season in progress, 0 - end of season
7555 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7556 // 8 Arena season id
7557 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7558 if(mapid == 530) // Outland
7560 data << uint32(0x9bf) << uint32(0x0); // 7
7561 data << uint32(0x9bd) << uint32(0xF); // 8
7562 data << uint32(0x9bb) << uint32(0xF); // 9
7564 switch(zoneid)
7566 case 1:
7567 case 11:
7568 case 12:
7569 case 38:
7570 case 40:
7571 case 51:
7572 case 1519:
7573 case 1537:
7574 case 2257:
7575 break;
7576 case 2597: // AV
7577 data << uint32(0x7ae) << uint32(0x1); // 7
7578 data << uint32(0x532) << uint32(0x1); // 8
7579 data << uint32(0x531) << uint32(0x0); // 9
7580 data << uint32(0x52e) << uint32(0x0); // 10
7581 data << uint32(0x571) << uint32(0x0); // 11
7582 data << uint32(0x570) << uint32(0x0); // 12
7583 data << uint32(0x567) << uint32(0x1); // 13
7584 data << uint32(0x566) << uint32(0x1); // 14
7585 data << uint32(0x550) << uint32(0x1); // 15
7586 data << uint32(0x544) << uint32(0x0); // 16
7587 data << uint32(0x536) << uint32(0x0); // 17
7588 data << uint32(0x535) << uint32(0x1); // 18
7589 data << uint32(0x518) << uint32(0x0); // 19
7590 data << uint32(0x517) << uint32(0x0); // 20
7591 data << uint32(0x574) << uint32(0x0); // 21
7592 data << uint32(0x573) << uint32(0x0); // 22
7593 data << uint32(0x572) << uint32(0x0); // 23
7594 data << uint32(0x56f) << uint32(0x0); // 24
7595 data << uint32(0x56e) << uint32(0x0); // 25
7596 data << uint32(0x56d) << uint32(0x0); // 26
7597 data << uint32(0x56c) << uint32(0x0); // 27
7598 data << uint32(0x56b) << uint32(0x0); // 28
7599 data << uint32(0x56a) << uint32(0x1); // 29
7600 data << uint32(0x569) << uint32(0x1); // 30
7601 data << uint32(0x568) << uint32(0x1); // 13
7602 data << uint32(0x565) << uint32(0x0); // 32
7603 data << uint32(0x564) << uint32(0x0); // 33
7604 data << uint32(0x563) << uint32(0x0); // 34
7605 data << uint32(0x562) << uint32(0x0); // 35
7606 data << uint32(0x561) << uint32(0x0); // 36
7607 data << uint32(0x560) << uint32(0x0); // 37
7608 data << uint32(0x55f) << uint32(0x0); // 38
7609 data << uint32(0x55e) << uint32(0x0); // 39
7610 data << uint32(0x55d) << uint32(0x0); // 40
7611 data << uint32(0x3c6) << uint32(0x4); // 41
7612 data << uint32(0x3c4) << uint32(0x6); // 42
7613 data << uint32(0x3c2) << uint32(0x4); // 43
7614 data << uint32(0x516) << uint32(0x1); // 44
7615 data << uint32(0x515) << uint32(0x0); // 45
7616 data << uint32(0x3b6) << uint32(0x6); // 46
7617 data << uint32(0x55c) << uint32(0x0); // 47
7618 data << uint32(0x55b) << uint32(0x0); // 48
7619 data << uint32(0x55a) << uint32(0x0); // 49
7620 data << uint32(0x559) << uint32(0x0); // 50
7621 data << uint32(0x558) << uint32(0x0); // 51
7622 data << uint32(0x557) << uint32(0x0); // 52
7623 data << uint32(0x556) << uint32(0x0); // 53
7624 data << uint32(0x555) << uint32(0x0); // 54
7625 data << uint32(0x554) << uint32(0x1); // 55
7626 data << uint32(0x553) << uint32(0x1); // 56
7627 data << uint32(0x552) << uint32(0x1); // 57
7628 data << uint32(0x551) << uint32(0x1); // 58
7629 data << uint32(0x54f) << uint32(0x0); // 59
7630 data << uint32(0x54e) << uint32(0x0); // 60
7631 data << uint32(0x54d) << uint32(0x1); // 61
7632 data << uint32(0x54c) << uint32(0x0); // 62
7633 data << uint32(0x54b) << uint32(0x0); // 63
7634 data << uint32(0x545) << uint32(0x0); // 64
7635 data << uint32(0x543) << uint32(0x1); // 65
7636 data << uint32(0x542) << uint32(0x0); // 66
7637 data << uint32(0x540) << uint32(0x0); // 67
7638 data << uint32(0x53f) << uint32(0x0); // 68
7639 data << uint32(0x53e) << uint32(0x0); // 69
7640 data << uint32(0x53d) << uint32(0x0); // 70
7641 data << uint32(0x53c) << uint32(0x0); // 71
7642 data << uint32(0x53b) << uint32(0x0); // 72
7643 data << uint32(0x53a) << uint32(0x1); // 73
7644 data << uint32(0x539) << uint32(0x0); // 74
7645 data << uint32(0x538) << uint32(0x0); // 75
7646 data << uint32(0x537) << uint32(0x0); // 76
7647 data << uint32(0x534) << uint32(0x0); // 77
7648 data << uint32(0x533) << uint32(0x0); // 78
7649 data << uint32(0x530) << uint32(0x0); // 79
7650 data << uint32(0x52f) << uint32(0x0); // 80
7651 data << uint32(0x52d) << uint32(0x1); // 81
7652 break;
7653 case 3277: // WS
7654 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7655 bg->FillInitialWorldStates(data);
7656 else
7658 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7659 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7660 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7661 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7662 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7663 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7664 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7665 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7667 break;
7668 case 3358: // AB
7669 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7670 bg->FillInitialWorldStates(data);
7671 else
7673 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7674 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7675 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7676 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7677 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7678 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7679 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7680 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7681 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7682 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7683 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7684 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7685 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7686 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7687 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7688 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7689 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7690 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7691 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7692 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7693 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7694 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7695 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7696 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7697 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7698 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7699 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7700 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7701 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7702 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7703 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7704 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7706 break;
7707 case 3820: // EY
7708 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7709 bg->FillInitialWorldStates(data);
7710 else
7712 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7713 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7714 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7715 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7716 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7717 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7718 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7719 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7720 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7721 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7722 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7723 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7724 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7725 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7726 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7727 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7728 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7729 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7730 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7731 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7732 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7733 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7734 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7735 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7736 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7737 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7738 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7739 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7740 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7741 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7742 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7743 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7744 // and some more ... unknown
7746 break;
7747 case 3483: // Hellfire Peninsula
7748 data << uint32(0x9ba) << uint32(0x1); // 10
7749 data << uint32(0x9b9) << uint32(0x1); // 11
7750 data << uint32(0x9b5) << uint32(0x0); // 12
7751 data << uint32(0x9b4) << uint32(0x1); // 13
7752 data << uint32(0x9b3) << uint32(0x0); // 14
7753 data << uint32(0x9b2) << uint32(0x0); // 15
7754 data << uint32(0x9b1) << uint32(0x1); // 16
7755 data << uint32(0x9b0) << uint32(0x0); // 17
7756 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7757 data << uint32(0x9ac) << uint32(0x0); // 19
7758 data << uint32(0x9a8) << uint32(0x0); // 20
7759 data << uint32(0x9a7) << uint32(0x0); // 21
7760 data << uint32(0x9a6) << uint32(0x1); // 22
7761 break;
7762 case 3519: // Terokkar Forest
7763 data << uint32(0xa41) << uint32(0x0); // 10
7764 data << uint32(0xa40) << uint32(0x14); // 11
7765 data << uint32(0xa3f) << uint32(0x0); // 12
7766 data << uint32(0xa3e) << uint32(0x0); // 13
7767 data << uint32(0xa3d) << uint32(0x5); // 14
7768 data << uint32(0xa3c) << uint32(0x0); // 15
7769 data << uint32(0xa87) << uint32(0x0); // 16
7770 data << uint32(0xa86) << uint32(0x0); // 17
7771 data << uint32(0xa85) << uint32(0x0); // 18
7772 data << uint32(0xa84) << uint32(0x0); // 19
7773 data << uint32(0xa83) << uint32(0x0); // 20
7774 data << uint32(0xa82) << uint32(0x0); // 21
7775 data << uint32(0xa81) << uint32(0x0); // 22
7776 data << uint32(0xa80) << uint32(0x0); // 23
7777 data << uint32(0xa7e) << uint32(0x0); // 24
7778 data << uint32(0xa7d) << uint32(0x0); // 25
7779 data << uint32(0xa7c) << uint32(0x0); // 26
7780 data << uint32(0xa7b) << uint32(0x0); // 27
7781 data << uint32(0xa7a) << uint32(0x0); // 28
7782 data << uint32(0xa79) << uint32(0x0); // 29
7783 data << uint32(0x9d0) << uint32(0x5); // 30
7784 data << uint32(0x9ce) << uint32(0x0); // 31
7785 data << uint32(0x9cd) << uint32(0x0); // 32
7786 data << uint32(0x9cc) << uint32(0x0); // 33
7787 data << uint32(0xa88) << uint32(0x0); // 34
7788 data << uint32(0xad0) << uint32(0x0); // 35
7789 data << uint32(0xacf) << uint32(0x1); // 36
7790 break;
7791 case 3521: // Zangarmarsh
7792 data << uint32(0x9e1) << uint32(0x0); // 10
7793 data << uint32(0x9e0) << uint32(0x0); // 11
7794 data << uint32(0x9df) << uint32(0x0); // 12
7795 data << uint32(0xa5d) << uint32(0x1); // 13
7796 data << uint32(0xa5c) << uint32(0x0); // 14
7797 data << uint32(0xa5b) << uint32(0x1); // 15
7798 data << uint32(0xa5a) << uint32(0x0); // 16
7799 data << uint32(0xa59) << uint32(0x1); // 17
7800 data << uint32(0xa58) << uint32(0x0); // 18
7801 data << uint32(0xa57) << uint32(0x0); // 19
7802 data << uint32(0xa56) << uint32(0x0); // 20
7803 data << uint32(0xa55) << uint32(0x1); // 21
7804 data << uint32(0xa54) << uint32(0x0); // 22
7805 data << uint32(0x9e7) << uint32(0x0); // 23
7806 data << uint32(0x9e6) << uint32(0x0); // 24
7807 data << uint32(0x9e5) << uint32(0x0); // 25
7808 data << uint32(0xa00) << uint32(0x0); // 26
7809 data << uint32(0x9ff) << uint32(0x1); // 27
7810 data << uint32(0x9fe) << uint32(0x0); // 28
7811 data << uint32(0x9fd) << uint32(0x0); // 29
7812 data << uint32(0x9fc) << uint32(0x1); // 30
7813 data << uint32(0x9fb) << uint32(0x0); // 31
7814 data << uint32(0xa62) << uint32(0x0); // 32
7815 data << uint32(0xa61) << uint32(0x1); // 33
7816 data << uint32(0xa60) << uint32(0x1); // 34
7817 data << uint32(0xa5f) << uint32(0x0); // 35
7818 break;
7819 case 3698: // Nagrand Arena
7820 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7821 bg->FillInitialWorldStates(data);
7822 else
7824 data << uint32(0xa0f) << uint32(0x0); // 7
7825 data << uint32(0xa10) << uint32(0x0); // 8
7826 data << uint32(0xa11) << uint32(0x0); // 9 show
7828 break;
7829 case 3702: // Blade's Edge Arena
7830 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7831 bg->FillInitialWorldStates(data);
7832 else
7834 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7835 data << uint32(0x9f1) << uint32(0x0); // 8 green
7836 data << uint32(0x9f3) << uint32(0x0); // 9 show
7838 break;
7839 case 3968: // Ruins of Lordaeron
7840 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7841 bg->FillInitialWorldStates(data);
7842 else
7844 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7845 data << uint32(0xbb9) << uint32(0x0); // 8 green
7846 data << uint32(0xbba) << uint32(0x0); // 9 show
7848 break;
7849 case 3703: // Shattrath City
7850 break;
7851 default:
7852 data << uint32(0x914) << uint32(0x0); // 7
7853 data << uint32(0x913) << uint32(0x0); // 8
7854 data << uint32(0x912) << uint32(0x0); // 9
7855 data << uint32(0x915) << uint32(0x0); // 10
7856 break;
7858 GetSession()->SendPacket(&data);
7861 uint32 Player::GetXPRestBonus(uint32 xp)
7863 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7865 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7866 rested_bonus = xp;
7868 SetRestBonus( GetRestBonus() - rested_bonus);
7870 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7871 return rested_bonus;
7874 void Player::SetBindPoint(uint64 guid)
7876 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7877 data << uint64(guid);
7878 GetSession()->SendPacket( &data );
7881 void Player::SendTalentWipeConfirm(uint64 guid)
7883 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7884 data << uint64(guid);
7885 data << uint32(resetTalentsCost());
7886 GetSession()->SendPacket( &data );
7889 void Player::SendPetSkillWipeConfirm()
7891 Pet* pet = GetPet();
7892 if(!pet)
7893 return;
7894 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7895 data << pet->GetGUID();
7896 data << uint32(pet->resetTalentsCost());
7897 GetSession()->SendPacket( &data );
7900 /*********************************************************/
7901 /*** STORAGE SYSTEM ***/
7902 /*********************************************************/
7904 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7906 assert(i < 3);
7907 if(i < 2 && item)
7909 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7910 return;
7911 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7912 if(charges == 0)
7913 return;
7914 if(charges > 1)
7915 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7916 else if(charges <= 1)
7918 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7919 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7924 void Player::SetSheath( SheathState sheathed )
7926 switch (sheathed)
7928 case SHEATH_STATE_UNARMED: // no prepared weapon
7929 SetVirtualItemSlot(0,NULL);
7930 SetVirtualItemSlot(1,NULL);
7931 SetVirtualItemSlot(2,NULL);
7932 break;
7933 case SHEATH_STATE_MELEE: // prepared melee weapon
7935 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7936 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7937 SetVirtualItemSlot(2,NULL);
7938 }; break;
7939 case SHEATH_STATE_RANGED: // prepared ranged weapon
7940 SetVirtualItemSlot(0,NULL);
7941 SetVirtualItemSlot(1,NULL);
7942 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7943 break;
7944 default:
7945 SetVirtualItemSlot(0,NULL);
7946 SetVirtualItemSlot(1,NULL);
7947 SetVirtualItemSlot(2,NULL);
7948 break;
7950 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
7953 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7955 uint8 pClass = getClass();
7957 uint8 slots[4];
7958 slots[0] = NULL_SLOT;
7959 slots[1] = NULL_SLOT;
7960 slots[2] = NULL_SLOT;
7961 slots[3] = NULL_SLOT;
7962 switch( proto->InventoryType )
7964 case INVTYPE_HEAD:
7965 slots[0] = EQUIPMENT_SLOT_HEAD;
7966 break;
7967 case INVTYPE_NECK:
7968 slots[0] = EQUIPMENT_SLOT_NECK;
7969 break;
7970 case INVTYPE_SHOULDERS:
7971 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7972 break;
7973 case INVTYPE_BODY:
7974 slots[0] = EQUIPMENT_SLOT_BODY;
7975 break;
7976 case INVTYPE_CHEST:
7977 slots[0] = EQUIPMENT_SLOT_CHEST;
7978 break;
7979 case INVTYPE_ROBE:
7980 slots[0] = EQUIPMENT_SLOT_CHEST;
7981 break;
7982 case INVTYPE_WAIST:
7983 slots[0] = EQUIPMENT_SLOT_WAIST;
7984 break;
7985 case INVTYPE_LEGS:
7986 slots[0] = EQUIPMENT_SLOT_LEGS;
7987 break;
7988 case INVTYPE_FEET:
7989 slots[0] = EQUIPMENT_SLOT_FEET;
7990 break;
7991 case INVTYPE_WRISTS:
7992 slots[0] = EQUIPMENT_SLOT_WRISTS;
7993 break;
7994 case INVTYPE_HANDS:
7995 slots[0] = EQUIPMENT_SLOT_HANDS;
7996 break;
7997 case INVTYPE_FINGER:
7998 slots[0] = EQUIPMENT_SLOT_FINGER1;
7999 slots[1] = EQUIPMENT_SLOT_FINGER2;
8000 break;
8001 case INVTYPE_TRINKET:
8002 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8003 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8004 break;
8005 case INVTYPE_CLOAK:
8006 slots[0] = EQUIPMENT_SLOT_BACK;
8007 break;
8008 case INVTYPE_WEAPON:
8010 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8012 // suggest offhand slot only if know dual wielding
8013 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8014 if(CanDualWield())
8015 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8016 break;
8018 case INVTYPE_SHIELD:
8019 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8020 break;
8021 case INVTYPE_RANGED:
8022 slots[0] = EQUIPMENT_SLOT_RANGED;
8023 break;
8024 case INVTYPE_2HWEAPON:
8025 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8026 if (CanDualWield() && CanTitanGrip())
8027 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8028 break;
8029 case INVTYPE_TABARD:
8030 slots[0] = EQUIPMENT_SLOT_TABARD;
8031 break;
8032 case INVTYPE_WEAPONMAINHAND:
8033 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8034 break;
8035 case INVTYPE_WEAPONOFFHAND:
8036 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8037 break;
8038 case INVTYPE_HOLDABLE:
8039 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8040 break;
8041 case INVTYPE_THROWN:
8042 slots[0] = EQUIPMENT_SLOT_RANGED;
8043 break;
8044 case INVTYPE_RANGEDRIGHT:
8045 slots[0] = EQUIPMENT_SLOT_RANGED;
8046 break;
8047 case INVTYPE_BAG:
8048 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8049 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8050 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8051 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8052 break;
8053 case INVTYPE_RELIC:
8055 switch(proto->SubClass)
8057 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8058 if (pClass == CLASS_PALADIN)
8059 slots[0] = EQUIPMENT_SLOT_RANGED;
8060 break;
8061 case ITEM_SUBCLASS_ARMOR_IDOL:
8062 if (pClass == CLASS_DRUID)
8063 slots[0] = EQUIPMENT_SLOT_RANGED;
8064 break;
8065 case ITEM_SUBCLASS_ARMOR_TOTEM:
8066 if (pClass == CLASS_SHAMAN)
8067 slots[0] = EQUIPMENT_SLOT_RANGED;
8068 break;
8069 case ITEM_SUBCLASS_ARMOR_MISC:
8070 if (pClass == CLASS_WARLOCK)
8071 slots[0] = EQUIPMENT_SLOT_RANGED;
8072 break;
8073 case ITEM_SUBCLASS_ARMOR_SIGIL:
8074 if (pClass == CLASS_DEATH_KNIGHT)
8075 slots[0] = EQUIPMENT_SLOT_RANGED;
8076 break;
8078 break;
8080 default :
8081 return NULL_SLOT;
8084 if( slot != NULL_SLOT )
8086 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8088 for (int i = 0; i < 4; ++i)
8090 if ( slots[i] == slot )
8091 return slot;
8095 else
8097 // search free slot at first
8098 for (int i = 0; i < 4; ++i)
8100 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8102 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8103 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8104 return slots[i];
8108 // if not found free and can swap return first appropriate from used
8109 for (int i = 0; i < 4; ++i)
8111 if ( slots[i] != NULL_SLOT && swap )
8112 return slots[i];
8116 // no free position
8117 return NULL_SLOT;
8120 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8122 Item *pItem;
8123 uint32 tempcount = 0;
8125 uint8 res = EQUIP_ERR_OK;
8127 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8129 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8130 if( pItem && pItem->GetEntry() == item )
8132 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8133 if(ires==EQUIP_ERR_OK)
8135 tempcount += pItem->GetCount();
8136 if( tempcount >= count )
8137 return EQUIP_ERR_OK;
8139 else
8140 res = ires;
8143 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8145 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8146 if( pItem && pItem->GetEntry() == item )
8148 tempcount += pItem->GetCount();
8149 if( tempcount >= count )
8150 return EQUIP_ERR_OK;
8153 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8155 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8156 if( pItem && pItem->GetEntry() == item )
8158 tempcount += pItem->GetCount();
8159 if( tempcount >= count )
8160 return EQUIP_ERR_OK;
8163 Bag *pBag;
8164 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8166 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8167 if( pBag )
8169 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8171 pItem = GetItemByPos( i, j );
8172 if( pItem && pItem->GetEntry() == item )
8174 tempcount += pItem->GetCount();
8175 if( tempcount >= count )
8176 return EQUIP_ERR_OK;
8182 // not found req. item count and have unequippable items
8183 return res;
8186 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8188 uint32 count = 0;
8189 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8191 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8192 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8193 count += pItem->GetCount();
8195 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8197 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8198 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8199 count += pItem->GetCount();
8201 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8203 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8204 if( pBag )
8205 count += pBag->GetItemCount(item,skipItem);
8208 if(skipItem && skipItem->GetProto()->GemProperties)
8210 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8212 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8213 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8214 count += pItem->GetGemCountWithID(item);
8218 if(inBankAlso)
8220 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8222 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8223 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8224 count += pItem->GetCount();
8226 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8228 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8229 if( pBag )
8230 count += pBag->GetItemCount(item,skipItem);
8233 if(skipItem && skipItem->GetProto()->GemProperties)
8235 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8237 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8238 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8239 count += pItem->GetGemCountWithID(item);
8244 return count;
8247 Item* Player::GetItemByGuid( uint64 guid ) const
8249 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8251 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8252 if( pItem && pItem->GetGUID() == guid )
8253 return pItem;
8255 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8257 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8258 if( pItem && pItem->GetGUID() == guid )
8259 return pItem;
8262 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8264 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8265 if( pBag )
8267 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8269 Item* pItem = pBag->GetItemByPos( j );
8270 if( pItem && pItem->GetGUID() == guid )
8271 return pItem;
8275 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8277 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8278 if( pBag )
8280 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8282 Item* pItem = pBag->GetItemByPos( j );
8283 if( pItem && pItem->GetGUID() == guid )
8284 return pItem;
8289 return NULL;
8292 Item* Player::GetItemByPos( uint16 pos ) const
8294 uint8 bag = pos >> 8;
8295 uint8 slot = pos & 255;
8296 return GetItemByPos( bag, slot );
8299 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8301 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8302 return m_items[slot];
8303 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8304 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8306 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8307 if ( pBag )
8308 return pBag->GetItemByPos(slot);
8310 return NULL;
8313 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8315 uint16 slot;
8316 switch (attackType)
8318 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8319 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8320 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8321 default: return NULL;
8324 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8325 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8326 return NULL;
8328 if(!useable)
8329 return item;
8331 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8332 return NULL;
8334 return item;
8337 Item* Player::GetShield(bool useable) const
8339 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8340 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8341 return NULL;
8343 if(!useable)
8344 return item;
8346 if( item->IsBroken())
8347 return NULL;
8349 return item;
8352 uint32 Player::GetAttackBySlot( uint8 slot )
8354 switch(slot)
8356 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8357 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8358 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8359 default: return MAX_ATTACK;
8363 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8365 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8366 return true;
8367 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8368 return true;
8369 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8370 return true;
8371 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8372 return true;
8373 return false;
8376 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8378 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8379 return true;
8380 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8381 return true;
8382 return false;
8385 bool Player::IsBankPos( uint8 bag, uint8 slot )
8387 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8388 return true;
8389 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8390 return true;
8391 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8392 return true;
8393 return false;
8396 bool Player::IsBagPos( uint16 pos )
8398 uint8 bag = pos >> 8;
8399 uint8 slot = pos & 255;
8400 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8401 return true;
8402 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8403 return true;
8404 return false;
8407 bool Player::IsValidPos( uint8 bag, uint8 slot )
8409 // post selected
8410 if(bag == NULL_BAG)
8411 return true;
8413 if (bag == INVENTORY_SLOT_BAG_0)
8415 // any post selected
8416 if (slot == NULL_SLOT)
8417 return true;
8419 // equipment
8420 if (slot < EQUIPMENT_SLOT_END)
8421 return true;
8423 // bag equip slots
8424 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8425 return true;
8427 // backpack slots
8428 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8429 return true;
8431 // keyring slots
8432 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8433 return true;
8435 // bank main slots
8436 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8437 return true;
8439 // bank bag slots
8440 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8441 return true;
8443 return false;
8446 // bag content slots
8447 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8449 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8450 if(!pBag)
8451 return false;
8453 // any post selected
8454 if (slot == NULL_SLOT)
8455 return true;
8457 return slot < pBag->GetBagSize();
8460 // bank bag content slots
8461 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8463 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8464 if(!pBag)
8465 return false;
8467 // any post selected
8468 if (slot == NULL_SLOT)
8469 return true;
8471 return slot < pBag->GetBagSize();
8474 // where this?
8475 return false;
8479 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8481 uint32 tempcount = 0;
8482 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8484 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8485 if( pItem && pItem->GetEntry() == item )
8487 tempcount += pItem->GetCount();
8488 if( tempcount >= count )
8489 return true;
8492 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8494 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8495 if( pItem && pItem->GetEntry() == item )
8497 tempcount += pItem->GetCount();
8498 if( tempcount >= count )
8499 return true;
8502 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8504 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8506 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8508 Item* pItem = GetItemByPos( i, j );
8509 if( pItem && pItem->GetEntry() == item )
8511 tempcount += pItem->GetCount();
8512 if( tempcount >= count )
8513 return true;
8519 if(inBankAlso)
8521 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8523 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8524 if( pItem && pItem->GetEntry() == item )
8526 tempcount += pItem->GetCount();
8527 if( tempcount >= count )
8528 return true;
8531 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8533 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8535 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8537 Item* pItem = GetItemByPos( i, j );
8538 if( pItem && pItem->GetEntry() == item )
8540 tempcount += pItem->GetCount();
8541 if( tempcount >= count )
8542 return true;
8549 return false;
8552 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8554 uint32 tempcount = 0;
8555 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8557 if(i==int(except_slot))
8558 continue;
8560 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8561 if( pItem && pItem->GetEntry() == item)
8563 tempcount += pItem->GetCount();
8564 if( tempcount >= count )
8565 return true;
8569 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8570 if (pProto && pProto->GemProperties)
8572 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8574 if(i==int(except_slot))
8575 continue;
8577 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8578 if( pItem && pItem->GetProto()->Socket[0].Color)
8580 tempcount += pItem->GetGemCountWithID(item);
8581 if( tempcount >= count )
8582 return true;
8587 return false;
8590 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8592 uint32 tempcount = 0;
8593 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8595 if(i==int(except_slot))
8596 continue;
8598 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8599 if (!pItem)
8600 continue;
8602 ItemPrototype const *pProto = pItem->GetProto();
8603 if (!pProto)
8604 continue;
8606 if (pProto->ItemLimitCategory == limitCategory)
8608 tempcount += pItem->GetCount();
8609 if( tempcount >= count )
8610 return true;
8613 if( pProto->Socket[0].Color)
8615 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8616 if( tempcount >= count )
8617 return true;
8621 return false;
8624 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8626 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8627 if( !pProto )
8629 if(no_space_count)
8630 *no_space_count = count;
8631 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8634 // no maximum
8635 if(pProto->MaxCount <= 0)
8636 return EQUIP_ERR_OK;
8638 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8640 if (curcount + count > uint32(pProto->MaxCount))
8642 if(no_space_count)
8643 *no_space_count = count +curcount - pProto->MaxCount;
8644 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8647 return EQUIP_ERR_OK;
8650 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8652 Item *pItem;
8653 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8655 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8656 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8657 return true;
8659 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8661 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8662 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8663 return true;
8665 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8667 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8669 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8671 pItem = GetItemByPos( i, j );
8672 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8673 return true;
8677 return false;
8680 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8682 Item* pItem2 = GetItemByPos( bag, slot );
8684 // ignore move item (this slot will be empty at move)
8685 if(pItem2==pSrcItem)
8686 pItem2 = NULL;
8688 uint32 need_space;
8690 // empty specific slot - check item fit to slot
8691 if( !pItem2 || swap )
8693 if( bag == INVENTORY_SLOT_BAG_0 )
8695 // keyring case
8696 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8697 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8699 // vanitypet case (not use, vanity pets stored as spells)
8700 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8701 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8703 // currencytoken case
8704 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8705 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8707 // guestbag case (not use)
8708 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END)
8709 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8711 // prevent cheating
8712 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8713 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8715 else
8717 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8718 if( !pBag )
8719 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8721 ItemPrototype const* pBagProto = pBag->GetProto();
8722 if( !pBagProto )
8723 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8725 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8726 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8729 // non empty stack with space
8730 need_space = pProto->GetMaxStackSize();
8732 // non empty slot, check item type
8733 else
8735 // check item type
8736 if(pItem2->GetEntry() != pProto->ItemId)
8737 return EQUIP_ERR_ITEM_CANT_STACK;
8739 // check free space
8740 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8741 return EQUIP_ERR_ITEM_CANT_STACK;
8743 // free stack space or infinity
8744 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8747 if(need_space > count)
8748 need_space = count;
8750 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8751 if(!newPosition.isContainedIn(dest))
8753 dest.push_back(newPosition);
8754 count -= need_space;
8756 return EQUIP_ERR_OK;
8759 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
8761 // skip specific bag already processed in first called _CanStoreItem_InBag
8762 if(bag==skip_bag)
8763 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8765 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8766 if( !pBag )
8767 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8769 ItemPrototype const* pBagProto = pBag->GetProto();
8770 if( !pBagProto )
8771 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8773 // specialized bag mode or non-specilized
8774 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8775 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8777 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8778 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8780 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8782 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8783 if(j==skip_slot)
8784 continue;
8786 Item* pItem2 = GetItemByPos( bag, j );
8788 // ignore move item (this slot will be empty at move)
8789 if(pItem2==pSrcItem)
8790 pItem2 = NULL;
8792 // if merge skip empty, if !merge skip non-empty
8793 if((pItem2!=NULL)!=merge)
8794 continue;
8796 if( pItem2 )
8798 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8800 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8801 if(need_space > count)
8802 need_space = count;
8804 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8805 if(!newPosition.isContainedIn(dest))
8807 dest.push_back(newPosition);
8808 count -= need_space;
8810 if(count==0)
8811 return EQUIP_ERR_OK;
8815 else
8817 uint32 need_space = pProto->GetMaxStackSize();
8818 if(need_space > count)
8819 need_space = count;
8821 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8822 if(!newPosition.isContainedIn(dest))
8824 dest.push_back(newPosition);
8825 count -= need_space;
8827 if(count==0)
8828 return EQUIP_ERR_OK;
8832 return EQUIP_ERR_OK;
8835 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
8837 for(uint32 j = slot_begin; j < slot_end; ++j)
8839 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8840 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8841 continue;
8843 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8845 // ignore move item (this slot will be empty at move)
8846 if(pItem2==pSrcItem)
8847 pItem2 = NULL;
8849 // if merge skip empty, if !merge skip non-empty
8850 if((pItem2!=NULL)!=merge)
8851 continue;
8853 if( pItem2 )
8855 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8857 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8858 if(need_space > count)
8859 need_space = count;
8860 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8861 if(!newPosition.isContainedIn(dest))
8863 dest.push_back(newPosition);
8864 count -= need_space;
8866 if(count==0)
8867 return EQUIP_ERR_OK;
8871 else
8873 uint32 need_space = pProto->GetMaxStackSize();
8874 if(need_space > count)
8875 need_space = count;
8877 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8878 if(!newPosition.isContainedIn(dest))
8880 dest.push_back(newPosition);
8881 count -= need_space;
8883 if(count==0)
8884 return EQUIP_ERR_OK;
8888 return EQUIP_ERR_OK;
8891 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8893 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8895 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8896 if( !pProto )
8898 if(no_space_count)
8899 *no_space_count = count;
8900 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8903 if(pItem && pItem->IsBindedNotWith(this))
8905 if(no_space_count)
8906 *no_space_count = count;
8907 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8910 // check count of items (skip for auto move for same player from bank)
8911 uint32 no_similar_count = 0; // can't store this amount similar items
8912 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8913 if(res!=EQUIP_ERR_OK)
8915 if(count==no_similar_count)
8917 if(no_space_count)
8918 *no_space_count = no_similar_count;
8919 return res;
8921 count -= no_similar_count;
8924 // in specific slot
8925 if( bag != NULL_BAG && slot != NULL_SLOT )
8927 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8928 if(res!=EQUIP_ERR_OK)
8930 if(no_space_count)
8931 *no_space_count = count + no_similar_count;
8932 return res;
8935 if(count==0)
8937 if(no_similar_count==0)
8938 return EQUIP_ERR_OK;
8940 if(no_space_count)
8941 *no_space_count = count + no_similar_count;
8942 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8946 // not specific slot or have space for partly store only in specific slot
8948 // in specific bag
8949 if( bag != NULL_BAG )
8951 // search stack in bag for merge to
8952 if( pProto->Stackable != 1 )
8954 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8956 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8957 if(res!=EQUIP_ERR_OK)
8959 if(no_space_count)
8960 *no_space_count = count + no_similar_count;
8961 return res;
8964 if(count==0)
8966 if(no_similar_count==0)
8967 return EQUIP_ERR_OK;
8969 if(no_space_count)
8970 *no_space_count = count + no_similar_count;
8971 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8974 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8975 if(res!=EQUIP_ERR_OK)
8977 if(no_space_count)
8978 *no_space_count = count + no_similar_count;
8979 return res;
8982 if(count==0)
8984 if(no_similar_count==0)
8985 return EQUIP_ERR_OK;
8987 if(no_space_count)
8988 *no_space_count = count + no_similar_count;
8989 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8992 else // equipped bag
8994 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8995 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8996 if(res!=EQUIP_ERR_OK)
8997 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8999 if(res!=EQUIP_ERR_OK)
9001 if(no_space_count)
9002 *no_space_count = count + no_similar_count;
9003 return res;
9006 if(count==0)
9008 if(no_similar_count==0)
9009 return EQUIP_ERR_OK;
9011 if(no_space_count)
9012 *no_space_count = count + no_similar_count;
9013 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9018 // search free slot in bag for place to
9019 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9021 // search free slot - keyring case
9022 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9024 uint32 keyringSize = GetMaxKeyringSize();
9025 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9026 if(res!=EQUIP_ERR_OK)
9028 if(no_space_count)
9029 *no_space_count = count + no_similar_count;
9030 return res;
9033 if(count==0)
9035 if(no_similar_count==0)
9036 return EQUIP_ERR_OK;
9038 if(no_space_count)
9039 *no_space_count = count + no_similar_count;
9040 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9043 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9044 if(res!=EQUIP_ERR_OK)
9046 if(no_space_count)
9047 *no_space_count = count + no_similar_count;
9048 return res;
9051 if(count==0)
9053 if(no_similar_count==0)
9054 return EQUIP_ERR_OK;
9056 if(no_space_count)
9057 *no_space_count = count + no_similar_count;
9058 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9061 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9063 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9064 if(res!=EQUIP_ERR_OK)
9066 if(no_space_count)
9067 *no_space_count = count + no_similar_count;
9068 return res;
9071 if(count==0)
9073 if(no_similar_count==0)
9074 return EQUIP_ERR_OK;
9076 if(no_space_count)
9077 *no_space_count = count + no_similar_count;
9078 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9082 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9083 if(res!=EQUIP_ERR_OK)
9085 if(no_space_count)
9086 *no_space_count = count + no_similar_count;
9087 return res;
9090 if(count==0)
9092 if(no_similar_count==0)
9093 return EQUIP_ERR_OK;
9095 if(no_space_count)
9096 *no_space_count = count + no_similar_count;
9097 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9100 else // equipped bag
9102 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9103 if(res!=EQUIP_ERR_OK)
9104 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9106 if(res!=EQUIP_ERR_OK)
9108 if(no_space_count)
9109 *no_space_count = count + no_similar_count;
9110 return res;
9113 if(count==0)
9115 if(no_similar_count==0)
9116 return EQUIP_ERR_OK;
9118 if(no_space_count)
9119 *no_space_count = count + no_similar_count;
9120 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9125 // not specific bag or have space for partly store only in specific bag
9127 // search stack for merge to
9128 if( pProto->Stackable != 1 )
9130 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9131 if(res!=EQUIP_ERR_OK)
9133 if(no_space_count)
9134 *no_space_count = count + no_similar_count;
9135 return res;
9138 if(count==0)
9140 if(no_similar_count==0)
9141 return EQUIP_ERR_OK;
9143 if(no_space_count)
9144 *no_space_count = count + no_similar_count;
9145 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9148 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9149 if(res!=EQUIP_ERR_OK)
9151 if(no_space_count)
9152 *no_space_count = count + no_similar_count;
9153 return res;
9156 if(count==0)
9158 if(no_similar_count==0)
9159 return EQUIP_ERR_OK;
9161 if(no_space_count)
9162 *no_space_count = count + no_similar_count;
9163 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9166 if( pProto->BagFamily )
9168 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9170 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9171 if(res!=EQUIP_ERR_OK)
9172 continue;
9174 if(count==0)
9176 if(no_similar_count==0)
9177 return EQUIP_ERR_OK;
9179 if(no_space_count)
9180 *no_space_count = count + no_similar_count;
9181 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9186 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9188 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9189 if(res!=EQUIP_ERR_OK)
9190 continue;
9192 if(count==0)
9194 if(no_similar_count==0)
9195 return EQUIP_ERR_OK;
9197 if(no_space_count)
9198 *no_space_count = count + no_similar_count;
9199 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9204 // search free slot - special bag case
9205 if( pProto->BagFamily )
9207 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9209 uint32 keyringSize = GetMaxKeyringSize();
9210 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9211 if(res!=EQUIP_ERR_OK)
9213 if(no_space_count)
9214 *no_space_count = count + no_similar_count;
9215 return res;
9218 if(count==0)
9220 if(no_similar_count==0)
9221 return EQUIP_ERR_OK;
9223 if(no_space_count)
9224 *no_space_count = count + no_similar_count;
9225 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9228 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9230 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9231 if(res!=EQUIP_ERR_OK)
9233 if(no_space_count)
9234 *no_space_count = count + no_similar_count;
9235 return res;
9238 if(count==0)
9240 if(no_similar_count==0)
9241 return EQUIP_ERR_OK;
9243 if(no_space_count)
9244 *no_space_count = count + no_similar_count;
9245 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9249 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9251 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9252 if(res!=EQUIP_ERR_OK)
9253 continue;
9255 if(count==0)
9257 if(no_similar_count==0)
9258 return EQUIP_ERR_OK;
9260 if(no_space_count)
9261 *no_space_count = count + no_similar_count;
9262 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9267 // search free slot
9268 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9269 if(res!=EQUIP_ERR_OK)
9271 if(no_space_count)
9272 *no_space_count = count + no_similar_count;
9273 return res;
9276 if(count==0)
9278 if(no_similar_count==0)
9279 return EQUIP_ERR_OK;
9281 if(no_space_count)
9282 *no_space_count = count + no_similar_count;
9283 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9286 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9288 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9289 if(res!=EQUIP_ERR_OK)
9290 continue;
9292 if(count==0)
9294 if(no_similar_count==0)
9295 return EQUIP_ERR_OK;
9297 if(no_space_count)
9298 *no_space_count = count + no_similar_count;
9299 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9303 if(no_space_count)
9304 *no_space_count = count + no_similar_count;
9306 return EQUIP_ERR_INVENTORY_FULL;
9309 //////////////////////////////////////////////////////////////////////////
9310 uint8 Player::CanStoreItems( Item **pItems,int count) const
9312 Item *pItem2;
9314 // fill space table
9315 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9316 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9317 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9318 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9320 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9321 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9322 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9323 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9325 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9327 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9329 if (pItem2 && !pItem2->IsInTrade())
9331 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9335 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9337 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9339 if (pItem2 && !pItem2->IsInTrade())
9341 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9345 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9347 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9349 if (pItem2 && !pItem2->IsInTrade())
9351 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9355 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9357 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9359 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9361 pItem2 = GetItemByPos( i, j );
9362 if (pItem2 && !pItem2->IsInTrade())
9364 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9370 // check free space for all items
9371 for (int k = 0; k < count; ++k)
9373 Item *pItem = pItems[k];
9375 // no item
9376 if (!pItem) continue;
9378 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9379 ItemPrototype const *pProto = pItem->GetProto();
9381 // strange item
9382 if( !pProto )
9383 return EQUIP_ERR_ITEM_NOT_FOUND;
9385 // item it 'bind'
9386 if(pItem->IsBindedNotWith(this))
9387 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9389 Bag *pBag;
9390 ItemPrototype const *pBagProto;
9392 // item is 'one item only'
9393 uint8 res = CanTakeMoreSimilarItems(pItem);
9394 if(res != EQUIP_ERR_OK)
9395 return res;
9397 // search stack for merge to
9398 if( pProto->Stackable != 1 )
9400 bool b_found = false;
9402 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9404 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9405 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9407 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9408 b_found = true;
9409 break;
9412 if (b_found) continue;
9414 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9416 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9417 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9419 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9420 b_found = true;
9421 break;
9424 if (b_found) continue;
9426 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9428 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9429 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9431 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9432 b_found = true;
9433 break;
9436 if (b_found) continue;
9438 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9440 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9441 if( pBag )
9443 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9445 pItem2 = GetItemByPos( t, j );
9446 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9448 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9449 b_found = true;
9450 break;
9455 if (b_found) continue;
9458 // special bag case
9459 if( pProto->BagFamily )
9461 bool b_found = false;
9462 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9464 uint32 keyringSize = GetMaxKeyringSize();
9465 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9467 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9469 inv_keys[t-KEYRING_SLOT_START] = 1;
9470 b_found = true;
9471 break;
9476 if (b_found) continue;
9478 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9480 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9482 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9484 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9485 b_found = true;
9486 break;
9491 if (b_found) continue;
9493 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9495 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9496 if( pBag )
9498 pBagProto = pBag->GetProto();
9500 // not plain container check
9501 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9502 ItemCanGoIntoBag(pProto,pBagProto) )
9504 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9506 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9508 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9509 b_found = true;
9510 break;
9516 if (b_found) continue;
9519 // search free slot
9520 bool b_found = false;
9521 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9523 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9525 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9526 b_found = true;
9527 break;
9530 if (b_found) continue;
9532 // search free slot in bags
9533 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9535 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9536 if( pBag )
9538 pBagProto = pBag->GetProto();
9540 // special bag already checked
9541 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9542 continue;
9544 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9546 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9548 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9549 b_found = true;
9550 break;
9556 // no free slot found?
9557 if (!b_found)
9558 return EQUIP_ERR_INVENTORY_FULL;
9561 return EQUIP_ERR_OK;
9564 //////////////////////////////////////////////////////////////////////////
9565 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9567 dest = 0;
9568 Item *pItem = Item::CreateItem( item, 1, this );
9569 if( pItem )
9571 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9572 delete pItem;
9573 return result;
9576 return EQUIP_ERR_ITEM_NOT_FOUND;
9579 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9581 dest = 0;
9582 if( pItem )
9584 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9585 ItemPrototype const *pProto = pItem->GetProto();
9586 if( pProto )
9588 if(pItem->IsBindedNotWith(this))
9589 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9591 // check count of items (skip for auto move for same player from bank)
9592 uint8 res = CanTakeMoreSimilarItems(pItem);
9593 if(res != EQUIP_ERR_OK)
9594 return res;
9596 // check this only in game
9597 if(not_loading)
9599 // May be here should be more stronger checks; STUNNED checked
9600 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9601 if (hasUnitState(UNIT_STAT_STUNNED))
9602 return EQUIP_ERR_YOU_ARE_STUNNED;
9604 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9605 // - combat
9606 // - in-progress arenas
9607 if( !pProto->CanChangeEquipStateInCombat() )
9609 if( isInCombat() )
9610 return EQUIP_ERR_NOT_IN_COMBAT;
9612 if(BattleGround* bg = GetBattleGround())
9613 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9614 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9617 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9618 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9620 if(IsNonMeleeSpellCasted(false))
9621 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9624 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9625 if (ssd && ssd->MaxLevel < getLevel())
9626 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9628 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9629 if (eslot == NULL_SLOT)
9630 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9632 uint8 msg = CanUseItem(pItem , not_loading);
9633 if (msg != EQUIP_ERR_OK)
9634 return msg;
9635 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9636 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9638 // if swap ignore item (equipped also)
9639 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9640 return res2;
9642 // check unique-equipped special item classes
9643 if (pProto->Class == ITEM_CLASS_QUIVER)
9645 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9647 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9649 if (pBag != pItem)
9651 if (ItemPrototype const* pBagProto = pBag->GetProto())
9653 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9654 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9655 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9656 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9663 uint32 type = pProto->InventoryType;
9665 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9667 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9669 if (!CanDualWield())
9670 return EQUIP_ERR_CANT_DUAL_WIELD;
9672 else if (type == INVTYPE_2HWEAPON)
9674 if (!CanDualWield() || !CanTitanGrip())
9675 return EQUIP_ERR_CANT_DUAL_WIELD;
9678 if (IsTwoHandUsed())
9679 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9682 // equip two-hand weapon case (with possible unequip 2 items)
9683 if (type == INVTYPE_2HWEAPON)
9685 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9687 if (!CanTitanGrip())
9688 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9690 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9691 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9693 if (!CanTitanGrip())
9695 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9696 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9697 ItemPosCountVec off_dest;
9698 if (offItem && (!not_loading ||
9699 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9700 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9701 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9704 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9705 return EQUIP_ERR_OK;
9709 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9712 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9714 // Applied only to equipped items and bank bags
9715 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9716 return EQUIP_ERR_OK;
9718 Item* pItem = GetItemByPos(pos);
9720 // Applied only to existed equipped item
9721 if( !pItem )
9722 return EQUIP_ERR_OK;
9724 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9726 ItemPrototype const *pProto = pItem->GetProto();
9727 if( !pProto )
9728 return EQUIP_ERR_ITEM_NOT_FOUND;
9730 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9731 // - combat
9732 // - in-progress arenas
9733 if( !pProto->CanChangeEquipStateInCombat() )
9735 if( isInCombat() )
9736 return EQUIP_ERR_NOT_IN_COMBAT;
9738 if(BattleGround* bg = GetBattleGround())
9739 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9740 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9743 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9744 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9746 return EQUIP_ERR_OK;
9749 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9751 if (!pItem)
9752 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9754 uint32 count = pItem->GetCount();
9756 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9757 ItemPrototype const *pProto = pItem->GetProto();
9758 if (!pProto)
9759 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9761 if (pItem->IsBindedNotWith(this))
9762 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9764 // check count of items (skip for auto move for same player from bank)
9765 uint8 res = CanTakeMoreSimilarItems(pItem);
9766 if (res != EQUIP_ERR_OK)
9767 return res;
9769 // in specific slot
9770 if (bag != NULL_BAG && slot != NULL_SLOT)
9772 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9774 if (!pItem->IsBag())
9775 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9777 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9778 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9780 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9781 return cantuse;
9784 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9785 if (res!=EQUIP_ERR_OK)
9786 return res;
9788 if (count==0)
9789 return EQUIP_ERR_OK;
9792 // not specific slot or have space for partly store only in specific slot
9794 // in specific bag
9795 if( bag != NULL_BAG )
9797 if( pProto->InventoryType == INVTYPE_BAG )
9799 Bag *pBag = (Bag*)pItem;
9800 if( pBag && !pBag->IsEmpty() )
9801 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9804 // search stack in bag for merge to
9805 if( pProto->Stackable != 1 )
9807 if( bag == INVENTORY_SLOT_BAG_0 )
9809 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9810 if(res!=EQUIP_ERR_OK)
9811 return res;
9813 if(count==0)
9814 return EQUIP_ERR_OK;
9816 else
9818 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9819 if(res!=EQUIP_ERR_OK)
9820 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9822 if(res!=EQUIP_ERR_OK)
9823 return res;
9825 if(count==0)
9826 return EQUIP_ERR_OK;
9830 // search free slot in bag
9831 if( bag == INVENTORY_SLOT_BAG_0 )
9833 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9834 if(res!=EQUIP_ERR_OK)
9835 return res;
9837 if(count==0)
9838 return EQUIP_ERR_OK;
9840 else
9842 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9843 if(res != EQUIP_ERR_OK)
9844 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9846 if(res != EQUIP_ERR_OK)
9847 return res;
9849 if(count == 0)
9850 return EQUIP_ERR_OK;
9854 // not specific bag or have space for partly store only in specific bag
9856 // search stack for merge to
9857 if( pProto->Stackable != 1 )
9859 // in slots
9860 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9861 if(res != EQUIP_ERR_OK)
9862 return res;
9864 if(count == 0)
9865 return EQUIP_ERR_OK;
9867 // in special bags
9868 if( pProto->BagFamily )
9870 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9872 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9873 if(res!=EQUIP_ERR_OK)
9874 continue;
9876 if(count==0)
9877 return EQUIP_ERR_OK;
9881 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9883 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9884 if(res!=EQUIP_ERR_OK)
9885 continue;
9887 if(count==0)
9888 return EQUIP_ERR_OK;
9892 // search free place in special bag
9893 if( pProto->BagFamily )
9895 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9897 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9898 if(res!=EQUIP_ERR_OK)
9899 continue;
9901 if(count==0)
9902 return EQUIP_ERR_OK;
9906 // search free space
9907 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9908 if(res!=EQUIP_ERR_OK)
9909 return res;
9911 if(count==0)
9912 return EQUIP_ERR_OK;
9914 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9916 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9917 if(res!=EQUIP_ERR_OK)
9918 continue;
9920 if(count==0)
9921 return EQUIP_ERR_OK;
9923 return EQUIP_ERR_BANK_FULL;
9926 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9928 if (pItem)
9930 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9932 if (!isAlive() && not_loading)
9933 return EQUIP_ERR_YOU_ARE_DEAD;
9935 //if (isStunned())
9936 // return EQUIP_ERR_YOU_ARE_STUNNED;
9938 ItemPrototype const *pProto = pItem->GetProto();
9939 if (pProto)
9941 if (pItem->IsBindedNotWith(this))
9942 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9944 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
9945 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9947 if (pItem->GetSkill() != 0)
9949 if (GetSkillValue( pItem->GetSkill() ) == 0)
9950 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9953 if (pProto->RequiredSkill != 0)
9955 if (GetSkillValue( pProto->RequiredSkill ) == 0)
9956 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9958 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
9959 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9962 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
9963 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9965 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
9966 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9968 if (getLevel() < pProto->RequiredLevel)
9969 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9971 return EQUIP_ERR_OK;
9974 return EQUIP_ERR_ITEM_NOT_FOUND;
9977 bool Player::CanUseItem( ItemPrototype const *pProto )
9979 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9981 if( pProto )
9983 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9984 return false;
9985 if( pProto->RequiredSkill != 0 )
9987 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9988 return false;
9989 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9990 return false;
9992 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9993 return false;
9994 if( getLevel() < pProto->RequiredLevel )
9995 return false;
9996 return true;
9998 return false;
10001 uint8 Player::CanUseAmmo( uint32 item ) const
10003 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10004 if( !isAlive() )
10005 return EQUIP_ERR_YOU_ARE_DEAD;
10006 //if( isStunned() )
10007 // return EQUIP_ERR_YOU_ARE_STUNNED;
10008 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10009 if( pProto )
10011 if( pProto->InventoryType!= INVTYPE_AMMO )
10012 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10013 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10014 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10015 if( pProto->RequiredSkill != 0 )
10017 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10018 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10019 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10020 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10022 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10023 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10024 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10025 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10027 if( getLevel() < pProto->RequiredLevel )
10028 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10030 // Requires No Ammo
10031 if(GetDummyAura(46699))
10032 return EQUIP_ERR_BAG_FULL6;
10034 return EQUIP_ERR_OK;
10036 return EQUIP_ERR_ITEM_NOT_FOUND;
10039 void Player::SetAmmo( uint32 item )
10041 if(!item)
10042 return;
10044 // already set
10045 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10046 return;
10048 // check ammo
10049 if(item)
10051 uint8 msg = CanUseAmmo( item );
10052 if( msg != EQUIP_ERR_OK )
10054 SendEquipError( msg, NULL, NULL );
10055 return;
10059 SetUInt32Value(PLAYER_AMMO_ID, item);
10061 _ApplyAmmoBonuses();
10064 void Player::RemoveAmmo()
10066 SetUInt32Value(PLAYER_AMMO_ID, 0);
10068 m_ammoDPS = 0.0f;
10070 if(CanModifyStats())
10071 UpdateDamagePhysical(RANGED_ATTACK);
10074 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10075 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10077 uint32 count = 0;
10078 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10079 count += itr->count;
10081 Item *pItem = Item::CreateItem( item, count, this );
10082 if( pItem )
10084 ItemAddedQuestCheck( item, count );
10085 if(randomPropertyId)
10086 pItem->SetItemRandomProperties(randomPropertyId);
10087 pItem = StoreItem( dest, pItem, update );
10089 return pItem;
10092 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10094 if( !pItem )
10095 return NULL;
10097 Item* lastItem = pItem;
10098 uint32 entry = pItem->GetEntry();
10099 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10101 uint16 pos = itr->pos;
10102 uint32 count = itr->count;
10104 ++itr;
10106 if(itr == dest.end())
10108 lastItem = _StoreItem(pos,pItem,count,false,update);
10109 break;
10112 lastItem = _StoreItem(pos,pItem,count,true,update);
10114 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10115 return lastItem;
10118 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10119 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10121 if( !pItem )
10122 return NULL;
10124 uint8 bag = pos >> 8;
10125 uint8 slot = pos & 255;
10127 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10129 Item *pItem2 = GetItemByPos( bag, slot );
10131 if (!pItem2)
10133 if (clone)
10134 pItem = pItem->CloneItem(count, this);
10135 else
10136 pItem->SetCount(count);
10138 if (!pItem)
10139 return NULL;
10141 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10142 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10143 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10144 pItem->SetBinding( true );
10146 if (bag == INVENTORY_SLOT_BAG_0)
10148 m_items[slot] = pItem;
10149 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10150 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10151 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10153 pItem->SetSlot( slot );
10154 pItem->SetContainer( NULL );
10156 // need update known currency
10157 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10158 UpdateKnownCurrencies(pItem->GetEntry(), true);
10160 if (IsInWorld() && update)
10162 pItem->AddToWorld();
10163 pItem->SendUpdateToPlayer( this );
10166 pItem->SetState(ITEM_CHANGED, this);
10168 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10170 pBag->StoreItem( slot, pItem, update );
10171 if( IsInWorld() && update )
10173 pItem->AddToWorld();
10174 pItem->SendUpdateToPlayer( this );
10176 pItem->SetState(ITEM_CHANGED, this);
10177 pBag->SetState(ITEM_CHANGED, this);
10180 AddEnchantmentDurations(pItem);
10181 AddItemDurations(pItem);
10183 return pItem;
10185 else
10187 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10188 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10189 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10190 pItem2->SetBinding( true );
10192 pItem2->SetCount( pItem2->GetCount() + count );
10193 if (IsInWorld() && update)
10194 pItem2->SendUpdateToPlayer( this );
10196 if (!clone)
10198 // delete item (it not in any slot currently)
10199 if (IsInWorld() && update)
10201 pItem->RemoveFromWorld();
10202 pItem->DestroyForPlayer( this );
10205 RemoveEnchantmentDurations(pItem);
10206 RemoveItemDurations(pItem);
10208 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10209 pItem->SetState(ITEM_REMOVED, this);
10212 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10213 AddEnchantmentDurations(pItem2);
10215 pItem2->SetState(ITEM_CHANGED, this);
10217 return pItem2;
10221 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10223 if (Item *pItem = Item::CreateItem( item, 1, this ))
10225 ItemAddedQuestCheck( item, 1 );
10226 return EquipItem( pos, pItem, update );
10229 return NULL;
10232 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10235 AddEnchantmentDurations(pItem);
10236 AddItemDurations(pItem);
10238 uint8 bag = pos >> 8;
10239 uint8 slot = pos & 255;
10241 Item *pItem2 = GetItemByPos( bag, slot );
10243 if( !pItem2 )
10245 VisualizeItem( slot, pItem);
10247 if(isAlive())
10249 ItemPrototype const *pProto = pItem->GetProto();
10251 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10252 if(pProto && pProto->ItemSet)
10253 AddItemsSetItem(this, pItem);
10255 _ApplyItemMods(pItem, slot, true);
10257 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10259 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10261 if (getClass() == CLASS_ROGUE)
10262 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10264 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10266 if (!spellProto)
10267 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10268 else
10270 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10272 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10273 data << uint64(GetGUID());
10274 data << uint8(1);
10275 data << uint32(cooldownSpell);
10276 data << uint32(0);
10277 GetSession()->SendPacket(&data);
10282 if( IsInWorld() && update )
10284 pItem->AddToWorld();
10285 pItem->SendUpdateToPlayer( this );
10288 ApplyEquipCooldown(pItem);
10290 if( slot == EQUIPMENT_SLOT_MAINHAND )
10291 UpdateExpertise(BASE_ATTACK);
10292 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10293 UpdateExpertise(OFF_ATTACK);
10295 else
10297 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10298 if( IsInWorld() && update )
10299 pItem2->SendUpdateToPlayer( this );
10301 // delete item (it not in any slot currently)
10302 //pItem->DeleteFromDB();
10303 if( IsInWorld() && update )
10305 pItem->RemoveFromWorld();
10306 pItem->DestroyForPlayer( this );
10309 RemoveEnchantmentDurations(pItem);
10310 RemoveItemDurations(pItem);
10312 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10313 pItem->SetState(ITEM_REMOVED, this);
10314 pItem2->SetState(ITEM_CHANGED, this);
10316 ApplyEquipCooldown(pItem2);
10318 return pItem2;
10321 // only for full equip instead adding to stack
10322 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10324 return pItem;
10327 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10329 if( pItem )
10331 AddEnchantmentDurations(pItem);
10332 AddItemDurations(pItem);
10334 uint8 slot = pos & 255;
10335 VisualizeItem( slot, pItem);
10337 if( IsInWorld() )
10339 pItem->AddToWorld();
10340 pItem->SendUpdateToPlayer( this );
10343 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10347 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10349 if(pItem)
10351 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10353 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10354 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10356 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10357 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10359 // Use SetInt16Value to prevent set high part to FFFF for negative value
10360 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10361 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10363 else
10365 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10367 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10368 SetUInt32Value(VisibleBase + 0, 0);
10370 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10371 SetUInt32Value(VisibleBase + 1 + i, 0);
10373 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10374 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10378 void Player::VisualizeItem( uint8 slot, Item *pItem)
10380 if(!pItem)
10381 return;
10383 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10384 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10385 pItem->SetBinding( true );
10387 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10389 m_items[slot] = pItem;
10390 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10391 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10392 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10393 pItem->SetSlot( slot );
10394 pItem->SetContainer( NULL );
10396 if( slot < EQUIPMENT_SLOT_END )
10397 SetVisibleItemSlot(slot, pItem);
10399 pItem->SetState(ITEM_CHANGED, this);
10402 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10404 // note: removeitem does not actually change the item
10405 // it only takes the item out of storage temporarily
10406 // note2: if removeitem is to be used for delinking
10407 // the item must be removed from the player's updatequeue
10409 Item *pItem = GetItemByPos( bag, slot );
10410 if( pItem )
10412 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10414 RemoveEnchantmentDurations(pItem);
10415 RemoveItemDurations(pItem);
10417 if( bag == INVENTORY_SLOT_BAG_0 )
10419 if ( slot < INVENTORY_SLOT_BAG_END )
10421 ItemPrototype const *pProto = pItem->GetProto();
10422 // 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);
10429 // remove item dependent auras and casts (only weapon and armor slots)
10430 if(slot < EQUIPMENT_SLOT_END)
10432 RemoveItemDependentAurasAndCasts(pItem);
10434 // remove held enchantments, update expertise
10435 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10437 if (pItem->GetItemSuffixFactor())
10439 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10440 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10442 else
10444 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10445 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10448 UpdateExpertise(BASE_ATTACK);
10450 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10451 UpdateExpertise(OFF_ATTACK);
10454 // need update known currency
10455 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10456 UpdateKnownCurrencies(pItem->GetEntry(), false);
10458 m_items[slot] = NULL;
10459 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10461 if ( slot < EQUIPMENT_SLOT_END )
10462 SetVisibleItemSlot(slot, NULL);
10464 else
10466 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10467 if( pBag )
10468 pBag->RemoveItem(slot, update);
10470 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10471 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10472 pItem->SetSlot( NULL_SLOT );
10473 if( IsInWorld() && update )
10474 pItem->SendUpdateToPlayer( this );
10478 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10479 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10481 if(Item* it = GetItemByPos(bag,slot))
10483 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10484 RemoveItem(bag, slot, update);
10485 it->RemoveFromUpdateQueueOf(this);
10486 if(it->IsInWorld())
10488 it->RemoveFromWorld();
10489 it->DestroyForPlayer( this );
10494 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10495 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10497 // update quest counters
10498 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10500 // store item
10501 Item* pLastItem = StoreItem(dest, pItem, update);
10503 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10504 if(pLastItem == pItem)
10506 // update owner for last item (this can be original item with wrong owner
10507 if(pLastItem->GetOwnerGUID() != GetGUID())
10508 pLastItem->SetOwnerGUID(GetGUID());
10510 // if this original item then it need create record in inventory
10511 // in case trade we already have item in other player inventory
10512 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10516 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10518 Item *pItem = GetItemByPos( bag, slot );
10519 if( pItem )
10521 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10523 // start from destroy contained items (only equipped bag can have its)
10524 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10526 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10527 DestroyItem(slot, i, update);
10530 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10531 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10533 RemoveEnchantmentDurations(pItem);
10534 RemoveItemDurations(pItem);
10536 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10538 if( bag == INVENTORY_SLOT_BAG_0 )
10540 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10542 // equipment and equipped bags can have applied bonuses
10543 if ( slot < INVENTORY_SLOT_BAG_END )
10545 ItemPrototype const *pProto = pItem->GetProto();
10547 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10548 if(pProto && pProto->ItemSet)
10549 RemoveItemsSetItem(this, pProto);
10551 _ApplyItemMods(pItem, slot, false);
10554 if ( slot < EQUIPMENT_SLOT_END )
10556 // remove item dependent auras and casts (only weapon and armor slots)
10557 RemoveItemDependentAurasAndCasts(pItem);
10559 // update expertise
10560 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10561 UpdateExpertise(BASE_ATTACK);
10562 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10563 UpdateExpertise(OFF_ATTACK);
10565 // equipment visual show
10566 SetVisibleItemSlot(slot, NULL);
10568 // need update known currency
10569 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10570 UpdateKnownCurrencies(pItem->GetEntry(), false);
10572 m_items[slot] = NULL;
10574 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10575 pBag->RemoveItem(slot, update);
10577 if( IsInWorld() && update )
10579 pItem->RemoveFromWorld();
10580 pItem->DestroyForPlayer(this);
10583 //pItem->SetOwnerGUID(0);
10584 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10585 pItem->SetSlot( NULL_SLOT );
10586 pItem->SetState(ITEM_REMOVED, this);
10590 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10592 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10593 uint32 remcount = 0;
10595 // in inventory
10596 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10598 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10600 if (pItem->GetEntry() == item)
10602 if (pItem->GetCount() + remcount <= count)
10604 // all items in inventory can unequipped
10605 remcount += pItem->GetCount();
10606 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10608 if (remcount >= count)
10609 return;
10611 else
10613 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10614 pItem->SetCount( pItem->GetCount() - count + remcount );
10615 if (IsInWorld() & update)
10616 pItem->SendUpdateToPlayer( this );
10617 pItem->SetState(ITEM_CHANGED, this);
10618 return;
10624 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10626 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10628 if (pItem->GetEntry() == item)
10630 if (pItem->GetCount() + remcount <= count)
10632 // all keys can be unequipped
10633 remcount += pItem->GetCount();
10634 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10636 if (remcount >= count)
10637 return;
10639 else
10641 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10642 pItem->SetCount( pItem->GetCount() - count + remcount );
10643 if (IsInWorld() & update)
10644 pItem->SendUpdateToPlayer( this );
10645 pItem->SetState(ITEM_CHANGED, this);
10646 return;
10652 // in inventory bags
10653 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10655 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10657 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10659 if(Item* pItem = pBag->GetItemByPos(j))
10661 if (pItem->GetEntry() == item)
10663 // all items in bags can be unequipped
10664 if (pItem->GetCount() + remcount <= count)
10666 remcount += pItem->GetCount();
10667 DestroyItem( i, j, update );
10669 if (remcount >= count)
10670 return;
10672 else
10674 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10675 pItem->SetCount( pItem->GetCount() - count + remcount );
10676 if (IsInWorld() && update)
10677 pItem->SendUpdateToPlayer( this );
10678 pItem->SetState(ITEM_CHANGED, this);
10679 return;
10687 // in equipment and bag list
10688 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10690 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10692 if (pItem && pItem->GetEntry() == item)
10694 if (pItem->GetCount() + remcount <= count)
10696 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10698 remcount += pItem->GetCount();
10699 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10701 if (remcount >= count)
10702 return;
10705 else
10707 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10708 pItem->SetCount( pItem->GetCount() - count + remcount );
10709 if (IsInWorld() & update)
10710 pItem->SendUpdateToPlayer( this );
10711 pItem->SetState(ITEM_CHANGED, this);
10712 return;
10719 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10721 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10723 // in inventory
10724 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10725 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10726 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10727 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10729 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10730 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10731 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10732 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10734 // in inventory bags
10735 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10736 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10737 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10738 if (Item* pItem = pBag->GetItemByPos(j))
10739 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10740 DestroyItem(i, j, update);
10742 // in equipment and bag list
10743 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10744 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10745 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10746 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10749 void Player::DestroyConjuredItems( bool update )
10751 // used when entering arena
10752 // destroys all conjured items
10753 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10755 // in inventory
10756 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10757 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10758 if (pItem->IsConjuredConsumable())
10759 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10761 // in inventory bags
10762 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10763 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10764 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10765 if (Item* pItem = pBag->GetItemByPos(j))
10766 if (pItem->IsConjuredConsumable())
10767 DestroyItem( i, j, update);
10769 // in equipment and bag list
10770 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10771 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10772 if (pItem->IsConjuredConsumable())
10773 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10776 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10778 if(!pItem)
10779 return;
10781 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10783 if( pItem->GetCount() <= count )
10785 count -= pItem->GetCount();
10787 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10789 else
10791 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10792 pItem->SetCount( pItem->GetCount() - count );
10793 count = 0;
10794 if( IsInWorld() & update )
10795 pItem->SendUpdateToPlayer( this );
10796 pItem->SetState(ITEM_CHANGED, this);
10800 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10802 uint8 srcbag = src >> 8;
10803 uint8 srcslot = src & 255;
10805 uint8 dstbag = dst >> 8;
10806 uint8 dstslot = dst & 255;
10808 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10809 if( !pSrcItem )
10811 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10812 return;
10815 // not let split all items (can be only at cheating)
10816 if(pSrcItem->GetCount() == count)
10818 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10819 return;
10822 // not let split more existed items (can be only at cheating)
10823 if(pSrcItem->GetCount() < count)
10825 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10826 return;
10829 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10831 //best error message found for attempting to split while looting
10832 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10833 return;
10836 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10837 Item *pNewItem = pSrcItem->CloneItem( count, this );
10838 if( !pNewItem )
10840 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10841 return;
10844 if( IsInventoryPos( dst ) )
10846 // change item amount before check (for unique max count check)
10847 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10849 ItemPosCountVec dest;
10850 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10851 if( msg != EQUIP_ERR_OK )
10853 delete pNewItem;
10854 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10855 SendEquipError( msg, pSrcItem, NULL );
10856 return;
10859 if( IsInWorld() )
10860 pSrcItem->SendUpdateToPlayer( this );
10861 pSrcItem->SetState(ITEM_CHANGED, this);
10862 StoreItem( dest, pNewItem, true);
10864 else if( IsBankPos ( dst ) )
10866 // change item amount before check (for unique max count check)
10867 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10869 ItemPosCountVec dest;
10870 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10871 if( msg != EQUIP_ERR_OK )
10873 delete pNewItem;
10874 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10875 SendEquipError( msg, pSrcItem, NULL );
10876 return;
10879 if( IsInWorld() )
10880 pSrcItem->SendUpdateToPlayer( this );
10881 pSrcItem->SetState(ITEM_CHANGED, this);
10882 BankItem( dest, pNewItem, true);
10884 else if( IsEquipmentPos ( dst ) )
10886 // change item amount before check (for unique max count check), provide space for splitted items
10887 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10889 uint16 dest;
10890 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10891 if( msg != EQUIP_ERR_OK )
10893 delete pNewItem;
10894 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10895 SendEquipError( msg, pSrcItem, NULL );
10896 return;
10899 if( IsInWorld() )
10900 pSrcItem->SendUpdateToPlayer( this );
10901 pSrcItem->SetState(ITEM_CHANGED, this);
10902 EquipItem( dest, pNewItem, true);
10903 AutoUnequipOffhandIfNeed();
10907 void Player::SwapItem( uint16 src, uint16 dst )
10909 uint8 srcbag = src >> 8;
10910 uint8 srcslot = src & 255;
10912 uint8 dstbag = dst >> 8;
10913 uint8 dstslot = dst & 255;
10915 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10916 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10918 if( !pSrcItem )
10919 return;
10921 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10923 if(!isAlive() )
10925 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10926 return;
10929 // SRC checks
10931 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10933 //best error message found for attempting to swap while looting
10934 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10935 return;
10938 // check unequip potability for equipped items and bank bags
10939 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10941 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10942 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10943 if(msg != EQUIP_ERR_OK)
10945 SendEquipError( msg, pSrcItem, pDstItem );
10946 return;
10950 // prevent put equipped/bank bag in self
10951 if( IsBagPos ( src ) && srcslot == dstbag)
10953 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10954 return;
10957 // DST checks
10959 if (pDstItem)
10961 if(pDstItem->m_lootGenerated) // prevent swap looting item
10963 //best error message found for attempting to swap while looting
10964 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10965 return;
10968 // check unequip potability for equipped items and bank bags
10969 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10971 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10972 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10973 if(msg != EQUIP_ERR_OK)
10975 SendEquipError( msg, pSrcItem, pDstItem );
10976 return;
10981 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10982 // or swap empty bag with another empty or not empty bag (with items exchange)
10984 // Move case
10985 if( !pDstItem )
10987 if( IsInventoryPos( dst ) )
10989 ItemPosCountVec dest;
10990 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10991 if( msg != EQUIP_ERR_OK )
10993 SendEquipError( msg, pSrcItem, NULL );
10994 return;
10997 RemoveItem(srcbag, srcslot, true);
10998 StoreItem( dest, pSrcItem, true);
11000 else if( IsBankPos ( dst ) )
11002 ItemPosCountVec dest;
11003 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11004 if( msg != EQUIP_ERR_OK )
11006 SendEquipError( msg, pSrcItem, NULL );
11007 return;
11010 RemoveItem(srcbag, srcslot, true);
11011 BankItem( dest, pSrcItem, true);
11013 else if( IsEquipmentPos ( dst ) )
11015 uint16 dest;
11016 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11017 if( msg != EQUIP_ERR_OK )
11019 SendEquipError( msg, pSrcItem, NULL );
11020 return;
11023 RemoveItem(srcbag, srcslot, true);
11024 EquipItem(dest, pSrcItem, true);
11025 AutoUnequipOffhandIfNeed();
11028 return;
11031 // attempt merge to / fill target item
11032 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11034 uint8 msg;
11035 ItemPosCountVec sDest;
11036 uint16 eDest;
11037 if( IsInventoryPos( dst ) )
11038 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11039 else if( IsBankPos ( dst ) )
11040 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11041 else if( IsEquipmentPos ( dst ) )
11042 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11043 else
11044 return;
11046 // can be merge/fill
11047 if(msg == EQUIP_ERR_OK)
11049 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11051 RemoveItem(srcbag, srcslot, true);
11053 if( IsInventoryPos( dst ) )
11054 StoreItem( sDest, pSrcItem, true);
11055 else if( IsBankPos ( dst ) )
11056 BankItem( sDest, pSrcItem, true);
11057 else if( IsEquipmentPos ( dst ) )
11059 EquipItem( eDest, pSrcItem, true);
11060 AutoUnequipOffhandIfNeed();
11063 else
11065 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11066 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11067 pSrcItem->SetState(ITEM_CHANGED, this);
11068 pDstItem->SetState(ITEM_CHANGED, this);
11069 if( IsInWorld() )
11071 pSrcItem->SendUpdateToPlayer( this );
11072 pDstItem->SendUpdateToPlayer( this );
11075 return;
11079 // impossible merge/fill, do real swap
11080 uint8 msg;
11082 // check src->dest move possibility
11083 ItemPosCountVec sDest;
11084 uint16 eDest = 0;
11085 if( IsInventoryPos( dst ) )
11086 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11087 else if( IsBankPos( dst ) )
11088 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11089 else if( IsEquipmentPos( dst ) )
11091 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11092 if( msg == EQUIP_ERR_OK )
11093 msg = CanUnequipItem( eDest, true );
11096 if( msg != EQUIP_ERR_OK )
11098 SendEquipError( msg, pSrcItem, pDstItem );
11099 return;
11102 // check dest->src move possibility
11103 ItemPosCountVec sDest2;
11104 uint16 eDest2 = 0;
11105 if( IsInventoryPos( src ) )
11106 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11107 else if( IsBankPos( src ) )
11108 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11109 else if( IsEquipmentPos( src ) )
11111 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11112 if( msg == EQUIP_ERR_OK )
11113 msg = CanUnequipItem( eDest2, true);
11116 if( msg != EQUIP_ERR_OK )
11118 SendEquipError( msg, pDstItem, pSrcItem );
11119 return;
11122 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11123 if(pSrcItem->IsBag() && pDstItem->IsBag())
11125 Bag* emptyBag = NULL;
11126 Bag* fullBag = NULL;
11127 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11129 emptyBag = (Bag*)pSrcItem;
11130 fullBag = (Bag*)pDstItem;
11132 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11134 emptyBag = (Bag*)pDstItem;
11135 fullBag = (Bag*)pSrcItem;
11138 // bag swap (with items exchange) case
11139 if(emptyBag && fullBag)
11141 ItemPrototype const* emotyProto = emptyBag->GetProto();
11143 uint32 count = 0;
11145 for(int i=0; i < fullBag->GetBagSize(); ++i)
11147 Item *bagItem = fullBag->GetItemByPos(i);
11148 if (!bagItem)
11149 continue;
11151 ItemPrototype const* bagItemProto = bagItem->GetProto();
11152 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11154 // one from items not go to empty target bag
11155 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11156 return;
11159 ++count;
11163 if (count > emptyBag->GetBagSize())
11165 // too small targeted bag
11166 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11167 return;
11170 // Items swap
11171 count = 0; // will pos in new bag
11172 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11174 Item *bagItem = fullBag->GetItemByPos(i);
11175 if (!bagItem)
11176 continue;
11178 fullBag->RemoveItem(i, true);
11179 emptyBag->StoreItem(count, bagItem, true);
11180 bagItem->SetState(ITEM_CHANGED, this);
11182 ++count;
11187 // now do moves, remove...
11188 RemoveItem(dstbag, dstslot, false);
11189 RemoveItem(srcbag, srcslot, false);
11191 // add to dest
11192 if( IsInventoryPos( dst ) )
11193 StoreItem(sDest, pSrcItem, true);
11194 else if( IsBankPos( dst ) )
11195 BankItem(sDest, pSrcItem, true);
11196 else if( IsEquipmentPos( dst ) )
11197 EquipItem(eDest, pSrcItem, true);
11199 // add to src
11200 if( IsInventoryPos( src ) )
11201 StoreItem(sDest2, pDstItem, true);
11202 else if( IsBankPos( src ) )
11203 BankItem(sDest2, pDstItem, true);
11204 else if( IsEquipmentPos( src ) )
11205 EquipItem(eDest2, pDstItem, true);
11207 AutoUnequipOffhandIfNeed();
11210 void Player::AddItemToBuyBackSlot( Item *pItem )
11212 if( pItem )
11214 uint32 slot = m_currentBuybackSlot;
11215 // if current back slot non-empty search oldest or free
11216 if(m_items[slot])
11218 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11219 uint32 oldest_slot = BUYBACK_SLOT_START;
11221 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11223 // found empty
11224 if(!m_items[i])
11226 slot = i;
11227 break;
11230 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11232 if(oldest_time > i_time)
11234 oldest_time = i_time;
11235 oldest_slot = i;
11239 // find oldest
11240 slot = oldest_slot;
11243 RemoveItemFromBuyBackSlot( slot, true );
11244 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11246 m_items[slot] = pItem;
11247 time_t base = time(NULL);
11248 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11249 uint32 eslot = slot - BUYBACK_SLOT_START;
11251 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11252 ItemPrototype const *pProto = pItem->GetProto();
11253 if( pProto )
11254 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11255 else
11256 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11257 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11259 // move to next (for non filled list is move most optimized choice)
11260 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11261 ++m_currentBuybackSlot;
11265 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11267 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11268 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11269 return m_items[slot];
11270 return NULL;
11273 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11275 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11276 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11278 Item *pItem = m_items[slot];
11279 if( pItem )
11281 pItem->RemoveFromWorld();
11282 if(del) pItem->SetState(ITEM_REMOVED, this);
11285 m_items[slot] = NULL;
11287 uint32 eslot = slot - BUYBACK_SLOT_START;
11288 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11289 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11290 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11292 // if current backslot is filled set to now free slot
11293 if(m_items[m_currentBuybackSlot])
11294 m_currentBuybackSlot = slot;
11298 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11300 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11301 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11302 data << uint8(msg);
11304 if(msg)
11306 data << uint64(pItem ? pItem->GetGUID() : 0);
11307 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11308 data << uint8(0); // not 0 there...
11310 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11312 uint32 level = 0;
11314 if(pItem)
11315 if(ItemPrototype const* proto = pItem->GetProto())
11316 level = proto->RequiredLevel;
11318 data << uint32(level); // new 2.4.0
11321 GetSession()->SendPacket(&data);
11324 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11326 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11327 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11328 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11329 data << uint32(item);
11330 if( param > 0 )
11331 data << uint32(param);
11332 data << uint8(msg);
11333 GetSession()->SendPacket(&data);
11336 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11338 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11339 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11340 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11341 data << uint64(guid);
11342 if( param > 0 )
11343 data << uint32(param);
11344 data << uint8(msg);
11345 GetSession()->SendPacket(&data);
11348 void Player::ClearTrade()
11350 tradeGold = 0;
11351 acceptTrade = false;
11352 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11353 tradeItems[i] = NULL_SLOT;
11356 void Player::TradeCancel(bool sendback)
11358 if(pTrader)
11360 // send yellow "Trade canceled" message to both traders
11361 WorldSession* ws;
11362 ws = GetSession();
11363 if(sendback)
11364 ws->SendCancelTrade();
11365 ws = pTrader->GetSession();
11366 if(!ws->PlayerLogout())
11367 ws->SendCancelTrade();
11369 // cleanup
11370 ClearTrade();
11371 pTrader->ClearTrade();
11372 // prevent loss of reference
11373 pTrader->pTrader = NULL;
11374 pTrader = NULL;
11378 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11380 if(m_itemDuration.empty())
11381 return;
11383 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11385 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11387 Item* item = *itr;
11388 ++itr; // current element can be erased in UpdateDuration
11390 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11391 item->UpdateDuration(this,time);
11395 void Player::UpdateEnchantTime(uint32 time)
11397 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11399 assert(itr->item);
11400 next = itr;
11401 if(!itr->item->GetEnchantmentId(itr->slot))
11403 next = m_enchantDuration.erase(itr);
11405 else if(itr->leftduration <= time)
11407 ApplyEnchantment(itr->item, itr->slot, false, false);
11408 itr->item->ClearEnchantment(itr->slot);
11409 next = m_enchantDuration.erase(itr);
11411 else if(itr->leftduration > time)
11413 itr->leftduration -= time;
11414 ++next;
11419 void Player::AddEnchantmentDurations(Item *item)
11421 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11423 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11424 continue;
11426 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11427 if( duration > 0 )
11428 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11432 void Player::RemoveEnchantmentDurations(Item *item)
11434 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11436 if(itr->item == item)
11438 // save duration in item
11439 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11440 itr = m_enchantDuration.erase(itr);
11442 else
11443 ++itr;
11447 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11449 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11450 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11452 next = itr;
11453 if(itr->slot == slot)
11455 if(itr->item && itr->item->GetEnchantmentId(slot))
11457 // remove from stats
11458 ApplyEnchantment(itr->item, slot, false, false);
11459 // remove visual
11460 itr->item->ClearEnchantment(slot);
11462 // remove from update list
11463 next = m_enchantDuration.erase(itr);
11465 else
11466 ++next;
11469 // remove enchants from inventory items
11470 // NOTE: no need to remove these from stats, since these aren't equipped
11471 // in inventory
11472 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11474 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11475 if( pItem && pItem->GetEnchantmentId(slot) )
11476 pItem->ClearEnchantment(slot);
11479 // in inventory bags
11480 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11482 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11483 if( pBag )
11485 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11487 Item* pItem = pBag->GetItemByPos(j);
11488 if( pItem && pItem->GetEnchantmentId(slot) )
11489 pItem->ClearEnchantment(slot);
11495 // duration == 0 will remove item enchant
11496 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11498 if(!item)
11499 return;
11501 if(slot >= MAX_ENCHANTMENT_SLOT)
11502 return;
11504 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11506 if(itr->item == item && itr->slot == slot)
11508 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11509 m_enchantDuration.erase(itr);
11510 break;
11513 if(item && duration > 0 )
11515 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11516 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11520 void Player::ApplyEnchantment(Item *item,bool apply)
11522 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11523 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11526 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11528 if(!item)
11529 return;
11531 if(!item->IsEquipped())
11532 return;
11534 if(slot >= MAX_ENCHANTMENT_SLOT)
11535 return;
11537 uint32 enchant_id = item->GetEnchantmentId(slot);
11538 if(!enchant_id)
11539 return;
11541 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11542 if(!pEnchant)
11543 return;
11545 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11546 return;
11548 if (!item->IsBroken())
11550 for (int s = 0; s < 3; ++s)
11552 uint32 enchant_display_type = pEnchant->type[s];
11553 uint32 enchant_amount = pEnchant->amount[s];
11554 uint32 enchant_spell_id = pEnchant->spellid[s];
11556 switch(enchant_display_type)
11558 case ITEM_ENCHANTMENT_TYPE_NONE:
11559 break;
11560 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11561 // processed in Player::CastItemCombatSpell
11562 break;
11563 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11564 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11565 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11566 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11567 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11568 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11569 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11570 break;
11571 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11572 if(enchant_spell_id)
11574 if(apply)
11576 int32 basepoints = 0;
11577 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11578 if (item->GetItemRandomPropertyId())
11580 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11581 if (item_rand)
11583 // Search enchant_amount
11584 for (int k = 0; k < 3; ++k)
11586 if(item_rand->enchant_id[k] == enchant_id)
11588 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11589 break;
11594 // Cast custom spell vs all equal basepoints getted from enchant_amount
11595 if (basepoints)
11596 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11597 else
11598 CastSpell(this, enchant_spell_id, true, item);
11600 else
11601 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11603 break;
11604 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11605 if (!enchant_amount)
11607 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11608 if(item_rand)
11610 for (int k = 0; k < 3; ++k)
11612 if(item_rand->enchant_id[k] == enchant_id)
11614 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11615 break;
11621 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11622 break;
11623 case ITEM_ENCHANTMENT_TYPE_STAT:
11625 if (!enchant_amount)
11627 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11628 if(item_rand_suffix)
11630 for (int k = 0; k < 3; ++k)
11632 if(item_rand_suffix->enchant_id[k] == enchant_id)
11634 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11635 break;
11641 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11642 switch (enchant_spell_id)
11644 case ITEM_MOD_MANA:
11645 sLog.outDebug("+ %u MANA",enchant_amount);
11646 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11647 break;
11648 case ITEM_MOD_HEALTH:
11649 sLog.outDebug("+ %u HEALTH",enchant_amount);
11650 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11651 break;
11652 case ITEM_MOD_AGILITY:
11653 sLog.outDebug("+ %u AGILITY",enchant_amount);
11654 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11655 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11656 break;
11657 case ITEM_MOD_STRENGTH:
11658 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11659 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11660 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11661 break;
11662 case ITEM_MOD_INTELLECT:
11663 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11664 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11665 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11666 break;
11667 case ITEM_MOD_SPIRIT:
11668 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11669 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11670 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11671 break;
11672 case ITEM_MOD_STAMINA:
11673 sLog.outDebug("+ %u STAMINA",enchant_amount);
11674 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11675 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11676 break;
11677 case ITEM_MOD_DEFENSE_SKILL_RATING:
11678 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11679 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11680 break;
11681 case ITEM_MOD_DODGE_RATING:
11682 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11683 sLog.outDebug("+ %u DODGE", enchant_amount);
11684 break;
11685 case ITEM_MOD_PARRY_RATING:
11686 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11687 sLog.outDebug("+ %u PARRY", enchant_amount);
11688 break;
11689 case ITEM_MOD_BLOCK_RATING:
11690 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11691 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11692 break;
11693 case ITEM_MOD_HIT_MELEE_RATING:
11694 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11695 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11696 break;
11697 case ITEM_MOD_HIT_RANGED_RATING:
11698 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11699 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11700 break;
11701 case ITEM_MOD_HIT_SPELL_RATING:
11702 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11703 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11704 break;
11705 case ITEM_MOD_CRIT_MELEE_RATING:
11706 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11707 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11708 break;
11709 case ITEM_MOD_CRIT_RANGED_RATING:
11710 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11711 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11712 break;
11713 case ITEM_MOD_CRIT_SPELL_RATING:
11714 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11715 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11716 break;
11717 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11718 // in Enchantments
11719 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11720 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11721 // break;
11722 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11723 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11724 // break;
11725 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11726 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11727 // break;
11728 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11729 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11730 // break;
11731 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11732 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11733 // break;
11734 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11735 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11736 // break;
11737 // case ITEM_MOD_HASTE_MELEE_RATING:
11738 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11739 // break;
11740 // case ITEM_MOD_HASTE_RANGED_RATING:
11741 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11742 // break;
11743 case ITEM_MOD_HASTE_SPELL_RATING:
11744 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11745 break;
11746 case ITEM_MOD_HIT_RATING:
11747 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11748 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11749 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11750 sLog.outDebug("+ %u HIT", enchant_amount);
11751 break;
11752 case ITEM_MOD_CRIT_RATING:
11753 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11754 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11755 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11756 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11757 break;
11758 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11759 // case ITEM_MOD_HIT_TAKEN_RATING:
11760 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11761 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11762 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11763 // break;
11764 // case ITEM_MOD_CRIT_TAKEN_RATING:
11765 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11766 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11767 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11768 // break;
11769 case ITEM_MOD_RESILIENCE_RATING:
11770 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11771 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11772 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11773 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11774 break;
11775 case ITEM_MOD_HASTE_RATING:
11776 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11777 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11778 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11779 sLog.outDebug("+ %u HASTE", enchant_amount);
11780 break;
11781 case ITEM_MOD_EXPERTISE_RATING:
11782 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11783 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11784 break;
11785 case ITEM_MOD_ATTACK_POWER:
11786 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11787 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11788 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11789 break;
11790 case ITEM_MOD_RANGED_ATTACK_POWER:
11791 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11792 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11793 break;
11794 case ITEM_MOD_FERAL_ATTACK_POWER:
11795 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11796 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11797 break;
11798 case ITEM_MOD_SPELL_HEALING_DONE:
11799 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11800 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11801 break;
11802 case ITEM_MOD_SPELL_DAMAGE_DONE:
11803 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11804 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11805 break;
11806 case ITEM_MOD_MANA_REGENERATION:
11807 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11808 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11809 break;
11810 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11811 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11812 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11813 break;
11814 case ITEM_MOD_SPELL_POWER:
11815 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11816 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11817 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11818 break;
11819 default:
11820 break;
11822 break;
11824 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11826 if(getClass() == CLASS_SHAMAN)
11828 float addValue = 0.0f;
11829 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11831 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11832 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11834 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11836 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11837 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11840 break;
11842 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11843 // processed in Player::CastItemUseSpell
11844 break;
11845 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11846 // nothing do..
11847 break;
11848 default:
11849 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11850 break;
11851 } /*switch(enchant_display_type)*/
11852 } /*for*/
11855 // visualize enchantment at player and equipped items
11856 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11858 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11859 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11862 if(apply_dur)
11864 if(apply)
11866 // set duration
11867 uint32 duration = item->GetEnchantmentDuration(slot);
11868 if(duration > 0)
11869 AddEnchantmentDuration(item, slot, duration);
11871 else
11873 // duration == 0 will remove EnchantDuration
11874 AddEnchantmentDuration(item, slot, 0);
11879 void Player::SendEnchantmentDurations()
11881 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11883 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11887 void Player::SendItemDurations()
11889 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11891 (*itr)->SendTimeUpdate(this);
11895 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11897 if(!item) // prevent crash
11898 return;
11900 // last check 2.0.10
11901 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11902 data << uint64(GetGUID()); // player GUID
11903 data << uint32(received); // 0=looted, 1=from npc
11904 data << uint32(created); // 0=received, 1=created
11905 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11906 data << uint8(item->GetBagSlot()); // bagslot
11907 // item slot, but when added to stack: 0xFFFFFFFF
11908 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11909 data << uint32(item->GetEntry()); // item id
11910 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11911 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11912 data << uint32(count); // count of items
11913 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11915 if (broadcast && GetGroup())
11916 GetGroup()->BroadcastPacket(&data, true);
11917 else
11918 GetSession()->SendPacket(&data);
11921 /*********************************************************/
11922 /*** QUEST SYSTEM ***/
11923 /*********************************************************/
11925 void Player::PrepareQuestMenu( uint64 guid )
11927 Object *pObject;
11928 QuestRelations* pObjectQR;
11929 QuestRelations* pObjectQIR;
11931 // pets also can have quests
11932 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11933 if( pCreature )
11935 pObject = (Object*)pCreature;
11936 pObjectQR = &objmgr.mCreatureQuestRelations;
11937 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11939 else
11941 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11942 if( pGameObject )
11944 pObject = (Object*)pGameObject;
11945 pObjectQR = &objmgr.mGOQuestRelations;
11946 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11948 else
11949 return;
11952 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11953 qm.ClearMenu();
11955 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11957 uint32 quest_id = i->second;
11958 QuestStatus status = GetQuestStatus( quest_id );
11959 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11960 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11961 else if ( status == QUEST_STATUS_INCOMPLETE )
11962 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11963 else if (status == QUEST_STATUS_AVAILABLE )
11964 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11967 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11969 uint32 quest_id = i->second;
11970 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11971 if(!pQuest) continue;
11973 QuestStatus status = GetQuestStatus( quest_id );
11975 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11976 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11977 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11978 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11982 void Player::SendPreparedQuest( uint64 guid )
11984 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11985 if( questMenu.Empty() )
11986 return;
11988 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11990 uint32 status = qmi0.m_qIcon;
11992 // single element case
11993 if ( questMenu.MenuItemCount() == 1 )
11995 // Auto open -- maybe also should verify there is no greeting
11996 uint32 quest_id = qmi0.m_qId;
11997 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11999 if ( pQuest )
12001 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
12002 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
12003 else if( status == DIALOG_STATUS_INCOMPLETE )
12004 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
12005 // Send completable on repeatable quest if player don't have quest
12006 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
12007 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
12008 else
12009 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12012 // multiply entries
12013 else
12015 QEmote qe;
12016 qe._Delay = 0;
12017 qe._Emote = 0;
12018 std::string title = "";
12020 // need pet case for some quests
12021 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12022 if( pCreature )
12024 uint32 textid = pCreature->GetNpcTextId();
12025 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12026 if( !gossiptext )
12028 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12029 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12030 title = "";
12032 else
12034 qe = gossiptext->Options[0].Emotes[0];
12036 if(!gossiptext->Options[0].Text_0.empty())
12038 title = gossiptext->Options[0].Text_0;
12040 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12041 if (loc_idx >= 0)
12043 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12044 if (nl)
12046 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12047 title = nl->Text_0[0][loc_idx];
12051 else
12053 title = gossiptext->Options[0].Text_1;
12055 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12056 if (loc_idx >= 0)
12058 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12059 if (nl)
12061 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12062 title = nl->Text_1[0][loc_idx];
12068 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12072 bool Player::IsActiveQuest( uint32 quest_id ) const
12074 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12076 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12079 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12081 Object *pObject;
12082 QuestRelations* pObjectQR;
12083 QuestRelations* pObjectQIR;
12085 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12086 if( pCreature )
12088 pObject = (Object*)pCreature;
12089 pObjectQR = &objmgr.mCreatureQuestRelations;
12090 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12092 else
12094 GameObject *pGameObject = GetMap()->GetGameObject(guid);
12095 if( pGameObject )
12097 pObject = (Object*)pGameObject;
12098 pObjectQR = &objmgr.mGOQuestRelations;
12099 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12101 else
12102 return NULL;
12105 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12106 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12108 if (itr->second == nextQuestID)
12109 return objmgr.GetQuestTemplate(nextQuestID);
12112 return NULL;
12115 bool Player::CanSeeStartQuest( Quest const *pQuest )
12117 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12118 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12119 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12120 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12122 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12125 return false;
12128 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12130 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12131 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12132 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12133 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12134 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12135 && SatisfyQuestDay( pQuest, msg );
12138 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12140 if( !SatisfyQuestLog( msg ) )
12141 return false;
12143 uint32 srcitem = pQuest->GetSrcItemId();
12144 if( srcitem > 0 )
12146 uint32 count = pQuest->GetSrcItemCount();
12147 ItemPosCountVec dest;
12148 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12150 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12151 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12152 return true;
12153 else if( msg2 != EQUIP_ERR_OK )
12155 SendEquipError( msg2, NULL, NULL );
12156 return false;
12159 return true;
12162 bool Player::CanCompleteQuest( uint32 quest_id )
12164 if( quest_id )
12166 QuestStatusData& q_status = mQuestStatus[quest_id];
12167 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12168 return false; // not allow re-complete quest
12170 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12172 if(!qInfo)
12173 return false;
12175 // auto complete quest
12176 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12177 return true;
12179 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12182 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12184 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12186 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12187 return false;
12191 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12193 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12195 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12196 continue;
12198 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12199 return false;
12203 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12204 return false;
12206 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12207 return false;
12209 if ( qInfo->GetRewOrReqMoney() < 0 )
12211 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12212 return false;
12215 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12216 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12217 return false;
12219 return true;
12222 return false;
12225 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12227 // Solve problem that player don't have the quest and try complete it.
12228 // if repeatable she must be able to complete event if player don't have it.
12229 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12230 if( !CanTakeQuest(pQuest, false) )
12231 return false;
12233 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12234 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12235 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12236 return false;
12238 if( !CanRewardQuest(pQuest, false) )
12239 return false;
12241 return true;
12244 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12246 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12247 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12248 return false;
12250 // daily quest can't be rewarded (25 daily quest already completed)
12251 if(!SatisfyQuestDay(pQuest,true))
12252 return false;
12254 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12255 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12256 return false;
12258 // prevent receive reward with quest items in bank
12259 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12261 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12263 if( pQuest->ReqItemCount[i]!= 0 &&
12264 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12266 if(msg)
12267 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12268 return false;
12273 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12274 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12275 return false;
12277 return true;
12280 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12282 // prevent receive reward with quest items in bank or for not completed quest
12283 if(!CanRewardQuest(pQuest,msg))
12284 return false;
12286 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12288 if( pQuest->RewChoiceItemId[reward] )
12290 ItemPosCountVec dest;
12291 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12292 if( res != EQUIP_ERR_OK )
12294 SendEquipError( res, NULL, NULL );
12295 return false;
12300 if ( pQuest->GetRewItemsCount() > 0 )
12302 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12304 if( pQuest->RewItemId[i] )
12306 ItemPosCountVec dest;
12307 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12308 if( res != EQUIP_ERR_OK )
12310 SendEquipError( res, NULL, NULL );
12311 return false;
12317 return true;
12320 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12322 uint16 log_slot = FindQuestSlot( 0 );
12323 assert(log_slot < MAX_QUEST_LOG_SIZE);
12325 uint32 quest_id = pQuest->GetQuestId();
12327 // if not exist then created with set uState==NEW and rewarded=false
12328 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12330 // check for repeatable quests status reset
12331 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12332 questStatusData.m_explored = false;
12334 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12336 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12337 questStatusData.m_itemcount[i] = 0;
12340 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12342 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12343 questStatusData.m_creatureOrGOcount[i] = 0;
12346 GiveQuestSourceItem( pQuest );
12347 AdjustQuestReqItemCount( pQuest, questStatusData );
12349 if( pQuest->GetRepObjectiveFaction() )
12350 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12351 GetReputationMgr().SetVisible(factionEntry);
12353 uint32 qtime = 0;
12354 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12356 uint32 limittime = pQuest->GetLimitTime();
12358 // shared timed quest
12359 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12360 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12362 AddTimedQuest( quest_id );
12363 questStatusData.m_timer = limittime * IN_MILISECONDS;
12364 qtime = static_cast<uint32>(time(NULL)) + limittime;
12366 else
12367 questStatusData.m_timer = 0;
12369 SetQuestSlot(log_slot, quest_id, qtime);
12371 if (questStatusData.uState != QUEST_NEW)
12372 questStatusData.uState = QUEST_CHANGED;
12374 //starting initial quest script
12375 if(questGiver && pQuest->GetQuestStartScript()!=0)
12376 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12378 // Some spells applied at quest activation
12379 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12380 if(saBounds.first != saBounds.second)
12382 uint32 zone, area;
12383 GetZoneAndAreaId(zone,area);
12385 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12386 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12387 if( !HasAura(itr->second->spellId,0) )
12388 CastSpell(this,itr->second->spellId,true);
12391 UpdateForQuestWorldObjects();
12394 void Player::CompleteQuest( uint32 quest_id )
12396 if( quest_id )
12398 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12400 uint16 log_slot = FindQuestSlot( quest_id );
12401 if( log_slot < MAX_QUEST_LOG_SIZE)
12402 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12404 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12406 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12407 RewardQuest(qInfo,0,this,false);
12408 else
12409 SendQuestComplete( quest_id );
12414 void Player::IncompleteQuest( uint32 quest_id )
12416 if( quest_id )
12418 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12420 uint16 log_slot = FindQuestSlot( quest_id );
12421 if( log_slot < MAX_QUEST_LOG_SIZE)
12422 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12426 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12428 uint32 quest_id = pQuest->GetQuestId();
12430 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12432 if ( pQuest->ReqItemId[i] )
12433 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12436 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12437 // SetTimedQuest( 0 );
12438 m_timedquests.erase(pQuest->GetQuestId());
12440 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12442 if( pQuest->RewChoiceItemId[reward] )
12444 ItemPosCountVec dest;
12445 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12447 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12448 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12453 if ( pQuest->GetRewItemsCount() > 0 )
12455 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12457 if( pQuest->RewItemId[i] )
12459 ItemPosCountVec dest;
12460 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12462 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12463 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12469 RewardReputation( pQuest );
12471 if( pQuest->GetRewSpellCast() > 0 )
12472 CastSpell( this, pQuest->GetRewSpellCast(), true);
12473 else if( pQuest->GetRewSpell() > 0)
12474 CastSpell( this, pQuest->GetRewSpell(), true);
12476 uint16 log_slot = FindQuestSlot( quest_id );
12477 if( log_slot < MAX_QUEST_LOG_SIZE)
12478 SetQuestSlot(log_slot,0);
12480 QuestStatusData& q_status = mQuestStatus[quest_id];
12482 // Not give XP in case already completed once repeatable quest
12483 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12485 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12486 GiveXP( XP , NULL );
12487 else
12489 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12490 ModifyMoney( money );
12491 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12494 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12495 if(pQuest->GetRewOrReqMoney())
12497 ModifyMoney( pQuest->GetRewOrReqMoney() );
12499 if(pQuest->GetRewOrReqMoney() > 0)
12500 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12503 // honor reward
12504 if(pQuest->GetRewHonorableKills())
12505 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12507 // title reward
12508 if(pQuest->GetCharTitleId())
12510 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12511 SetTitle(titleEntry);
12514 if(pQuest->GetBonusTalents())
12516 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12517 InitTalentForLevel();
12520 // Send reward mail
12521 if(pQuest->GetRewMailTemplateId())
12523 MailMessageType mailType;
12524 uint32 senderGuidOrEntry;
12525 switch(questGiver->GetTypeId())
12527 case TYPEID_UNIT:
12528 mailType = MAIL_CREATURE;
12529 senderGuidOrEntry = questGiver->GetEntry();
12530 break;
12531 case TYPEID_GAMEOBJECT:
12532 mailType = MAIL_GAMEOBJECT;
12533 senderGuidOrEntry = questGiver->GetEntry();
12534 break;
12535 case TYPEID_ITEM:
12536 mailType = MAIL_ITEM;
12537 senderGuidOrEntry = questGiver->GetEntry();
12538 break;
12539 case TYPEID_PLAYER:
12540 mailType = MAIL_NORMAL;
12541 senderGuidOrEntry = questGiver->GetGUIDLow();
12542 break;
12543 default:
12544 mailType = MAIL_NORMAL;
12545 senderGuidOrEntry = GetGUIDLow();
12546 break;
12549 Loot questMailLoot;
12551 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12553 // fill mail
12554 MailItemsInfo mi; // item list preparing
12556 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12557 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12559 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12561 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12563 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12564 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12569 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12572 if(pQuest->IsDaily())
12574 SetDailyQuestStatus(quest_id);
12575 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12578 if ( !pQuest->IsRepeatable() )
12579 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12580 else
12581 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12583 q_status.m_rewarded = true;
12585 if(announce)
12586 SendQuestReward( pQuest, XP, questGiver );
12588 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12589 if (pQuest->GetZoneOrSort() > 0)
12590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12591 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12592 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12594 uint32 zone = 0;
12595 uint32 area = 0;
12597 // remove auras from spells with quest reward state limitations
12598 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12599 if(saEndBounds.first != saEndBounds.second)
12601 GetZoneAndAreaId(zone,area);
12603 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12604 if(!itr->second->IsFitToRequirements(this,zone,area))
12605 RemoveAurasDueToSpell(itr->second->spellId);
12608 // Some spells applied at quest reward
12609 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12610 if(saBounds.first != saBounds.second)
12612 if(!zone || !area)
12613 GetZoneAndAreaId(zone,area);
12615 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12616 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12617 if( !HasAura(itr->second->spellId,0) )
12618 CastSpell(this,itr->second->spellId,true);
12622 void Player::FailQuest( uint32 quest_id )
12624 if( quest_id )
12626 IncompleteQuest( quest_id );
12628 uint16 log_slot = FindQuestSlot( quest_id );
12629 if( log_slot < MAX_QUEST_LOG_SIZE)
12631 SetQuestSlotTimer(log_slot, 1 );
12632 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12634 SendQuestFailed( quest_id );
12638 void Player::FailTimedQuest( uint32 quest_id )
12640 if( quest_id )
12642 QuestStatusData& q_status = mQuestStatus[quest_id];
12644 q_status.m_timer = 0;
12645 if (q_status.uState != QUEST_NEW)
12646 q_status.uState = QUEST_CHANGED;
12648 IncompleteQuest( quest_id );
12650 uint16 log_slot = FindQuestSlot( quest_id );
12651 if( log_slot < MAX_QUEST_LOG_SIZE)
12653 SetQuestSlotTimer(log_slot, 1 );
12654 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12656 SendQuestTimerFailed( quest_id );
12660 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12662 int32 zoneOrSort = qInfo->GetZoneOrSort();
12663 int32 skillOrClass = qInfo->GetSkillOrClass();
12665 // skip zone zoneOrSort and 0 case skillOrClass
12666 if( zoneOrSort >= 0 && skillOrClass == 0 )
12667 return true;
12669 int32 questSort = -zoneOrSort;
12670 uint8 reqSortClass = ClassByQuestSort(questSort);
12672 // check class sort cases in zoneOrSort
12673 if( reqSortClass != 0 && getClass() != reqSortClass)
12675 if( msg )
12676 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12677 return false;
12680 // check class
12681 if( skillOrClass < 0 )
12683 uint8 reqClass = -int32(skillOrClass);
12684 if(getClass() != reqClass)
12686 if( msg )
12687 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12688 return false;
12691 // check skill
12692 else if( skillOrClass > 0 )
12694 uint32 reqSkill = skillOrClass;
12695 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12697 if( msg )
12698 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12699 return false;
12703 return true;
12706 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12708 if( getLevel() < qInfo->GetMinLevel() )
12710 if( msg )
12711 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12712 return false;
12714 return true;
12717 bool Player::SatisfyQuestLog( bool msg )
12719 // exist free slot
12720 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12721 return true;
12723 if( msg )
12725 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12726 GetSession()->SendPacket( &data );
12727 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12729 return false;
12732 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12734 // No previous quest (might be first quest in a series)
12735 if( qInfo->prevQuests.empty())
12736 return true;
12738 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12740 uint32 prevId = abs(*iter);
12742 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12743 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12745 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12747 // If any of the positive previous quests completed, return true
12748 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12750 // skip one-from-all exclusive group
12751 if(qPrevInfo->GetExclusiveGroup() >= 0)
12752 return true;
12754 // each-from-all exclusive group ( < 0)
12755 // can be start if only all quests in prev quest exclusive group completed and rewarded
12756 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12757 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12759 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12761 for(; iter2 != end; ++iter2)
12763 uint32 exclude_Id = iter2->second;
12765 // skip checked quest id, only state of other quests in group is interesting
12766 if(exclude_Id == prevId)
12767 continue;
12769 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12771 // alternative quest from group also must be completed and rewarded(reported)
12772 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12774 if( msg )
12775 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12776 return false;
12779 return true;
12781 // If any of the negative previous quests active, return true
12782 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12783 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12785 // skip one-from-all exclusive group
12786 if(qPrevInfo->GetExclusiveGroup() >= 0)
12787 return true;
12789 // each-from-all exclusive group ( < 0)
12790 // can be start if only all quests in prev quest exclusive group active
12791 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12792 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12794 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12796 for(; iter2 != end; ++iter2)
12798 uint32 exclude_Id = iter2->second;
12800 // skip checked quest id, only state of other quests in group is interesting
12801 if(exclude_Id == prevId)
12802 continue;
12804 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12806 // alternative quest from group also must be active
12807 if( i_exstatus == mQuestStatus.end() ||
12808 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12809 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12811 if( msg )
12812 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12813 return false;
12816 return true;
12821 // Has only positive prev. quests in non-rewarded state
12822 // and negative prev. quests in non-active state
12823 if( msg )
12824 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12826 return false;
12829 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12831 uint32 reqraces = qInfo->GetRequiredRaces();
12832 if ( reqraces == 0 )
12833 return true;
12834 if( (reqraces & getRaceMask()) == 0 )
12836 if( msg )
12837 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12838 return false;
12840 return true;
12843 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12845 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12846 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12848 if( msg )
12849 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12850 return false;
12853 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12854 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12856 if( msg )
12857 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12858 return false;
12861 return true;
12864 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12866 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12867 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12869 if( msg )
12870 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12871 return false;
12873 return true;
12876 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12878 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12880 if( msg )
12881 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12882 return false;
12884 return true;
12887 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12889 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12890 if(qInfo->GetExclusiveGroup() <= 0)
12891 return true;
12893 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12894 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12896 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12898 for(; iter != end; ++iter)
12900 uint32 exclude_Id = iter->second;
12902 // skip checked quest id, only state of other quests in group is interesting
12903 if(exclude_Id == qInfo->GetQuestId())
12904 continue;
12906 // not allow have daily quest if daily quest from exclusive group already recently completed
12907 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12908 if( !SatisfyQuestDay(Nquest, false) )
12910 if( msg )
12911 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12912 return false;
12915 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12917 // alternative quest already started or completed
12918 if( i_exstatus != mQuestStatus.end()
12919 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12921 if( msg )
12922 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12923 return false;
12926 return true;
12929 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12931 if(!qInfo->GetNextQuestInChain())
12932 return true;
12934 // next quest in chain already started or completed
12935 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12936 if( itr != mQuestStatus.end()
12937 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12939 if( msg )
12940 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12941 return false;
12944 // check for all quests further up the chain
12945 // only necessary if there are quest chains with more than one quest that can be skipped
12946 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12947 return true;
12950 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12952 // No previous quest in chain
12953 if( qInfo->prevChainQuests.empty())
12954 return true;
12956 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12958 uint32 prevId = *iter;
12960 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12962 if( i_prevstatus != mQuestStatus.end() )
12964 // If any of the previous quests in chain active, return false
12965 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12966 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12968 if( msg )
12969 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12970 return false;
12974 // check for all quests further down the chain
12975 // only necessary if there are quest chains with more than one quest that can be skipped
12976 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12977 // return false;
12980 // No previous quest in chain active
12981 return true;
12984 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12986 if(!qInfo->IsDaily())
12987 return true;
12989 bool have_slot = false;
12990 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12992 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12993 if(qInfo->GetQuestId()==id)
12994 return false;
12996 if(!id)
12997 have_slot = true;
13000 if(!have_slot)
13002 if( msg )
13003 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13004 return false;
13007 return true;
13010 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13012 uint32 srcitem = pQuest->GetSrcItemId();
13013 if( srcitem > 0 )
13015 uint32 count = pQuest->GetSrcItemCount();
13016 if( count <= 0 )
13017 count = 1;
13019 ItemPosCountVec dest;
13020 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13021 if( msg == EQUIP_ERR_OK )
13023 Item * item = StoreNewItem(dest, srcitem, true);
13024 SendNewItem(item, count, true, false);
13025 return true;
13027 // player already have max amount required item, just report success
13028 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13029 return true;
13030 else
13031 SendEquipError( msg, NULL, NULL );
13032 return false;
13035 return true;
13038 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13040 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13041 if( qInfo )
13043 uint32 srcitem = qInfo->GetSrcItemId();
13044 if( srcitem > 0 )
13046 uint32 count = qInfo->GetSrcItemCount();
13047 if( count <= 0 )
13048 count = 1;
13050 // exist one case when destroy source quest item not possible:
13051 // non un-equippable item (equipped non-empty bag, for example)
13052 uint8 res = CanUnequipItems(srcitem,count);
13053 if(res != EQUIP_ERR_OK)
13055 if(msg)
13056 SendEquipError( res, NULL, NULL );
13057 return false;
13060 DestroyItemCount(srcitem, count, true, true);
13063 return true;
13066 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13068 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13069 if( qInfo )
13071 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13072 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13073 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13074 && !qInfo->IsRepeatable() )
13075 return itr->second.m_rewarded;
13077 return false;
13079 return false;
13082 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13084 if( quest_id )
13086 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13087 if( itr != mQuestStatus.end() )
13088 return itr->second.m_status;
13090 return QUEST_STATUS_NONE;
13093 bool Player::CanShareQuest(uint32 quest_id) const
13095 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13096 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13098 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13099 if( itr != mQuestStatus.end() )
13100 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13102 return false;
13105 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13107 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13108 if( qInfo )
13110 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13112 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13113 m_timedquests.erase(qInfo->GetQuestId());
13116 QuestStatusData& q_status = mQuestStatus[quest_id];
13118 q_status.m_status = status;
13119 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13122 UpdateForQuestWorldObjects();
13125 // not used in MaNGOS, but used in scripting code
13126 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13128 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13129 if( !qInfo )
13130 return 0;
13132 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13133 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13134 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13136 return 0;
13139 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13141 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13143 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13145 uint32 reqitemcount = pQuest->ReqItemCount[i];
13146 if( reqitemcount != 0 )
13148 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13150 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13151 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13157 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13159 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13160 if ( GetQuestSlotQuestId(i) == quest_id )
13161 return i;
13163 return MAX_QUEST_LOG_SIZE;
13166 void Player::AreaExploredOrEventHappens( uint32 questId )
13168 if( questId )
13170 uint16 log_slot = FindQuestSlot( questId );
13171 if( log_slot < MAX_QUEST_LOG_SIZE)
13173 QuestStatusData& q_status = mQuestStatus[questId];
13175 if(!q_status.m_explored)
13177 q_status.m_explored = true;
13178 if (q_status.uState != QUEST_NEW)
13179 q_status.uState = QUEST_CHANGED;
13182 if( CanCompleteQuest( questId ) )
13183 CompleteQuest( questId );
13187 //not used in mangosd, function for external script library
13188 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13190 if( Group *pGroup = GetGroup() )
13192 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13194 Player *pGroupGuy = itr->getSource();
13196 // for any leave or dead (with not released body) group member at appropriate distance
13197 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13198 pGroupGuy->AreaExploredOrEventHappens(questId);
13201 else
13202 AreaExploredOrEventHappens(questId);
13205 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13207 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13209 uint32 questid = GetQuestSlotQuestId(i);
13210 if ( questid == 0 )
13211 continue;
13213 QuestStatusData& q_status = mQuestStatus[questid];
13215 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13216 continue;
13218 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13219 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13220 continue;
13222 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13224 uint32 reqitem = qInfo->ReqItemId[j];
13225 if ( reqitem == entry )
13227 uint32 reqitemcount = qInfo->ReqItemCount[j];
13228 uint32 curitemcount = q_status.m_itemcount[j];
13229 if ( curitemcount < reqitemcount )
13231 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13232 q_status.m_itemcount[j] += additemcount;
13233 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13235 SendQuestUpdateAddItem( qInfo, j, additemcount );
13237 if ( CanCompleteQuest( questid ) )
13238 CompleteQuest( questid );
13239 return;
13243 UpdateForQuestWorldObjects();
13246 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13248 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13250 uint32 questid = GetQuestSlotQuestId(i);
13251 if(!questid)
13252 continue;
13253 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13254 if ( !qInfo )
13255 continue;
13256 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13257 continue;
13259 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13261 uint32 reqitem = qInfo->ReqItemId[j];
13262 if ( reqitem == entry )
13264 QuestStatusData& q_status = mQuestStatus[questid];
13266 uint32 reqitemcount = qInfo->ReqItemCount[j];
13267 uint32 curitemcount;
13268 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13269 curitemcount = q_status.m_itemcount[j];
13270 else
13271 curitemcount = GetItemCount(entry,true);
13272 if ( curitemcount < reqitemcount + count )
13274 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13275 q_status.m_itemcount[j] = curitemcount - remitemcount;
13276 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13278 IncompleteQuest( questid );
13280 return;
13284 UpdateForQuestWorldObjects();
13287 void Player::KilledMonster( uint32 entry, uint64 guid )
13289 uint32 addkillcount = 1;
13290 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13291 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13293 uint32 questid = GetQuestSlotQuestId(i);
13294 if(!questid)
13295 continue;
13297 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13298 if( !qInfo )
13299 continue;
13300 // just if !ingroup || !noraidgroup || raidgroup
13301 QuestStatusData& q_status = mQuestStatus[questid];
13302 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13304 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13306 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13308 // skip GO activate objective or none
13309 if(qInfo->ReqCreatureOrGOId[j] <=0)
13310 continue;
13312 // skip Cast at creature objective
13313 if(qInfo->ReqSpell[j] !=0 )
13314 continue;
13316 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13318 if ( reqkill == entry )
13320 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13321 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13322 if ( curkillcount < reqkillcount )
13324 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13325 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13327 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13329 if ( CanCompleteQuest( questid ) )
13330 CompleteQuest( questid );
13332 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13333 continue;
13341 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13343 bool isCreature = IS_CREATURE_GUID(guid);
13345 uint32 addCastCount = 1;
13346 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13348 uint32 questid = GetQuestSlotQuestId(i);
13349 if(!questid)
13350 continue;
13352 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13353 if ( !qInfo )
13354 continue;
13356 QuestStatusData& q_status = mQuestStatus[questid];
13358 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13360 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13362 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13364 // skip kill creature objective (0) or wrong spell casts
13365 if(qInfo->ReqSpell[j] != spell_id )
13366 continue;
13368 uint32 reqTarget = 0;
13370 if(isCreature)
13372 // creature activate objectives
13373 if(qInfo->ReqCreatureOrGOId[j] > 0)
13374 // checked at quest_template loading
13375 reqTarget = qInfo->ReqCreatureOrGOId[j];
13377 else
13379 // GO activate objective
13380 if(qInfo->ReqCreatureOrGOId[j] < 0)
13381 // checked at quest_template loading
13382 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13385 // other not this creature/GO related objectives
13386 if( reqTarget != entry )
13387 continue;
13389 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13390 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13391 if ( curCastCount < reqCastCount )
13393 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13394 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13396 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13399 if ( CanCompleteQuest( questid ) )
13400 CompleteQuest( questid );
13402 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13403 break;
13410 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13412 uint32 addTalkCount = 1;
13413 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13415 uint32 questid = GetQuestSlotQuestId(i);
13416 if(!questid)
13417 continue;
13419 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13420 if ( !qInfo )
13421 continue;
13423 QuestStatusData& q_status = mQuestStatus[questid];
13425 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13427 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13429 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13431 // skip spell casts and Gameobject objectives
13432 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13433 continue;
13435 uint32 reqTarget = 0;
13437 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13438 // checked at quest_template loading
13439 reqTarget = qInfo->ReqCreatureOrGOId[j];
13440 else
13441 continue;
13443 if ( reqTarget == entry )
13445 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13446 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13447 if ( curTalkCount < reqTalkCount )
13449 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13450 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13452 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13454 if ( CanCompleteQuest( questid ) )
13455 CompleteQuest( questid );
13457 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13458 continue;
13466 void Player::MoneyChanged( uint32 count )
13468 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13470 uint32 questid = GetQuestSlotQuestId(i);
13471 if (!questid)
13472 continue;
13474 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13475 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13477 QuestStatusData& q_status = mQuestStatus[questid];
13479 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13481 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13483 if ( CanCompleteQuest( questid ) )
13484 CompleteQuest( questid );
13487 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13489 if(int32(count) < -qInfo->GetRewOrReqMoney())
13490 IncompleteQuest( questid );
13496 void Player::ReputationChanged(FactionEntry const* factionEntry )
13498 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13500 if(uint32 questid = GetQuestSlotQuestId(i))
13502 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13504 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13506 QuestStatusData& q_status = mQuestStatus[questid];
13507 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13509 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13510 if ( CanCompleteQuest( questid ) )
13511 CompleteQuest( questid );
13513 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13515 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13516 IncompleteQuest( questid );
13524 bool Player::HasQuestForItem( uint32 itemid ) const
13526 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13528 uint32 questid = GetQuestSlotQuestId(i);
13529 if ( questid == 0 )
13530 continue;
13532 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13533 if(qs_itr == mQuestStatus.end())
13534 continue;
13536 QuestStatusData const& q_status = qs_itr->second;
13538 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13540 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13541 if(!qinfo)
13542 continue;
13544 // hide quest if player is in raid-group and quest is no raid quest
13545 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13546 continue;
13548 // There should be no mixed ReqItem/ReqSource drop
13549 // This part for ReqItem drop
13550 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13552 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13553 return true;
13555 // This part - for ReqSource
13556 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13558 // examined item is a source item
13559 if (qinfo->ReqSourceId[j] == itemid)
13561 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13563 // 'unique' item
13564 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13565 return true;
13567 // allows custom amount drop when not 0
13568 if (qinfo->ReqSourceCount[j])
13570 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13571 return true;
13572 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13573 return true;
13578 return false;
13581 void Player::SendQuestComplete( uint32 quest_id )
13583 if( quest_id )
13585 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13586 data << uint32(quest_id);
13587 GetSession()->SendPacket( &data );
13588 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13592 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13594 uint32 questid = pQuest->GetQuestId();
13595 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13596 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13597 data << uint32(questid);
13599 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13601 data << uint32(XP);
13602 data << uint32(pQuest->GetRewOrReqMoney());
13604 else
13606 data << uint32(0);
13607 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13610 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13611 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13612 GetSession()->SendPacket( &data );
13614 if (pQuest->GetQuestCompleteScript() != 0)
13615 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13618 void Player::SendQuestFailed( uint32 quest_id )
13620 if( quest_id )
13622 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13623 data << quest_id;
13624 data << uint32(0); // failed reason (4 for inventory is full)
13625 GetSession()->SendPacket( &data );
13626 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13630 void Player::SendQuestTimerFailed( uint32 quest_id )
13632 if( quest_id )
13634 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13635 data << quest_id;
13636 GetSession()->SendPacket( &data );
13637 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13641 void Player::SendCanTakeQuestResponse( uint32 msg )
13643 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13644 data << uint32(msg);
13645 GetSession()->SendPacket( &data );
13646 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13649 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13651 if( pPlayer )
13653 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13654 data << uint64(pPlayer->GetGUID());
13655 data << uint8(msg); // valid values: 0-8
13656 GetSession()->SendPacket( &data );
13657 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13661 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13663 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13664 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13665 //data << pQuest->ReqItemId[item_idx];
13666 //data << count;
13667 GetSession()->SendPacket( &data );
13670 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13672 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13674 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13675 if (entry < 0)
13676 // client expected gameobject template id in form (id|0x80000000)
13677 entry = (-entry) | 0x80000000;
13679 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13680 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13681 data << uint32(pQuest->GetQuestId());
13682 data << uint32(entry);
13683 data << uint32(old_count + add_count);
13684 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13685 data << uint64(guid);
13686 GetSession()->SendPacket(&data);
13688 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13689 if( log_slot < MAX_QUEST_LOG_SIZE)
13690 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13693 /*********************************************************/
13694 /*** LOAD SYSTEM ***/
13695 /*********************************************************/
13697 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13699 bool delete_result = true;
13700 if (!result)
13702 // 0 1 2 3 4 5 6 7 8 9 10
13703 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login, zone FROM characters WHERE guid = '%u'",guid);
13704 if (!result)
13705 return false;
13707 else
13708 delete_result = false;
13710 Field *fields = result->Fetch();
13712 if (!LoadValues( fields[1].GetString()))
13714 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13715 if (delete_result)
13716 delete result;
13717 return false;
13720 // overwrite possible wrong/corrupted guid
13721 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13723 m_name = fields[2].GetCppString();
13725 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13726 SetMapId(fields[6].GetUInt32());
13727 // the instance id is not needed at character enum
13729 m_Played_time[0] = fields[7].GetUInt32();
13730 m_Played_time[1] = fields[8].GetUInt32();
13732 m_atLoginFlags = fields[9].GetUInt32();
13734 // I don't see these used anywhere ..
13735 /*_LoadGroup();
13737 _LoadBoundInstances();*/
13739 if (delete_result)
13740 delete result;
13742 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13743 m_items[i] = NULL;
13745 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
13746 m_deathState = DEAD;
13748 return true;
13751 void Player::_LoadDeclinedNames(QueryResult* result)
13753 if(!result)
13754 return;
13756 if(m_declinedname)
13757 delete m_declinedname;
13759 m_declinedname = new DeclinedName;
13760 Field *fields = result->Fetch();
13761 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13762 m_declinedname->name[i] = fields[i].GetCppString();
13764 delete result;
13767 void Player::_LoadArenaTeamInfo(QueryResult *result)
13769 // arenateamid, played_week, played_season, personal_rating
13770 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13771 if (!result)
13772 return;
13776 Field *fields = result->Fetch();
13778 uint32 arenateamid = fields[0].GetUInt32();
13779 uint32 played_week = fields[1].GetUInt32();
13780 uint32 played_season = fields[2].GetUInt32();
13781 uint32 personal_rating = fields[3].GetUInt32();
13783 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13784 if(!aTeam)
13786 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13787 continue;
13789 uint8 arenaSlot = aTeam->GetSlot();
13791 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13792 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13793 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13794 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13795 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13796 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13798 }while (result->NextRow());
13799 delete result;
13802 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13804 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13805 if(!result)
13806 return false;
13808 Field *fields = result->Fetch();
13810 x = fields[0].GetFloat();
13811 y = fields[1].GetFloat();
13812 z = fields[2].GetFloat();
13813 o = fields[3].GetFloat();
13814 mapid = fields[4].GetUInt32();
13815 in_flight = !fields[5].GetCppString().empty();
13817 delete result;
13818 return true;
13821 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13823 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13824 if( !result )
13825 return false;
13827 Field *fields = result->Fetch();
13829 data = StrSplit(fields[0].GetCppString(), " ");
13831 delete result;
13833 return true;
13836 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13838 if(index >= data.size())
13839 return 0;
13841 return (uint32)atoi(data[index].c_str());
13844 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13846 float result;
13847 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13848 memcpy(&result, &temp, sizeof(result));
13850 return result;
13853 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13855 Tokens data;
13856 if(!LoadValuesArrayFromDB(data,guid))
13857 return 0;
13859 return GetUInt32ValueFromArray(data,index);
13862 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13864 float result;
13865 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13866 memcpy(&result, &temp, sizeof(result));
13868 return result;
13871 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13873 //// 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
13874 //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);
13875 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13877 if(!result)
13879 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13880 return false;
13883 Field *fields = result->Fetch();
13885 uint32 dbAccountId = fields[1].GetUInt32();
13887 // check if the character's account in the db and the logged in account match.
13888 // player should be able to load/delete character only with correct account!
13889 if( dbAccountId != GetSession()->GetAccountId() )
13891 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13892 delete result;
13893 return false;
13896 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13898 m_name = fields[3].GetCppString();
13900 // check name limitations
13901 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13903 delete result;
13904 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13905 return false;
13908 if(!LoadValues( fields[2].GetString()))
13910 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13911 delete result;
13912 return false;
13915 // overwrite possible wrong/corrupted guid
13916 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13918 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13919 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13921 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13922 SetVisibleItemSlot(slot, NULL);
13924 if (m_items[slot])
13926 delete m_items[slot];
13927 m_items[slot] = NULL;
13931 // update money limits
13932 if(GetMoney() > MAX_MONEY_AMOUNT)
13933 SetMoney(MAX_MONEY_AMOUNT);
13935 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13936 outDebugValues();
13938 m_race = fields[4].GetUInt8();
13939 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13940 //Other way is to saves m_team into characters table.
13941 setFactionForRace(m_race);
13942 SetCharm(NULL);
13944 m_class = fields[5].GetUInt8();
13946 // load home bind and check in same time class/race pair, it used later for restore broken positions
13947 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13949 delete result;
13950 return false;
13953 InitPrimaryProfessions(); // to max set before any spell loaded
13955 // init saved position, and fix it later if problematic
13956 uint32 transGUID = fields[24].GetUInt32();
13957 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13958 SetMapId(fields[9].GetUInt32());
13959 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13961 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13963 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13965 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13966 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13967 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13969 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13971 // check arena teams integrity
13972 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13974 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13975 if(!arena_team_id)
13976 continue;
13978 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13979 if(at->HaveMember(GetGUID()))
13980 continue;
13982 // arena team not exist or not member, cleanup fields
13983 for(int j =0; j < 6; ++j)
13984 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13987 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13989 if(!IsPositionValid())
13991 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());
13992 RelocateToHomebind();
13994 transGUID = 0;
13996 m_movementInfo.t_x = 0.0f;
13997 m_movementInfo.t_y = 0.0f;
13998 m_movementInfo.t_z = 0.0f;
13999 m_movementInfo.t_o = 0.0f;
14002 uint32 bgid = fields[34].GetUInt32();
14003 uint32 bgteam = fields[35].GetUInt32();
14005 if(bgid) //saved in BattleGround
14007 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14009 // check entry point and fix to homebind if need
14010 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14011 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14012 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14014 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14016 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14018 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14019 AddBattleGroundQueueId(bgQueueTypeId);
14021 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14022 SetBGTeam(bgteam);
14024 //join player to battleground group
14025 currentBg->EventPlayerLoggedIn(this, GetGUID());
14026 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14028 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14030 else
14032 Relocate(GetBattleGroundEntryPoint());
14033 //RemoveArenaAuras(true);
14036 else
14038 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14039 // if server restart after player save in BG or area
14040 // player can have current coordinates in to BG/Arean map, fix this
14041 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14043 // return to BG master
14044 SetMapId(fields[36].GetUInt32());
14045 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14047 // check entry point and fix to homebind if need
14048 mapEntry = sMapStore.LookupEntry(GetMapId());
14049 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14050 RelocateToHomebind();
14054 if (transGUID != 0)
14056 m_movementInfo.t_x = fields[20].GetFloat();
14057 m_movementInfo.t_y = fields[21].GetFloat();
14058 m_movementInfo.t_z = fields[22].GetFloat();
14059 m_movementInfo.t_o = fields[23].GetFloat();
14061 if( !MaNGOS::IsValidMapCoord(
14062 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14063 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14064 // transport size limited
14065 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14067 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14068 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14069 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14071 RelocateToHomebind();
14073 m_movementInfo.t_x = 0.0f;
14074 m_movementInfo.t_y = 0.0f;
14075 m_movementInfo.t_z = 0.0f;
14076 m_movementInfo.t_o = 0.0f;
14078 transGUID = 0;
14082 if (transGUID != 0)
14084 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14086 if( (*iter)->GetGUIDLow() == transGUID)
14088 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14089 // client without expansion support
14090 if(GetSession()->Expansion() < transMapEntry->Expansion())
14092 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14093 break;
14096 m_transport = *iter;
14097 m_transport->AddPassenger(this);
14098 SetMapId(m_transport->GetMapId());
14099 break;
14103 if(!m_transport)
14105 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14106 guid,transGUID);
14108 RelocateToHomebind();
14110 m_movementInfo.t_x = 0.0f;
14111 m_movementInfo.t_y = 0.0f;
14112 m_movementInfo.t_z = 0.0f;
14113 m_movementInfo.t_o = 0.0f;
14115 transGUID = 0;
14118 else // not transport case
14120 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14121 // client without expansion support
14122 if(GetSession()->Expansion() < mapEntry->Expansion())
14124 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14125 RelocateToHomebind();
14129 // NOW player must have valid map
14130 // load the player's map here if it's not already loaded
14131 Map *map = GetMap();
14133 // since the player may not be bound to the map yet, make sure subsequent
14134 // getmap calls won't create new maps
14135 SetInstanceId(map->GetInstanceId());
14137 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14138 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14140 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14141 if(at)
14142 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14143 else
14144 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());
14147 SaveRecallPosition();
14149 time_t now = time(NULL);
14150 time_t logoutTime = time_t(fields[16].GetUInt64());
14152 // since last logout (in seconds)
14153 uint64 time_diff = uint64(now - logoutTime);
14155 // set value, including drunk invisibility detection
14156 // calculate sobering. after 15 minutes logged out, the player will be sober again
14157 float soberFactor;
14158 if(time_diff > 15*MINUTE)
14159 soberFactor = 0;
14160 else
14161 soberFactor = 1-time_diff/(15.0f*MINUTE);
14162 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14163 SetDrunkValue(newDrunkenValue);
14165 m_rest_bonus = fields[15].GetFloat();
14166 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14167 float bubble0 = 0.031;
14168 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14169 float bubble1 = 0.125;
14171 if((int32)fields[16].GetUInt32() > 0)
14173 float bubble = fields[17].GetUInt32() > 0
14174 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14175 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14177 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14180 m_cinematic = fields[12].GetUInt32();
14181 m_Played_time[0]= fields[13].GetUInt32();
14182 m_Played_time[1]= fields[14].GetUInt32();
14184 m_resetTalentsCost = fields[18].GetUInt32();
14185 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14187 // reserve some flags
14188 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14190 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14191 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14193 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14195 uint32 extraflags = fields[25].GetUInt32();
14197 m_stableSlots = fields[26].GetUInt32();
14198 if(m_stableSlots > MAX_PET_STABLES)
14200 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14201 m_stableSlots = MAX_PET_STABLES;
14204 m_atLoginFlags = fields[27].GetUInt32();
14206 // Honor system
14207 // Update Honor kills data
14208 m_lastHonorUpdateTime = logoutTime;
14209 UpdateHonorFields();
14211 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14212 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14213 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14215 std::string taxi_nodes = fields[31].GetCppString();
14217 delete result;
14219 // clear channel spell data (if saved at channel spell casting)
14220 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14221 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14223 // clear charm/summon related fields
14224 SetCharm(NULL);
14225 SetPet(NULL);
14226 SetCharmerGUID(0);
14227 SetOwnerGUID(0);
14228 SetCreatorGUID(0);
14230 // reset some aura modifiers before aura apply
14231 SetFarSightGUID(0);
14232 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14233 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14235 _LoadSkills();
14237 // make sure the unit is considered out of combat for proper loading
14238 ClearInCombat();
14240 // make sure the unit is considered not in duel for proper loading
14241 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14242 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14244 // remember loaded power/health values to restore after stats initialization and modifier applying
14245 uint32 savedHealth = GetHealth();
14246 uint32 savedPower[MAX_POWERS];
14247 for(uint32 i = 0; i < MAX_POWERS; ++i)
14248 savedPower[i] = GetPower(Powers(i));
14250 // reset stats before loading any modifiers
14251 InitStatsForLevel();
14252 InitTaxiNodesForLevel();
14253 InitGlyphsForLevel();
14254 InitRunes();
14256 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14258 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14259 //_LoadMail();
14261 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14262 _LoadGlyphAuras();
14264 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14265 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14266 m_deathState = DEAD;
14268 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14270 // after spell load, learn rewarded spell if need also
14271 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14272 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14274 // after spell and quest load
14275 InitTalentForLevel();
14276 learnDefaultSpells();
14278 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14280 // must be before inventory (some items required reputation check)
14281 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14283 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14285 // update items with duration and realtime
14286 UpdateItemDuration(time_diff, true);
14288 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14290 // unread mails and next delivery time, actual mails not loaded
14291 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14293 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14295 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14296 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14297 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14299 if(!HasTitle(curTitle))
14300 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14303 // Not finish taxi flight path
14304 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14306 // problems with taxi path loading
14307 TaxiNodesEntry const* nodeEntry = NULL;
14308 if(uint32 node_id = m_taxi.GetTaxiSource())
14309 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14311 if(!nodeEntry) // don't know taxi start node, to homebind
14313 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14314 RelocateToHomebind();
14315 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14317 else // have start node, to it
14319 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14320 SetMapId(nodeEntry->map_id);
14321 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14322 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14324 m_taxi.ClearTaxiDestinations();
14326 else if(uint32 node_id = m_taxi.GetTaxiSource())
14328 // save source node as recall coord to prevent recall and fall from sky
14329 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14330 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14331 m_recallMap = nodeEntry->map_id;
14332 m_recallX = nodeEntry->x;
14333 m_recallY = nodeEntry->y;
14334 m_recallZ = nodeEntry->z;
14336 // flight will started later
14339 // has to be called after last Relocate() in Player::LoadFromDB
14340 SetFallInformation(0, GetPositionZ());
14342 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14344 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14345 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14346 if(!isAlive())
14347 RemoveAllAurasOnDeath();
14349 //apply all stat bonuses from items and auras
14350 SetCanModifyStats(true);
14351 UpdateAllStats();
14353 // restore remembered power/health values (but not more max values)
14354 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14355 for(uint32 i = 0; i < MAX_POWERS; ++i)
14356 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14358 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14359 outDebugValues();
14361 // GM state
14362 if(GetSession()->GetSecurity() > SEC_PLAYER)
14364 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14366 default:
14367 case 0: break; // disable
14368 case 1: SetGameMaster(true); break; // enable
14369 case 2: // save state
14370 if(extraflags & PLAYER_EXTRA_GM_ON)
14371 SetGameMaster(true);
14372 break;
14375 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14377 default:
14378 case 0: SetGMVisible(false); break; // invisible
14379 case 1: break; // visible
14380 case 2: // save state
14381 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14382 SetGMVisible(false);
14383 break;
14386 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14388 default:
14389 case 0: break; // disable
14390 case 1: SetAcceptTicket(true); break; // enable
14391 case 2: // save state
14392 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14393 SetAcceptTicket(true);
14394 break;
14397 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14399 default:
14400 case 0: break; // disable
14401 case 1: SetGMChat(true); break; // enable
14402 case 2: // save state
14403 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14404 SetGMChat(true);
14405 break;
14408 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14410 default:
14411 case 0: break; // disable
14412 case 1: SetAcceptWhispers(true); break; // enable
14413 case 2: // save state
14414 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14415 SetAcceptWhispers(true);
14416 break;
14420 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14422 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14423 m_achievementMgr.CheckAllAchievementCriteria();
14424 return true;
14427 bool Player::isAllowedToLoot(Creature* creature)
14429 if(Player* recipient = creature->GetLootRecipient())
14431 if (recipient == this)
14432 return true;
14433 if( Group* otherGroup = recipient->GetGroup())
14435 Group* thisGroup = GetGroup();
14436 if(!thisGroup)
14437 return false;
14438 return thisGroup == otherGroup;
14440 return false;
14442 else
14443 // prevent other players from looting if the recipient got disconnected
14444 return !creature->hasLootRecipient();
14447 void Player::_LoadActions(QueryResult *result)
14449 m_actionButtons.clear();
14451 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14453 if(result)
14457 Field *fields = result->Fetch();
14459 uint8 button = fields[0].GetUInt8();
14461 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14462 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14463 else
14465 sLog.outError( " ...at loading, and will deleted in DB also");
14467 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14468 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14471 while( result->NextRow() );
14473 delete result;
14477 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14479 m_Auras.clear();
14480 for (int i = 0; i < TOTAL_AURAS; ++i)
14481 m_modAuras[i].clear();
14483 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14485 if(result)
14489 Field *fields = result->Fetch();
14490 uint64 caster_guid = fields[0].GetUInt64();
14491 uint32 spellid = fields[1].GetUInt32();
14492 uint32 effindex = fields[2].GetUInt32();
14493 uint32 stackcount = fields[3].GetUInt32();
14494 int32 damage = (int32)fields[4].GetUInt32();
14495 int32 maxduration = (int32)fields[5].GetUInt32();
14496 int32 remaintime = (int32)fields[6].GetUInt32();
14497 int32 remaincharges = (int32)fields[7].GetUInt32();
14499 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14500 if(!spellproto)
14502 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14503 continue;
14506 if(effindex >= 3)
14508 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14509 continue;
14512 // negative effects should continue counting down after logout
14513 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14515 if(remaintime <= int32(timediff))
14516 continue;
14518 remaintime -= timediff;
14521 // prevent wrong values of remaincharges
14522 if(spellproto->procCharges)
14524 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14525 remaincharges = spellproto->procCharges;
14527 else
14528 remaincharges = 0;
14531 for(uint32 i=0; i<stackcount; ++i)
14533 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14534 if(!damage)
14535 damage = aura->GetModifier()->m_amount;
14537 // reset stolen single target auras
14538 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14539 aura->SetIsSingleTarget(false);
14541 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14542 AddAura(aura);
14543 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14546 while( result->NextRow() );
14548 delete result;
14551 if(m_class == CLASS_WARRIOR)
14552 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14555 void Player::_LoadGlyphAuras()
14557 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14559 if (uint32 glyph = GetGlyph(i))
14561 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14563 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14565 if(gp->TypeFlags == gs->TypeFlags)
14567 CastSpell(this, gp->SpellId, true);
14568 continue;
14570 else
14571 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14573 else
14574 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14576 else
14577 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14579 // On any error remove glyph
14580 SetGlyph(i, 0);
14585 void Player::LoadCorpse()
14587 if( isAlive() )
14589 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14591 else
14593 if(Corpse *corpse = GetCorpse())
14595 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14597 else
14599 //Prevent Dead Player login without corpse
14600 ResurrectPlayer(0.5f);
14605 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14607 //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());
14608 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14609 //NOTE: the "order by `bag`" is important because it makes sure
14610 //the bagMap is filled before items in the bags are loaded
14611 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14612 //expected to be equipped before offhand items (TODO: fixme)
14614 uint32 zone = GetZoneId();
14616 if (result)
14618 std::list<Item*> problematicItems;
14620 // prevent items from being added to the queue when stored
14621 m_itemUpdateQueueBlocked = true;
14624 Field *fields = result->Fetch();
14625 uint32 bag_guid = fields[1].GetUInt32();
14626 uint8 slot = fields[2].GetUInt8();
14627 uint32 item_guid = fields[3].GetUInt32();
14628 uint32 item_id = fields[4].GetUInt32();
14630 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14632 if(!proto)
14634 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14635 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14636 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14637 continue;
14640 Item *item = NewItemOrBag(proto);
14642 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14644 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14645 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14646 item->FSetState(ITEM_REMOVED);
14647 item->SaveToDB(); // it also deletes item object !
14648 continue;
14651 // not allow have in alive state item limited to another map/zone
14652 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14654 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14655 item->FSetState(ITEM_REMOVED);
14656 item->SaveToDB(); // it also deletes item object !
14657 continue;
14660 // "Conjured items disappear if you are logged out for more than 15 minutes"
14661 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14663 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14664 item->FSetState(ITEM_REMOVED);
14665 item->SaveToDB(); // it also deletes item object !
14666 continue;
14669 bool success = true;
14671 if (!bag_guid)
14673 // the item is not in a bag
14674 item->SetContainer( NULL );
14675 item->SetSlot(slot);
14677 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14679 ItemPosCountVec dest;
14680 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14681 item = StoreItem(dest, item, true);
14682 else
14683 success = false;
14685 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14687 uint16 dest;
14688 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14689 QuickEquipItem(dest, item);
14690 else
14691 success = false;
14693 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14695 ItemPosCountVec dest;
14696 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14697 item = BankItem(dest, item, true);
14698 else
14699 success = false;
14702 if(success)
14704 // store bags that may contain items in them
14705 if(item->IsBag() && IsBagPos(item->GetPos()))
14706 bagMap[item_guid] = (Bag*)item;
14709 else
14711 item->SetSlot(NULL_SLOT);
14712 // the item is in a bag, find the bag
14713 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14714 if(itr != bagMap.end())
14715 itr->second->StoreItem(slot, item, true );
14716 else
14717 success = false;
14720 // item's state may have changed after stored
14721 if (success)
14722 item->SetState(ITEM_UNCHANGED, this);
14723 else
14725 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);
14726 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14727 problematicItems.push_back(item);
14729 } while (result->NextRow());
14731 delete result;
14732 m_itemUpdateQueueBlocked = false;
14734 // send by mail problematic items
14735 while(!problematicItems.empty())
14737 // fill mail
14738 MailItemsInfo mi; // item list preparing
14740 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14742 Item* item = problematicItems.front();
14743 problematicItems.pop_front();
14745 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14748 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14750 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14753 //if(isAlive())
14754 _ApplyAllItemMods();
14757 // load mailed item which should receive current player
14758 void Player::_LoadMailedItems(Mail *mail)
14760 // data needs to be at first place for Item::LoadFromDB
14761 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);
14762 if(!result)
14763 return;
14767 Field *fields = result->Fetch();
14768 uint32 item_guid_low = fields[1].GetUInt32();
14769 uint32 item_template = fields[2].GetUInt32();
14771 mail->AddItem(item_guid_low, item_template);
14773 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14775 if(!proto)
14777 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);
14778 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14779 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14780 continue;
14783 Item *item = NewItemOrBag(proto);
14785 if(!item->LoadFromDB(item_guid_low, 0, result))
14787 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14788 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14789 item->FSetState(ITEM_REMOVED);
14790 item->SaveToDB(); // it also deletes item object !
14791 continue;
14794 AddMItem(item);
14795 } while (result->NextRow());
14797 delete result;
14800 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14802 //set a count of unread mails
14803 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14804 if (resultUnread)
14806 Field *fieldMail = resultUnread->Fetch();
14807 unReadMails = fieldMail[0].GetUInt8();
14808 delete resultUnread;
14811 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14812 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14813 if (resultDelivery)
14815 Field *fieldMail = resultDelivery->Fetch();
14816 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14817 delete resultDelivery;
14821 void Player::_LoadMail()
14823 m_mail.clear();
14824 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14825 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());
14826 if(result)
14830 Field *fields = result->Fetch();
14831 Mail *m = new Mail;
14832 m->messageID = fields[0].GetUInt32();
14833 m->messageType = fields[1].GetUInt8();
14834 m->sender = fields[2].GetUInt32();
14835 m->receiver = fields[3].GetUInt32();
14836 m->subject = fields[4].GetCppString();
14837 m->itemTextId = fields[5].GetUInt32();
14838 bool has_items = fields[6].GetBool();
14839 m->expire_time = (time_t)fields[7].GetUInt64();
14840 m->deliver_time = (time_t)fields[8].GetUInt64();
14841 m->money = fields[9].GetUInt32();
14842 m->COD = fields[10].GetUInt32();
14843 m->checked = fields[11].GetUInt32();
14844 m->stationery = fields[12].GetUInt8();
14845 m->mailTemplateId = fields[13].GetInt16();
14847 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14849 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14850 m->mailTemplateId = 0;
14853 m->state = MAIL_STATE_UNCHANGED;
14855 if (has_items)
14856 _LoadMailedItems(m);
14858 m_mail.push_back(m);
14859 } while( result->NextRow() );
14860 delete result;
14862 m_mailsLoaded = true;
14865 void Player::LoadPet()
14867 //fixme: the pet should still be loaded if the player is not in world
14868 // just not added to the map
14869 if(IsInWorld())
14871 Pet *pet = new Pet;
14872 if(!pet->LoadPetFromDB(this,0,0,true))
14873 delete pet;
14877 void Player::_LoadQuestStatus(QueryResult *result)
14879 mQuestStatus.clear();
14881 uint32 slot = 0;
14883 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14884 //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());
14886 if(result)
14890 Field *fields = result->Fetch();
14892 uint32 quest_id = fields[0].GetUInt32();
14893 // used to be new, no delete?
14894 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14895 if( pQuest )
14897 // find or create
14898 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14900 uint32 qstatus = fields[1].GetUInt32();
14901 if(qstatus < MAX_QUEST_STATUS)
14902 questStatusData.m_status = QuestStatus(qstatus);
14903 else
14905 questStatusData.m_status = QUEST_STATUS_NONE;
14906 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14909 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14910 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14912 time_t quest_time = time_t(fields[4].GetUInt64());
14914 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14916 AddTimedQuest( quest_id );
14918 if (quest_time <= sWorld.GetGameTime())
14919 questStatusData.m_timer = 1;
14920 else
14921 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14923 else
14924 quest_time = 0;
14926 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14927 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14928 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14929 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14930 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14931 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14932 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14933 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14935 questStatusData.uState = QUEST_UNCHANGED;
14937 // add to quest log
14938 if( slot < MAX_QUEST_LOG_SIZE &&
14939 ( questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
14940 questStatusData.m_status == QUEST_STATUS_COMPLETE &&
14941 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14943 SetQuestSlot(slot, quest_id, quest_time);
14945 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14946 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
14948 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14949 if(questStatusData.m_creatureOrGOcount[idx])
14950 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
14952 ++slot;
14955 if(questStatusData.m_rewarded)
14957 // learn rewarded spell if unknown
14958 learnQuestRewardedSpells(pQuest);
14960 // set rewarded title if any
14961 if(pQuest->GetCharTitleId())
14963 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14964 SetTitle(titleEntry);
14967 if(pQuest->GetBonusTalents())
14968 m_questRewardTalentCount += pQuest->GetBonusTalents();
14971 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14974 while( result->NextRow() );
14976 delete result;
14979 // clear quest log tail
14980 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14981 SetQuestSlot(i, 0);
14984 void Player::_LoadDailyQuestStatus(QueryResult *result)
14986 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14987 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14989 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14991 if(result)
14993 uint32 quest_daily_idx = 0;
14997 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14999 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15000 break;
15003 Field *fields = result->Fetch();
15005 uint32 quest_id = fields[0].GetUInt32();
15007 // save _any_ from daily quest times (it must be after last reset anyway)
15008 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15010 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15011 if( !pQuest )
15012 continue;
15014 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15015 ++quest_daily_idx;
15017 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15019 while( result->NextRow() );
15021 delete result;
15024 m_DailyQuestChanged = false;
15027 void Player::_LoadSpells(QueryResult *result)
15029 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15031 if(result)
15035 Field *fields = result->Fetch();
15037 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15039 while( result->NextRow() );
15041 delete result;
15045 void Player::_LoadTutorials(QueryResult *result)
15047 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15049 if(result)
15053 Field *fields = result->Fetch();
15055 for (int iI=0; iI<8; ++iI)
15056 m_Tutorials[iI] = fields[iI].GetUInt32();
15058 while( result->NextRow() );
15060 delete result;
15063 m_TutorialsChanged = false;
15066 void Player::_LoadGroup(QueryResult *result)
15068 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15069 if(result)
15071 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15072 delete result;
15073 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15074 if(group)
15076 uint8 subgroup = group->GetMemberGroup(GetGUID());
15077 SetGroup(group, subgroup);
15078 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15080 // the group leader may change the instance difficulty while the player is offline
15081 SetDifficulty(group->GetDifficulty());
15087 void Player::_LoadBoundInstances(QueryResult *result)
15089 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15090 m_boundInstances[i].clear();
15092 Group *group = GetGroup();
15094 //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));
15095 if(result)
15099 Field *fields = result->Fetch();
15100 bool perm = fields[1].GetBool();
15101 uint32 mapId = fields[2].GetUInt32();
15102 uint32 instanceId = fields[0].GetUInt32();
15103 uint8 difficulty = fields[3].GetUInt8();
15104 time_t resetTime = (time_t)fields[4].GetUInt64();
15105 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15106 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15107 // and in that case it is not used
15109 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15110 if(!mapEntry || !mapEntry->IsDungeon())
15112 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15113 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15114 continue;
15117 if(!perm && group)
15119 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);
15120 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15121 continue;
15124 // since non permanent binds are always solo bind, they can always be reset
15125 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15126 if(save) BindToInstance(save, perm, true);
15127 } while(result->NextRow());
15128 delete result;
15132 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15134 // some instances only have one difficulty
15135 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15136 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15138 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15139 if(itr != m_boundInstances[difficulty].end())
15140 return &itr->second;
15141 else
15142 return NULL;
15145 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15147 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15148 UnbindInstance(itr, difficulty, unload);
15151 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15153 if(itr != m_boundInstances[difficulty].end())
15155 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15156 itr->second.save->RemovePlayer(this); // save can become invalid
15157 m_boundInstances[difficulty].erase(itr++);
15161 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15163 if(save)
15165 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15166 if(bind.save)
15168 // update the save when the group kills a boss
15169 if(permanent != bind.perm || save != bind.save)
15170 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());
15172 else
15173 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15175 if(bind.save != save)
15177 if(bind.save) bind.save->RemovePlayer(this);
15178 save->AddPlayer(this);
15181 if(permanent) save->SetCanReset(false);
15183 bind.save = save;
15184 bind.perm = permanent;
15185 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());
15186 return &bind;
15188 else
15189 return NULL;
15192 void Player::SendRaidInfo()
15194 uint32 counter = 0;
15196 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15198 size_t p_counter = data.wpos();
15199 data << uint32(counter); // placeholder
15201 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15203 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15205 if(itr->second.perm)
15207 InstanceSave *save = itr->second.save;
15208 data << uint32(save->GetMapId());
15209 data << uint32(save->GetResetTime() - time(NULL));
15210 data << uint32(save->GetInstanceId());
15211 data << uint32(save->GetDifficulty());
15212 ++counter;
15216 data.put<uint32>(p_counter, counter);
15217 GetSession()->SendPacket(&data);
15221 - called on every successful teleportation to a map
15223 void Player::SendSavedInstances()
15225 bool hasBeenSaved = false;
15226 WorldPacket data;
15228 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15230 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15232 if(itr->second.perm) // only permanent binds are sent
15234 hasBeenSaved = true;
15235 break;
15240 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15241 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15242 data << uint32(hasBeenSaved);
15243 GetSession()->SendPacket(&data);
15245 if(!hasBeenSaved)
15246 return;
15248 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15250 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15252 if(itr->second.perm)
15254 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15255 data << uint32(itr->second.save->GetMapId());
15256 GetSession()->SendPacket(&data);
15262 /// convert the player's binds to the group
15263 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15265 bool has_binds = false;
15266 bool has_solo = false;
15268 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15269 assert(player_guid);
15271 // copy all binds to the group, when changing leader it's assumed the character
15272 // will not have any solo binds
15274 if(player)
15276 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15278 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15280 has_binds = true;
15281 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15282 // permanent binds are not removed
15283 if(!itr->second.perm)
15285 player->UnbindInstance(itr, i, true); // increments itr
15286 has_solo = true;
15288 else
15289 ++itr;
15294 // if the player's not online we don't know what binds it has
15295 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));
15296 // the following should not get executed when changing leaders
15297 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15300 bool Player::_LoadHomeBind(QueryResult *result)
15302 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15303 if(!info)
15305 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15306 return false;
15309 bool ok = false;
15310 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15311 if (result)
15313 Field *fields = result->Fetch();
15314 m_homebindMapId = fields[0].GetUInt32();
15315 m_homebindZoneId = fields[1].GetUInt16();
15316 m_homebindX = fields[2].GetFloat();
15317 m_homebindY = fields[3].GetFloat();
15318 m_homebindZ = fields[4].GetFloat();
15319 delete result;
15321 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15323 // accept saved data only for valid position (and non instanceable), and accessable
15324 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15325 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15327 ok = true;
15329 else
15330 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15333 if(!ok)
15335 m_homebindMapId = info->mapId;
15336 m_homebindZoneId = info->zoneId;
15337 m_homebindX = info->positionX;
15338 m_homebindY = info->positionY;
15339 m_homebindZ = info->positionZ;
15341 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);
15344 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15345 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15347 return true;
15350 /*********************************************************/
15351 /*** SAVE SYSTEM ***/
15352 /*********************************************************/
15354 void Player::SaveToDB()
15356 // delay auto save at any saves (manual, in code, or autosave)
15357 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15359 // first save/honor gain after midnight will also update the player's honor fields
15360 UpdateHonorFields();
15362 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15363 //save, far from tavern/city
15364 //save, but in tavern/city
15365 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15366 outDebugValues();
15368 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15369 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15370 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15371 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15372 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15373 uint32 tmp_displayid = GetDisplayId();
15375 // Set player sit state to standing on save, also stealth and shifted form
15376 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15377 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15378 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15379 SetDisplayId(GetNativeDisplayId());
15381 bool inworld = IsInWorld();
15383 CharacterDatabase.BeginTransaction();
15385 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15387 std::string sql_name = m_name;
15388 CharacterDatabase.escape_string(sql_name);
15390 std::ostringstream ss;
15391 ss << "INSERT INTO characters (guid,account,name,race,class,"
15392 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15393 "taximask, online, cinematic, "
15394 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15395 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15396 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15397 << GetGUIDLow() << ", "
15398 << GetSession()->GetAccountId() << ", '"
15399 << sql_name << "', "
15400 << m_race << ", "
15401 << m_class << ", ";
15403 if(!IsBeingTeleported())
15405 ss << GetMapId() << ", "
15406 << (uint32)GetDifficulty() << ", "
15407 << finiteAlways(GetPositionX()) << ", "
15408 << finiteAlways(GetPositionY()) << ", "
15409 << finiteAlways(GetPositionZ()) << ", "
15410 << finiteAlways(GetOrientation()) << ", '";
15412 else
15414 ss << GetTeleportDest().mapid << ", "
15415 << (uint32)GetDifficulty() << ", "
15416 << finiteAlways(GetTeleportDest().x) << ", "
15417 << finiteAlways(GetTeleportDest().y) << ", "
15418 << finiteAlways(GetTeleportDest().z) << ", "
15419 << finiteAlways(GetTeleportDest().o) << ", '";
15422 uint16 i;
15423 for( i = 0; i < m_valuesCount; ++i )
15425 ss << GetUInt32Value(i) << " ";
15428 ss << "', ";
15430 ss << m_taxi; // string with TaxiMaskSize numbers
15432 ss << ", ";
15433 ss << (inworld ? 1 : 0);
15435 ss << ", ";
15436 ss << m_cinematic;
15438 ss << ", ";
15439 ss << m_Played_time[0];
15440 ss << ", ";
15441 ss << m_Played_time[1];
15443 ss << ", ";
15444 ss << finiteAlways(m_rest_bonus);
15445 ss << ", ";
15446 ss << (uint64)time(NULL);
15447 ss << ", ";
15448 ss << is_save_resting;
15449 ss << ", ";
15450 ss << m_resetTalentsCost;
15451 ss << ", ";
15452 ss << (uint64)m_resetTalentsTime;
15454 ss << ", ";
15455 ss << finiteAlways(m_movementInfo.t_x);
15456 ss << ", ";
15457 ss << finiteAlways(m_movementInfo.t_y);
15458 ss << ", ";
15459 ss << finiteAlways(m_movementInfo.t_z);
15460 ss << ", ";
15461 ss << finiteAlways(m_movementInfo.t_o);
15462 ss << ", ";
15463 if (m_transport)
15464 ss << m_transport->GetGUIDLow();
15465 else
15466 ss << "0";
15468 ss << ", ";
15469 ss << m_ExtraFlags;
15471 ss << ", ";
15472 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15474 ss << ", ";
15475 ss << uint32(m_atLoginFlags);
15477 ss << ", ";
15478 ss << GetZoneId();
15480 ss << ", ";
15481 ss << (uint64)m_deathExpireTime;
15483 ss << ", '";
15484 ss << m_taxi.SaveTaxiDestinationsToString();
15485 ss << "', '0', ";
15486 ss << GetBattleGroundId();
15487 ss << ", ";
15488 ss << GetBGTeam();
15489 ss << ", ";
15490 ss << m_bgEntryPoint.mapid << ", "
15491 << finiteAlways(m_bgEntryPoint.x) << ", "
15492 << finiteAlways(m_bgEntryPoint.y) << ", "
15493 << finiteAlways(m_bgEntryPoint.z) << ", "
15494 << finiteAlways(m_bgEntryPoint.o);
15495 ss << ")";
15497 CharacterDatabase.Execute( ss.str().c_str() );
15499 if(m_mailsUpdated) //save mails only when needed
15500 _SaveMail();
15502 _SaveInventory();
15503 _SaveQuestStatus();
15504 _SaveDailyQuestStatus();
15505 _SaveTutorials();
15506 _SaveSpells();
15507 _SaveSpellCooldowns();
15508 _SaveActions();
15509 _SaveAuras();
15510 m_achievementMgr.SaveToDB();
15511 m_reputationMgr.SaveToDB();
15513 CharacterDatabase.CommitTransaction();
15515 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15516 SetDisplayId(tmp_displayid);
15517 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15518 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15519 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15520 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15522 // save pet (hunter pet level and experience and all type pets health/mana).
15523 if(Pet* pet = GetPet())
15524 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15527 // fast save function for item/money cheating preventing - save only inventory and money state
15528 void Player::SaveInventoryAndGoldToDB()
15530 _SaveInventory();
15531 //money is in data field
15532 SaveDataFieldToDB();
15535 void Player::_SaveActions()
15537 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15539 switch (itr->second.uState)
15541 case ACTIONBUTTON_NEW:
15542 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15543 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15544 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15545 ++itr;
15546 break;
15547 case ACTIONBUTTON_CHANGED:
15548 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15549 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15550 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15551 ++itr;
15552 break;
15553 case ACTIONBUTTON_DELETED:
15554 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15555 m_actionButtons.erase(itr++);
15556 break;
15557 default:
15558 ++itr;
15559 break;
15564 void Player::_SaveAuras()
15566 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15568 AuraMap const& auras = GetAuras();
15570 if (auras.empty())
15571 return;
15573 spellEffectPair lastEffectPair = auras.begin()->first;
15574 uint32 stackCounter = 1;
15576 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15578 if(itr == auras.end() || lastEffectPair != itr->first)
15580 AuraMap::const_iterator itr2 = itr;
15581 // save previous spellEffectPair to db
15582 itr2--;
15584 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15586 //skip all auras from spells that are passive or need a shapeshift
15587 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15589 //do not save single target auras (unless they were cast by the player)
15590 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15592 uint8 i;
15593 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15594 for (i = 0; i < 3; ++i)
15595 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15596 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15597 break;
15599 if (i == 3)
15601 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15602 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15603 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()));
15608 if(itr == auras.end())
15609 break;
15612 if (lastEffectPair == itr->first)
15613 stackCounter++;
15614 else
15616 lastEffectPair = itr->first;
15617 stackCounter = 1;
15622 void Player::_SaveInventory()
15624 // force items in buyback slots to new state
15625 // and remove those that aren't already
15626 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15628 Item *item = m_items[i];
15629 if (!item || item->GetState() == ITEM_NEW) continue;
15630 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15631 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15632 m_items[i]->FSetState(ITEM_NEW);
15635 // update enchantment durations
15636 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15638 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15641 // if no changes
15642 if (m_itemUpdateQueue.empty()) return;
15644 // do not save if the update queue is corrupt
15645 bool error = false;
15646 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15648 Item *item = m_itemUpdateQueue[i];
15649 if(!item || item->GetState() == ITEM_REMOVED) continue;
15650 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15652 if (test == NULL)
15654 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());
15655 error = true;
15657 else if (test != item)
15659 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());
15660 error = true;
15664 if (error)
15666 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15667 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15668 return;
15671 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15673 Item *item = m_itemUpdateQueue[i];
15674 if(!item) continue;
15676 Bag *container = item->GetContainer();
15677 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15679 switch(item->GetState())
15681 case ITEM_NEW:
15682 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());
15683 break;
15684 case ITEM_CHANGED:
15685 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());
15686 break;
15687 case ITEM_REMOVED:
15688 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15689 break;
15690 case ITEM_UNCHANGED:
15691 break;
15694 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15696 m_itemUpdateQueue.clear();
15699 void Player::_SaveMail()
15701 if (!m_mailsLoaded)
15702 return;
15704 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15706 Mail *m = (*itr);
15707 if (m->state == MAIL_STATE_CHANGED)
15709 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15710 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15711 if(m->removedItems.size())
15713 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15714 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15715 m->removedItems.clear();
15717 m->state = MAIL_STATE_UNCHANGED;
15719 else if (m->state == MAIL_STATE_DELETED)
15721 if (m->HasItems())
15722 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15723 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15724 if (m->itemTextId)
15725 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15726 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15727 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15731 //deallocate deleted mails...
15732 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15734 if ((*itr)->state == MAIL_STATE_DELETED)
15736 Mail* m = *itr;
15737 m_mail.erase(itr);
15738 delete m;
15739 itr = m_mail.begin();
15741 else
15742 ++itr;
15745 m_mailsUpdated = false;
15748 void Player::_SaveQuestStatus()
15750 // we don't need transactions here.
15751 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15753 switch (i->second.uState)
15755 case QUEST_NEW :
15756 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15757 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15758 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]);
15759 break;
15760 case QUEST_CHANGED :
15761 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15762 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 );
15763 break;
15764 case QUEST_UNCHANGED:
15765 break;
15767 i->second.uState = QUEST_UNCHANGED;
15771 void Player::_SaveDailyQuestStatus()
15773 if(!m_DailyQuestChanged)
15774 return;
15776 m_DailyQuestChanged = false;
15778 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15780 // we don't need transactions here.
15781 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15782 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15783 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15784 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15785 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15788 void Player::_SaveSpells()
15790 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15792 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15793 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15795 // add only changed/new not dependent spells
15796 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15797 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);
15799 if (itr->second->state == PLAYERSPELL_REMOVED)
15801 delete itr->second;
15802 m_spells.erase(itr++);
15804 else
15806 itr->second->state = PLAYERSPELL_UNCHANGED;
15807 ++itr;
15813 void Player::_SaveTutorials()
15815 if(!m_TutorialsChanged)
15816 return;
15818 uint32 Rows=0;
15819 // it's better than rebuilding indexes multiple times
15820 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15821 if(result)
15823 Rows = result->Fetch()[0].GetUInt32();
15824 delete result;
15827 if (Rows)
15829 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15830 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
15832 else
15834 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
15837 m_TutorialsChanged = false;
15840 void Player::outDebugValues() const
15842 if(!sLog.IsOutDebug()) // optimize disabled debug output
15843 return;
15845 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15846 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15847 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15848 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15849 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15850 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15851 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15852 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15853 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15854 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15855 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15856 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15859 /*********************************************************/
15860 /*** FLOOD FILTER SYSTEM ***/
15861 /*********************************************************/
15863 void Player::UpdateSpeakTime()
15865 // ignore chat spam protection for GMs in any mode
15866 if(GetSession()->GetSecurity() > SEC_PLAYER)
15867 return;
15869 time_t current = time (NULL);
15870 if(m_speakTime > current)
15872 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15873 if(!max_count)
15874 return;
15876 ++m_speakCount;
15877 if(m_speakCount >= max_count)
15879 // prevent overwrite mute time, if message send just before mutes set, for example.
15880 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15881 if(GetSession()->m_muteTime < new_mute)
15882 GetSession()->m_muteTime = new_mute;
15884 m_speakCount = 0;
15887 else
15888 m_speakCount = 0;
15890 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15893 bool Player::CanSpeak() const
15895 return GetSession()->m_muteTime <= time (NULL);
15898 /*********************************************************/
15899 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15900 /*********************************************************/
15902 void Player::SendAttackSwingNotInRange()
15904 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15905 GetSession()->SendPacket( &data );
15908 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15910 std::ostringstream ss;
15911 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15912 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15913 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15914 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15915 sLog.outDebug(ss.str().c_str());
15916 CharacterDatabase.Execute(ss.str().c_str());
15919 void Player::SaveDataFieldToDB()
15921 std::ostringstream ss;
15922 ss<<"UPDATE characters SET data='";
15924 for(uint16 i = 0; i < m_valuesCount; ++i )
15926 ss << GetUInt32Value(i) << " ";
15928 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15930 CharacterDatabase.Execute(ss.str().c_str());
15933 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15935 std::ostringstream ss2;
15936 ss2<<"UPDATE characters SET data='";
15937 int i=0;
15938 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15940 ss2<<tokens[i]<<" ";
15942 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15944 return CharacterDatabase.Execute(ss2.str().c_str());
15947 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15949 char buf[11];
15950 snprintf(buf,11,"%u",value);
15952 if(index >= tokens.size())
15953 return;
15955 tokens[index] = buf;
15958 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15960 Tokens tokens;
15961 if(!LoadValuesArrayFromDB(tokens,guid))
15962 return;
15964 if(index >= tokens.size())
15965 return;
15967 char buf[11];
15968 snprintf(buf,11,"%u",value);
15969 tokens[index] = buf;
15971 SaveValuesArrayInDB(tokens,guid);
15974 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15976 uint32 temp;
15977 memcpy(&temp, &value, sizeof(value));
15978 Player::SetUInt32ValueInDB(index, temp, guid);
15981 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15983 Tokens tokens;
15984 if(!LoadValuesArrayFromDB(tokens, guid))
15985 return;
15987 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15988 uint8 race = unit_bytes0 & 0xFF;
15989 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15991 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15992 if(!info)
15993 return;
15995 unit_bytes0 &= ~(0xFF << 16);
15996 unit_bytes0 |= (gender << 16);
15997 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15999 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
16000 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
16002 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
16004 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
16005 player_bytes2 &= ~0xFF;
16006 player_bytes2 |= facialHair;
16007 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
16009 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16010 player_bytes3 &= ~0xFF;
16011 player_bytes3 |= gender;
16012 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16014 SaveValuesArrayInDB(tokens, guid);
16017 void Player::SendAttackSwingNotStanding()
16019 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16020 GetSession()->SendPacket( &data );
16023 void Player::SendAttackSwingDeadTarget()
16025 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16026 GetSession()->SendPacket( &data );
16029 void Player::SendAttackSwingCantAttack()
16031 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16032 GetSession()->SendPacket( &data );
16035 void Player::SendAttackSwingCancelAttack()
16037 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16038 GetSession()->SendPacket( &data );
16041 void Player::SendAttackSwingBadFacingAttack()
16043 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16044 GetSession()->SendPacket( &data );
16047 void Player::SendAutoRepeatCancel()
16049 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16050 data.append(GetPackGUID()); // may be it's target guid
16051 GetSession()->SendPacket( &data );
16054 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16056 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16057 data << Area;
16058 data << Experience;
16059 GetSession()->SendPacket(&data);
16062 void Player::SendDungeonDifficulty(bool IsInGroup)
16064 uint8 val = 0x00000001;
16065 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16066 data << (uint32)GetDifficulty();
16067 data << uint32(val);
16068 data << uint32(IsInGroup);
16069 GetSession()->SendPacket(&data);
16072 void Player::SendResetFailedNotify(uint32 mapid)
16074 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16075 data << uint32(mapid);
16076 GetSession()->SendPacket(&data);
16079 /// Reset all solo instances and optionally send a message on success for each
16080 void Player::ResetInstances(uint8 method)
16082 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16084 // we assume that when the difficulty changes, all instances that can be reset will be
16085 uint8 dif = GetDifficulty();
16087 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16089 InstanceSave *p = itr->second.save;
16090 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16091 if(!entry || !p->CanReset())
16093 ++itr;
16094 continue;
16097 if(method == INSTANCE_RESET_ALL)
16099 // the "reset all instances" method can only reset normal maps
16100 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16102 ++itr;
16103 continue;
16107 // if the map is loaded, reset it
16108 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16109 if(map && map->IsDungeon())
16110 ((InstanceMap*)map)->Reset(method);
16112 // since this is a solo instance there should not be any players inside
16113 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16114 SendResetInstanceSuccess(p->GetMapId());
16116 p->DeleteFromDB();
16117 m_boundInstances[dif].erase(itr++);
16119 // the following should remove the instance save from the manager and delete it as well
16120 p->RemovePlayer(this);
16124 void Player::SendResetInstanceSuccess(uint32 MapId)
16126 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16127 data << MapId;
16128 GetSession()->SendPacket(&data);
16131 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16133 // TODO: find what other fail reasons there are besides players in the instance
16134 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16135 data << reason;
16136 data << MapId;
16137 GetSession()->SendPacket(&data);
16140 /*********************************************************/
16141 /*** Update timers ***/
16142 /*********************************************************/
16144 ///checks the 15 afk reports per 5 minutes limit
16145 void Player::UpdateAfkReport(time_t currTime)
16147 if(m_bgAfkReportedTimer <= currTime)
16149 m_bgAfkReportedCount = 0;
16150 m_bgAfkReportedTimer = currTime+5*MINUTE;
16154 void Player::UpdateContestedPvP(uint32 diff)
16156 if(!m_contestedPvPTimer||isInCombat())
16157 return;
16158 if(m_contestedPvPTimer <= diff)
16160 ResetContestedPvP();
16162 else
16163 m_contestedPvPTimer -= diff;
16166 void Player::UpdatePvPFlag(time_t currTime)
16168 if(!IsPvP())
16169 return;
16170 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16171 return;
16173 UpdatePvP(false);
16176 void Player::UpdateDuelFlag(time_t currTime)
16178 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16179 return;
16181 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16182 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16184 duel->startTimer = 0;
16185 duel->startTime = currTime;
16186 duel->opponent->duel->startTimer = 0;
16187 duel->opponent->duel->startTime = currTime;
16190 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16192 if(!pet)
16193 pet = GetPet();
16195 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16197 //returning of reagents only for players, so best done here
16198 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16199 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16201 if(spellInfo)
16203 for(uint32 i = 0; i < 7; ++i)
16205 if(spellInfo->Reagent[i] > 0)
16207 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16208 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16209 if( msg == EQUIP_ERR_OK )
16211 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16212 if(IsInWorld())
16213 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16218 m_temporaryUnsummonedPetNumber = 0;
16221 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16222 return;
16224 // only if current pet in slot
16225 switch(pet->getPetType())
16227 case MINI_PET:
16228 m_miniPet = 0;
16229 break;
16230 case GUARDIAN_PET:
16231 m_guardianPets.erase(pet->GetGUID());
16232 break;
16233 default:
16234 if(GetPetGUID() == pet->GetGUID())
16235 SetPet(NULL);
16236 break;
16239 pet->CombatStop();
16241 if(returnreagent)
16243 switch(pet->GetEntry())
16245 //warlock pets except imp are removed(?) when logging out
16246 case 1860:
16247 case 1863:
16248 case 417:
16249 case 17252:
16250 mode = PET_SAVE_NOT_IN_SLOT;
16251 break;
16255 pet->SavePetToDB(mode);
16257 pet->CleanupsBeforeDelete();
16258 pet->AddObjectToRemoveList();
16259 pet->m_removed = true;
16261 if(pet->isControlled())
16263 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16264 data << uint64(0);
16265 data << uint32(0);
16266 GetSession()->SendPacket(&data);
16268 if(GetGroup())
16269 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16273 void Player::RemoveMiniPet()
16275 if(Pet* pet = GetMiniPet())
16277 pet->Remove(PET_SAVE_AS_DELETED);
16278 m_miniPet = 0;
16282 Pet* Player::GetMiniPet()
16284 if(!m_miniPet)
16285 return NULL;
16286 return ObjectAccessor::GetPet(m_miniPet);
16289 void Player::RemoveGuardians()
16291 while(!m_guardianPets.empty())
16293 uint64 guid = *m_guardianPets.begin();
16294 if(Pet* pet = ObjectAccessor::GetPet(guid))
16295 pet->Remove(PET_SAVE_AS_DELETED);
16297 m_guardianPets.erase(guid);
16301 bool Player::HasGuardianWithEntry(uint32 entry)
16303 // pet guid middle part is entry (and creature also)
16304 // and in guardian list must be guardians with same entry _always_
16305 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16307 if(Pet* pet = ObjectAccessor::GetPet(*itr))
16308 if (pet->GetEntry() == entry)
16309 return true;
16312 return false;
16315 void Player::Uncharm()
16317 Unit* charm = GetCharm();
16318 if(!charm)
16319 return;
16321 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16322 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16325 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16327 *data << (uint8)msgtype;
16328 *data << (uint32)language;
16329 *data << (uint64)GetGUID();
16330 *data << (uint32)language; //language 2.1.0 ?
16331 *data << (uint64)GetGUID();
16332 *data << (uint32)(text.length()+1);
16333 *data << text;
16334 *data << (uint8)chatTag();
16337 void Player::Say(const std::string& text, const uint32 language)
16339 WorldPacket data(SMSG_MESSAGECHAT, 200);
16340 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16341 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16344 void Player::Yell(const std::string& text, const uint32 language)
16346 WorldPacket data(SMSG_MESSAGECHAT, 200);
16347 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16348 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16351 void Player::TextEmote(const std::string& text)
16353 WorldPacket data(SMSG_MESSAGECHAT, 200);
16354 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16355 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16358 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16360 if (language != LANG_ADDON) // if not addon data
16361 language = LANG_UNIVERSAL; // whispers should always be readable
16363 Player *rPlayer = objmgr.GetPlayer(receiver);
16365 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16366 if(!rPlayer->isDND() || isGameMaster())
16368 WorldPacket data(SMSG_MESSAGECHAT, 200);
16369 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16370 rPlayer->GetSession()->SendPacket(&data);
16372 data.Initialize(SMSG_MESSAGECHAT, 200);
16373 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16374 GetSession()->SendPacket(&data);
16376 else
16378 // announce to player that player he is whispering to is dnd and cannot receive his message
16379 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16382 if(!isAcceptWhispers())
16384 SetAcceptWhispers(true);
16385 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16388 // announce to player that player he is whispering to is afk
16389 if(rPlayer->isAFK())
16390 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16392 // if player whisper someone, auto turn of dnd to be able to receive an answer
16393 if(isDND() && !rPlayer->isGameMaster())
16394 ToggleDND();
16397 void Player::PetSpellInitialize()
16399 Pet* pet = GetPet();
16401 if(!pet)
16402 return;
16404 sLog.outDebug("Pet Spells Groups");
16406 CharmInfo *charmInfo = pet->GetCharmInfo();
16408 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16409 data << uint64(pet->GetGUID());
16410 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16411 data << uint32(0);
16412 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16414 // action bar loop
16415 charmInfo->BuildActionBar(&data);
16417 size_t spellsCountPos = data.wpos();
16419 // spells count
16420 uint8 addlist = 0;
16421 data << uint8(addlist); // placeholder
16423 if (pet->IsPermanentPetFor(this))
16425 // spells loop
16426 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16428 if(itr->second.state == PETSPELL_REMOVED)
16429 continue;
16431 data << uint16(itr->first);
16432 data << uint16(itr->second.active); // pet spell active state isn't boolean
16433 ++addlist;
16437 data.put<uint8>(spellsCountPos, addlist);
16439 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16440 data << uint8(cooldownsCount);
16442 time_t curTime = time(NULL);
16444 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16446 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16448 data << uint16(itr->first); // spellid
16449 data << uint16(0); // spell category?
16450 data << uint32(cooldown); // cooldown
16451 data << uint32(0); // category cooldown
16454 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16456 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16458 data << uint16(itr->first); // spellid
16459 data << uint16(0); // spell category?
16460 data << uint32(0); // cooldown
16461 data << uint32(cooldown); // category cooldown
16464 GetSession()->SendPacket(&data);
16467 void Player::PossessSpellInitialize()
16469 Unit* charm = GetCharm();
16471 if(!charm)
16472 return;
16474 CharmInfo *charmInfo = charm->GetCharmInfo();
16476 if(!charmInfo)
16478 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16479 return;
16482 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
16483 data << uint64(charm->GetGUID());
16484 data << uint32(0);
16485 data << uint32(0);
16486 data << uint32(0);
16488 charmInfo->BuildActionBar(&data);
16490 data << uint8(0); // spells count
16491 data << uint8(0); // cooldowns count
16493 GetSession()->SendPacket(&data);
16496 void Player::CharmSpellInitialize()
16498 Unit* charm = GetCharm();
16500 if(!charm)
16501 return;
16503 CharmInfo *charmInfo = charm->GetCharmInfo();
16504 if(!charmInfo)
16506 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16507 return;
16510 uint8 addlist = 0;
16512 if(charm->GetTypeId() != TYPEID_PLAYER)
16514 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16516 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16518 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16520 if(charmInfo->GetCharmSpell(i)->spellId)
16521 ++addlist;
16526 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
16527 data << uint64(charm->GetGUID());
16528 data << uint32(0);
16529 data << uint32(0);
16531 if(charm->GetTypeId() != TYPEID_PLAYER)
16532 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16533 else
16534 data << uint8(0) << uint8(0) << uint16(0);
16536 charmInfo->BuildActionBar(&data);
16538 data << uint8(addlist);
16540 if(addlist)
16542 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16544 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16545 if(cspell->spellId)
16547 data << uint16(cspell->spellId);
16548 data << uint16(cspell->active);
16553 data << uint8(0); // cooldowns count
16555 GetSession()->SendPacket(&data);
16558 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16560 if (!mod || !spellInfo)
16561 return false;
16563 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16565 // prevent apply to any spell except spell that trigger expire
16566 if(spell)
16568 if(mod->lastAffected != spell)
16569 return false;
16571 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16572 return false;
16575 return spellmgr.IsAffectedByMod(spellInfo, mod);
16578 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16580 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16582 for(int eff=0;eff<96;++eff)
16584 uint64 _mask = 0;
16585 uint64 _mask2= 0;
16586 if (eff<64) _mask = uint64(1) << (eff- 0);
16587 else _mask2= uint64(1) << (eff-64);
16588 if ( mod->mask & _mask || mod->mask2 & _mask2)
16590 int32 val = 0;
16591 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16593 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16594 val += (*itr)->value;
16596 val += apply ? mod->value : -(mod->value);
16597 WorldPacket data(Opcode, (1+1+4));
16598 data << uint8(eff);
16599 data << uint8(mod->op);
16600 data << int32(val);
16601 SendDirectMessage(&data);
16605 if (apply)
16606 m_spellMods[mod->op].push_back(mod);
16607 else
16609 if (mod->charges == -1)
16610 --m_SpellModRemoveCount;
16611 m_spellMods[mod->op].remove(mod);
16612 delete mod;
16616 void Player::RemoveSpellMods(Spell const* spell)
16618 if(!spell || (m_SpellModRemoveCount == 0))
16619 return;
16621 for(int i=0;i<MAX_SPELLMOD;++i)
16623 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16625 SpellModifier *mod = *itr;
16626 ++itr;
16628 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16630 RemoveAurasDueToSpell(mod->spellId);
16631 if (m_spellMods[i].empty())
16632 break;
16633 else
16634 itr = m_spellMods[i].begin();
16640 // send Proficiency
16641 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16643 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16644 data << pr1 << pr2;
16645 GetSession()->SendPacket (&data);
16648 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16650 QueryResult *result = NULL;
16651 if(type==10)
16652 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16653 else
16654 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16655 if(result)
16657 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.
16658 { // and SendPetitionQueryOpcode reads data from the DB
16659 Field *fields = result->Fetch();
16660 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16661 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16663 // send update if charter owner in game
16664 Player* owner = objmgr.GetPlayer(ownerguid);
16665 if(owner)
16666 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16668 } while ( result->NextRow() );
16670 delete result;
16672 if(type==10)
16673 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16674 else
16675 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16678 CharacterDatabase.BeginTransaction();
16679 if(type == 10)
16681 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16682 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16684 else
16686 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16687 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16689 CharacterDatabase.CommitTransaction();
16692 void Player::LeaveAllArenaTeams(uint64 guid)
16694 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));
16695 if(!result)
16696 return;
16700 Field *fields = result->Fetch();
16701 uint32 at_id = fields[0].GetUInt32();
16702 if(at_id != 0)
16704 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16705 if(at)
16706 at->DelMember(guid);
16708 } while (result->NextRow());
16710 delete result;
16713 void Player::SetRestBonus (float rest_bonus_new)
16715 // Prevent resting on max level
16716 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16717 rest_bonus_new = 0;
16719 if(rest_bonus_new < 0)
16720 rest_bonus_new = 0;
16722 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16724 if(rest_bonus_new > rest_bonus_max)
16725 m_rest_bonus = rest_bonus_max;
16726 else
16727 m_rest_bonus = rest_bonus_new;
16729 // update data for client
16730 if(m_rest_bonus>10)
16731 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16732 else if(m_rest_bonus<=1)
16733 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16735 //RestTickUpdate
16736 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16739 void Player::HandleStealthedUnitsDetection()
16741 std::list<Unit*> stealthedUnits;
16743 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16744 Cell cell(p);
16745 cell.data.Part.reserved = ALL_DISTRICT;
16746 cell.SetNoCreate();
16748 MaNGOS::AnyStealthedCheck u_check;
16749 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16751 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16752 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16754 CellLock<GridReadGuard> cell_lock(cell, p);
16755 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16756 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16758 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16760 if((*i)==this)
16762 i = stealthedUnits.erase(i);
16763 continue;
16766 if ((*i)->isVisibleForOrDetect(this,true))
16769 (*i)->SendUpdateToPlayer(this);
16770 m_clientGUIDs.insert((*i)->GetGUID());
16772 #ifdef MANGOS_DEBUG
16773 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16774 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16775 #endif
16777 // target aura duration for caster show only if target exist at caster client
16778 // send data at target visibility change (adding to client)
16779 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16780 SendAurasForTarget(*i);
16782 i = stealthedUnits.erase(i);
16783 continue;
16786 ++i;
16790 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16792 if(nodes.size() < 2)
16793 return false;
16795 // 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
16796 if(GetSession()->isLogingOut() || isInCombat())
16798 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16799 data << uint32(ERR_TAXIPLAYERBUSY);
16800 GetSession()->SendPacket(&data);
16801 return false;
16804 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16805 return false;
16807 // taximaster case
16808 if(npc)
16810 // not let cheating with start flight mounted
16811 if(IsMounted())
16813 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16814 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16815 GetSession()->SendPacket(&data);
16816 return false;
16819 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16821 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16822 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16823 GetSession()->SendPacket(&data);
16824 return false;
16827 // 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
16828 if(IsNonMeleeSpellCasted(false))
16830 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16831 data << uint32(ERR_TAXIPLAYERBUSY);
16832 GetSession()->SendPacket(&data);
16833 return false;
16836 // cast case or scripted call case
16837 else
16839 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16841 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16842 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16844 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16845 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16847 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16849 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16850 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16853 uint32 sourcenode = nodes[0];
16855 // starting node too far away (cheat?)
16856 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16857 if (!node)
16859 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16860 data << uint32(ERR_TAXINOSUCHPATH);
16861 GetSession()->SendPacket(&data);
16862 return false;
16865 // check node starting pos data set case if provided
16866 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16868 if (node->map_id != GetMapId() ||
16869 (node->x - GetPositionX())*(node->x - GetPositionX())+
16870 (node->y - GetPositionY())*(node->y - GetPositionY())+
16871 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16872 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16874 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16875 data << uint32(ERR_TAXITOOFARAWAY);
16876 GetSession()->SendPacket(&data);
16877 return false;
16880 // node must have pos if taxi master case (npc != NULL)
16881 else if (npc)
16883 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16884 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16885 GetSession()->SendPacket(&data);
16886 return false;
16889 // Prepare to flight start now
16891 // stop combat at start taxi flight if any
16892 CombatStop();
16894 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16895 TradeCancel(true);
16897 // clean not finished taxi path if any
16898 m_taxi.ClearTaxiDestinations();
16900 // 0 element current node
16901 m_taxi.AddTaxiDestination(sourcenode);
16903 // fill destinations path tail
16904 uint32 sourcepath = 0;
16905 uint32 totalcost = 0;
16907 uint32 prevnode = sourcenode;
16908 uint32 lastnode = 0;
16910 for(uint32 i = 1; i < nodes.size(); ++i)
16912 uint32 path, cost;
16914 lastnode = nodes[i];
16915 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16917 if(!path)
16919 m_taxi.ClearTaxiDestinations();
16920 return false;
16923 totalcost += cost;
16925 if(prevnode == sourcenode)
16926 sourcepath = path;
16928 m_taxi.AddTaxiDestination(lastnode);
16930 prevnode = lastnode;
16933 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16934 uint16 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam(), npc == NULL);
16936 // in spell case allow 0 model
16937 if (mount_id == 0 && spellid == 0 || sourcepath == 0)
16939 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16940 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16941 GetSession()->SendPacket(&data);
16942 m_taxi.ClearTaxiDestinations();
16943 return false;
16946 uint32 money = GetMoney();
16948 if (npc)
16949 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16951 if(money < totalcost)
16953 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16954 data << uint32(ERR_TAXINOTENOUGHMONEY);
16955 GetSession()->SendPacket(&data);
16956 m_taxi.ClearTaxiDestinations();
16957 return false;
16960 //Checks and preparations done, DO FLIGHT
16961 ModifyMoney(-(int32)totalcost);
16962 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16963 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16965 // prevent stealth flight
16966 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16968 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16969 data << uint32(ERR_TAXIOK);
16970 GetSession()->SendPacket(&data);
16972 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16974 GetSession()->SendDoFlight(mount_id, sourcepath);
16976 return true;
16979 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
16981 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
16982 if(!entry)
16983 return false;
16985 std::vector<uint32> nodes;
16987 nodes.resize(2);
16988 nodes[0] = entry->from;
16989 nodes[1] = entry->to;
16991 return ActivateTaxiPathTo(nodes,NULL,spellid);
16994 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16996 // last check 2.0.10
16997 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16998 data << GetGUID();
16999 data << uint8(0x0); // flags (0x1, 0x2)
17000 time_t curTime = time(NULL);
17001 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17003 if (itr->second->state == PLAYERSPELL_REMOVED)
17004 continue;
17005 uint32 unSpellId = itr->first;
17006 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17007 if (!spellInfo)
17009 ASSERT(spellInfo);
17010 continue;
17013 // Not send cooldown for this spells
17014 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17015 continue;
17017 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17019 data << uint32(unSpellId);
17020 data << uint32(unTimeMs); // in m.secs
17021 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17024 GetSession()->SendPacket(&data);
17027 void Player::InitDataForForm(bool reapplyMods)
17029 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17030 if(ssEntry && ssEntry->attackSpeed)
17032 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17033 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17034 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17036 else
17037 SetRegularAttackTime();
17039 switch(m_form)
17041 case FORM_CAT:
17043 if(getPowerType()!=POWER_ENERGY)
17044 setPowerType(POWER_ENERGY);
17045 break;
17047 case FORM_BEAR:
17048 case FORM_DIREBEAR:
17050 if(getPowerType()!=POWER_RAGE)
17051 setPowerType(POWER_RAGE);
17052 break;
17054 default: // 0, for example
17056 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17057 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17058 setPowerType(Powers(cEntry->powerType));
17059 break;
17063 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17064 if (!reapplyMods)
17065 UpdateEquipSpellsAtFormChange();
17067 UpdateAttackPowerAndDamage();
17068 UpdateAttackPowerAndDamage(true);
17071 // Return true is the bought item has a max count to force refresh of window by caller
17072 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17074 // cheating attempt
17075 if(count < 1) count = 1;
17077 if(!isAlive())
17078 return false;
17080 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17081 if( !pProto )
17083 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17084 return false;
17087 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17088 if (!pCreature)
17090 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17091 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17092 return false;
17095 VendorItemData const* vItems = pCreature->GetVendorItems();
17096 if(!vItems || vItems->Empty())
17098 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17099 return false;
17102 size_t vendor_slot = vItems->FindItemSlot(item);
17103 if(vendor_slot >= vItems->GetItemCount())
17105 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17106 return false;
17109 VendorItem const* crItem = vItems->m_items[vendor_slot];
17111 // check current item amount if it limited
17112 if( crItem->maxcount != 0 )
17114 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17116 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17117 return false;
17121 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17123 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17124 return false;
17127 if(crItem->ExtendedCost)
17129 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17130 if(!iece)
17132 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17133 return false;
17136 // honor points price
17137 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17139 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17140 return false;
17143 // arena points price
17144 if(GetArenaPoints() < (iece->reqarenapoints * count))
17146 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17147 return false;
17150 // item base price
17151 for (uint8 i = 0; i < 5; ++i)
17153 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17155 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17156 return false;
17160 // check for personal arena rating requirement
17161 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17163 // probably not the proper equip err
17164 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17165 return false;
17169 uint32 price = pProto->BuyPrice * count;
17171 // reputation discount
17172 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17174 if( GetMoney() < price )
17176 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17177 return false;
17180 uint8 bag = 0; // init for case invalid bagGUID
17182 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17184 Bag *pBag;
17185 if( bagguid == GetGUID() )
17187 bag = INVENTORY_SLOT_BAG_0;
17189 else
17191 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17193 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17194 if( pBag )
17196 if( bagguid == pBag->GetGUID() )
17198 bag = i;
17199 break;
17206 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17208 ItemPosCountVec dest;
17209 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17210 if( msg != EQUIP_ERR_OK )
17212 SendEquipError( msg, NULL, NULL );
17213 return false;
17216 ModifyMoney( -(int32)price );
17217 if(crItem->ExtendedCost) // case for new honor system
17219 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17220 if(iece->reqhonorpoints)
17221 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17222 if(iece->reqarenapoints)
17223 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17224 for (uint8 i = 0; i < 5; ++i)
17226 if(iece->reqitem[i])
17227 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17231 if(Item *it = StoreNewItem( dest, item, true ))
17233 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17235 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17236 data << pCreature->GetGUID();
17237 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17238 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17239 data << (uint32)count;
17240 GetSession()->SendPacket(&data);
17242 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17245 else if( IsEquipmentPos( bag, slot ) )
17247 if(pProto->BuyCount * count != 1)
17249 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17250 return false;
17253 uint16 dest;
17254 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17255 if( msg != EQUIP_ERR_OK )
17257 SendEquipError( msg, NULL, NULL );
17258 return false;
17261 ModifyMoney( -(int32)price );
17262 if(crItem->ExtendedCost) // case for new honor system
17264 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17265 if(iece->reqhonorpoints)
17266 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17267 if(iece->reqarenapoints)
17268 ModifyArenaPoints( - int32(iece->reqarenapoints));
17269 for (uint8 i = 0; i < 5; ++i)
17271 if(iece->reqitem[i])
17272 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17276 if(Item *it = EquipNewItem( dest, item, true ))
17278 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17280 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17281 data << pCreature->GetGUID();
17282 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17283 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17284 data << (uint32)count;
17285 GetSession()->SendPacket(&data);
17287 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17289 AutoUnequipOffhandIfNeed();
17292 else
17294 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17295 return false;
17298 return crItem->maxcount!=0;
17301 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17303 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17304 // the personal rating of the arena team must match the required limit as well
17305 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17306 uint32 max_personal_rating = 0;
17307 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17309 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17311 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17312 uint32 t_rating = at->GetRating();
17313 p_rating = p_rating<t_rating? p_rating : t_rating;
17314 if(max_personal_rating < p_rating)
17315 max_personal_rating = p_rating;
17318 return max_personal_rating;
17321 void Player::UpdateHomebindTime(uint32 time)
17323 // GMs never get homebind timer online
17324 if (m_InstanceValid || isGameMaster())
17326 if(m_HomebindTimer) // instance valid, but timer not reset
17328 // hide reminder
17329 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17330 data << uint32(0);
17331 data << uint32(0);
17332 GetSession()->SendPacket(&data);
17334 // instance is valid, reset homebind timer
17335 m_HomebindTimer = 0;
17337 else if (m_HomebindTimer > 0)
17339 if (time >= m_HomebindTimer)
17341 // teleport to homebind location
17342 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17344 else
17345 m_HomebindTimer -= time;
17347 else
17349 // instance is invalid, start homebind timer
17350 m_HomebindTimer = 60000;
17351 // send message to player
17352 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17353 data << m_HomebindTimer;
17354 data << uint32(1);
17355 GetSession()->SendPacket(&data);
17356 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17360 void Player::UpdatePvP(bool state, bool ovrride)
17362 if(!state || ovrride)
17364 SetPvP(state);
17365 pvpInfo.endTimer = 0;
17367 else
17369 if(pvpInfo.endTimer != 0)
17370 pvpInfo.endTimer = time(NULL);
17371 else
17372 SetPvP(state);
17376 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17378 // init cooldown values
17379 uint32 cat = 0;
17380 int32 rec = -1;
17381 int32 catrec = -1;
17383 // some special item spells without correct cooldown in SpellInfo
17384 // cooldown information stored in item prototype
17385 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17387 if(itemId)
17389 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17391 for(int idx = 0; idx < 5; ++idx)
17393 if(proto->Spells[idx].SpellId == spellInfo->Id)
17395 cat = proto->Spells[idx].SpellCategory;
17396 rec = proto->Spells[idx].SpellCooldown;
17397 catrec = proto->Spells[idx].SpellCategoryCooldown;
17398 break;
17404 // if no cooldown found above then base at DBC data
17405 if(rec < 0 && catrec < 0)
17407 cat = spellInfo->Category;
17408 rec = spellInfo->RecoveryTime;
17409 catrec = spellInfo->CategoryRecoveryTime;
17412 time_t curTime = time(NULL);
17414 time_t catrecTime;
17415 time_t recTime;
17417 // overwrite time for selected category
17418 if(infinityCooldown)
17420 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17421 // but not allow ignore until reset or re-login
17422 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17423 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17425 else
17427 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17428 // prevent 0 cooldowns set by another way
17429 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17430 rec = GetAttackTime(RANGED_ATTACK);
17432 // Now we have cooldown data (if found any), time to apply mods
17433 if(rec > 0)
17434 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17436 if(catrec > 0)
17437 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17439 // replace negative cooldowns by 0
17440 if (rec < 0) rec = 0;
17441 if (catrec < 0) catrec = 0;
17443 // no cooldown after applying spell mods
17444 if( rec == 0 && catrec == 0)
17445 return;
17447 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17448 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17451 // self spell cooldown
17452 if(recTime > 0)
17453 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17455 // category spells
17456 if (cat && catrec > 0)
17458 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17459 if(i_scstore != sSpellCategoryStore.end())
17461 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17463 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17464 continue;
17466 AddSpellCooldown(*i_scset, itemId, catrecTime);
17472 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17474 SpellCooldown sc;
17475 sc.end = end_time;
17476 sc.itemid = itemid;
17477 m_spellCooldowns[spellid] = sc;
17480 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17482 // start cooldowns at server side, if any
17483 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17485 // Send activate cooldown timer (possible 0) at client side
17486 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17487 data << spellInfo->Id;
17488 data << GetGUID();
17489 SendDirectMessage(&data);
17492 void Player::UpdatePotionCooldown(Spell* spell)
17494 // no potion used i combat or still in combat
17495 if(!m_lastPotionId || isInCombat())
17496 return;
17498 // Call not from spell cast, send cooldown event for item spells if no in combat
17499 if(!spell)
17501 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17502 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17503 for(int idx = 0; idx < 5; ++idx)
17504 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17505 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17506 SendCooldownEvent(spellInfo,m_lastPotionId);
17508 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17509 else
17510 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17512 m_lastPotionId = 0;
17515 //slot to be excluded while counting
17516 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17518 if(!enchantmentcondition)
17519 return true;
17521 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17523 if(!Condition)
17524 return true;
17526 uint8 curcount[4] = {0, 0, 0, 0};
17528 //counting current equipped gem colors
17529 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17531 if(i == slot)
17532 continue;
17533 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17534 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17536 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17538 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17539 if(!enchant_id)
17540 continue;
17542 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17543 if(!enchantEntry)
17544 continue;
17546 uint32 gemid = enchantEntry->GemID;
17547 if(!gemid)
17548 continue;
17550 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17551 if(!gemProto)
17552 continue;
17554 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17555 if(!gemProperty)
17556 continue;
17558 uint8 GemColor = gemProperty->color;
17560 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17562 if(tmpcolormask & GemColor)
17563 ++curcount[b];
17569 bool activate = true;
17571 for(int i = 0; i < 5; ++i)
17573 if(!Condition->Color[i])
17574 continue;
17576 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17578 // if have <CompareColor> use them as count, else use <value> from Condition
17579 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17581 switch(Condition->Comparator[i])
17583 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17584 activate &= (_cur_gem < _cmp_gem) ? true : false;
17585 break;
17586 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17587 activate &= (_cur_gem > _cmp_gem) ? true : false;
17588 break;
17589 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17590 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17591 break;
17595 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");
17597 return activate;
17600 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17602 //cycle all equipped items
17603 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17605 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17606 if(slot == exceptslot)
17607 continue;
17609 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17611 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17612 continue;
17614 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17616 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17617 if(!enchant_id)
17618 continue;
17620 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17621 if(!enchantEntry)
17622 continue;
17624 uint32 condition = enchantEntry->EnchantmentCondition;
17625 if(condition)
17627 //was enchant active with/without item?
17628 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17629 //should it now be?
17630 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17632 // ignore item gem conditions
17633 //if state changed, (dis)apply enchant
17634 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17641 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17642 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17644 //cycle all equipped items
17645 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17647 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17648 if(slot == exceptslot)
17649 continue;
17651 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17653 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17654 continue;
17656 //cycle all (gem)enchants
17657 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17659 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17660 if(!enchant_id) //if no enchant go to next enchant(slot)
17661 continue;
17663 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17664 if(!enchantEntry)
17665 continue;
17667 //only metagems to be (de)activated, so only enchants with condition
17668 uint32 condition = enchantEntry->EnchantmentCondition;
17669 if(condition)
17670 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17675 void Player::LeaveBattleground(bool teleportToEntryPoint)
17677 if(BattleGround *bg = GetBattleGround())
17679 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17681 // call after remove to be sure that player resurrected for correct cast
17682 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17684 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17685 CastSpell(this, 26013, true); // Deserter
17690 bool Player::CanJoinToBattleground() const
17692 // check Deserter debuff
17693 if(GetDummyAura(26013))
17694 return false;
17696 return true;
17699 bool Player::CanReportAfkDueToLimit()
17701 // a player can complain about 15 people per 5 minutes
17702 if(m_bgAfkReportedCount >= 15)
17703 return false;
17704 ++m_bgAfkReportedCount;
17705 return true;
17708 ///This player has been blamed to be inactive in a battleground
17709 void Player::ReportedAfkBy(Player* reporter)
17711 BattleGround *bg = GetBattleGround();
17712 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17713 return;
17715 // check if player has 'Idle' or 'Inactive' debuff
17716 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17718 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17719 // 3 players have to complain to apply debuff
17720 if(m_bgAfkReporter.size() >= 3)
17722 // cast 'Idle' spell
17723 CastSpell(this, 43680, true);
17724 m_bgAfkReporter.clear();
17729 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17731 // gamemaster in GM mode see all, including ghosts
17732 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17733 return true;
17735 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17736 if (InBattleGround())
17738 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17739 return false;
17740 return true;
17743 // Live player see live player or dead player with not realized corpse
17744 if(pl->isAlive() || pl->m_deathTimer > 0)
17746 return isAlive() || m_deathTimer > 0;
17749 // Ghost see other friendly ghosts, that's for sure
17750 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17751 return true;
17753 // Dead player see live players near own corpse
17754 if(isAlive())
17756 Corpse *corpse = pl->GetCorpse();
17757 if(corpse)
17759 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17760 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17761 return true;
17765 // and not see any other
17766 return false;
17769 bool Player::IsVisibleGloballyFor( Player* u ) const
17771 if(!u)
17772 return false;
17774 // Always can see self
17775 if (u==this)
17776 return true;
17778 // Visible units, always are visible for all players
17779 if (GetVisibility() == VISIBILITY_ON)
17780 return true;
17782 // GMs are visible for higher gms (or players are visible for gms)
17783 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17784 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17786 // non faction visibility non-breakable for non-GMs
17787 if (GetVisibility() == VISIBILITY_OFF)
17788 return false;
17790 // non-gm stealth/invisibility not hide from global player lists
17791 return true;
17794 void Player::UpdateVisibilityOf(WorldObject* target)
17796 if(HaveAtClient(target))
17798 if(!target->isVisibleForInState(this,true))
17800 target->DestroyForPlayer(this);
17801 m_clientGUIDs.erase(target->GetGUID());
17803 #ifdef MANGOS_DEBUG
17804 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17805 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17806 #endif
17809 else
17811 if(target->isVisibleForInState(this,false))
17813 target->SendUpdateToPlayer(this);
17814 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17815 m_clientGUIDs.insert(target->GetGUID());
17817 #ifdef MANGOS_DEBUG
17818 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17819 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17820 #endif
17822 // target aura duration for caster show only if target exist at caster client
17823 // send data at target visibility change (adding to client)
17824 if(target!=this && target->isType(TYPEMASK_UNIT))
17825 SendAurasForTarget((Unit*)target);
17827 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17828 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17833 template<class T>
17834 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17836 s64.insert(target->GetGUID());
17839 template<>
17840 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17842 if(!target->IsTransport())
17843 s64.insert(target->GetGUID());
17846 template<class T>
17847 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17849 if(HaveAtClient(target))
17851 if(!target->isVisibleForInState(this,true))
17853 target->BuildOutOfRangeUpdateBlock(&data);
17854 m_clientGUIDs.erase(target->GetGUID());
17856 #ifdef MANGOS_DEBUG
17857 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17858 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));
17859 #endif
17862 else
17864 if(target->isVisibleForInState(this,false))
17866 visibleNow.insert(target);
17867 target->BuildUpdate(data_updates);
17868 target->BuildCreateUpdateBlockForPlayer(&data, this);
17869 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17871 #ifdef MANGOS_DEBUG
17872 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17873 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));
17874 #endif
17879 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17880 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17881 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17882 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17883 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17885 void Player::InitPrimaryProfessions()
17887 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17890 void Player::SendComboPoints()
17892 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17893 if (combotarget)
17895 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17896 data.append(combotarget->GetPackGUID());
17897 data << uint8(m_comboPoints);
17898 GetSession()->SendPacket(&data);
17902 void Player::AddComboPoints(Unit* target, int8 count)
17904 if(!count)
17905 return;
17907 // without combo points lost (duration checked in aura)
17908 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17910 if(target->GetGUID() == m_comboTarget)
17912 m_comboPoints += count;
17914 else
17916 if(m_comboTarget)
17917 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17918 target2->RemoveComboPointHolder(GetGUIDLow());
17920 m_comboTarget = target->GetGUID();
17921 m_comboPoints = count;
17923 target->AddComboPointHolder(GetGUIDLow());
17926 if (m_comboPoints > 5) m_comboPoints = 5;
17927 if (m_comboPoints < 0) m_comboPoints = 0;
17929 SendComboPoints();
17932 void Player::ClearComboPoints()
17934 if(!m_comboTarget)
17935 return;
17937 // without combopoints lost (duration checked in aura)
17938 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17940 m_comboPoints = 0;
17942 SendComboPoints();
17944 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17945 target->RemoveComboPointHolder(GetGUIDLow());
17947 m_comboTarget = 0;
17950 void Player::SetGroup(Group *group, int8 subgroup)
17952 if(group == NULL)
17953 m_group.unlink();
17954 else
17956 // never use SetGroup without a subgroup unless you specify NULL for group
17957 assert(subgroup >= 0);
17958 m_group.link(group, this);
17959 m_group.setSubGroup((uint8)subgroup);
17963 void Player::SendInitialPacketsBeforeAddToMap()
17965 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17966 data << uint32(0); // unknown, may be rest state time or experience
17967 GetSession()->SendPacket(&data);
17969 // Homebind
17970 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17971 data << m_homebindX << m_homebindY << m_homebindZ;
17972 data << (uint32) m_homebindMapId;
17973 data << (uint32) m_homebindZoneId;
17974 GetSession()->SendPacket(&data);
17976 // SMSG_SET_PROFICIENCY
17977 // SMSG_UPDATE_AURA_DURATION
17979 // tutorial stuff
17980 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17981 for (int i = 0; i < 8; ++i)
17982 data << uint32( GetTutorialInt(i) );
17983 GetSession()->SendPacket(&data);
17985 SendInitialSpells();
17987 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17988 data << uint32(0); // count, for(count) uint32;
17989 GetSession()->SendPacket(&data);
17991 SendInitialActionButtons();
17992 m_reputationMgr.SendInitialReputations();
17993 m_achievementMgr.SendAllAchievementData();
17995 // update zone
17996 uint32 newzone, newarea;
17997 GetZoneAndAreaId(newzone,newarea);
17998 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18000 // SMSG_SET_AURA_SINGLE
18002 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
18003 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18004 data << (float)0.01666667f; // game speed
18005 GetSession()->SendPacket( &data );
18007 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18008 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
18009 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18011 m_mover = this;
18014 void Player::SendInitialPacketsAfterAddToMap()
18016 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18017 data << uint32(0x00000000); // on blizz it increments periodically
18018 GetSession()->SendPacket(&data);
18020 CastSpell(this, 836, true); // LOGINEFFECT
18022 // set some aura effects that send packet to player client after add player to map
18023 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18024 // same auras state lost at far teleport, send it one more time in this case also
18025 static const AuraType auratypes[] =
18027 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18028 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18029 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18031 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18033 Unit::AuraList const& auraList = GetAurasByType(*itr);
18034 if(!auraList.empty())
18035 auraList.front()->ApplyModifier(true,true);
18038 if(HasAuraType(SPELL_AURA_MOD_STUN))
18039 SetMovement(MOVE_ROOT);
18041 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18042 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18044 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18045 data2.append(GetPackGUID());
18046 data2 << (uint32)2;
18047 SendMessageToSet(&data2,true);
18050 SendAurasForTarget(this);
18051 SendEnchantmentDurations(); // must be after add to map
18052 SendItemDurations(); // must be after add to map
18055 void Player::SendUpdateToOutOfRangeGroupMembers()
18057 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18058 return;
18059 if(Group* group = GetGroup())
18060 group->UpdatePlayerOutOfRange(this);
18062 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18063 m_auraUpdateMask = 0;
18064 if(Pet *pet = GetPet())
18065 pet->ResetAuraUpdateMask();
18068 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18070 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18071 data << uint32(mapid);
18072 data << uint8(reason); // transfer abort reason
18073 switch(reason)
18075 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18076 case TRANSFER_ABORT_DIFFICULTY:
18077 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18078 data << uint8(arg);
18079 break;
18081 GetSession()->SendPacket(&data);
18084 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18086 // type of warning, based on the time remaining until reset
18087 uint32 type;
18088 if(time > 3600)
18089 type = RAID_INSTANCE_WELCOME;
18090 else if(time > 900 && time <= 3600)
18091 type = RAID_INSTANCE_WARNING_HOURS;
18092 else if(time > 300 && time <= 900)
18093 type = RAID_INSTANCE_WARNING_MIN;
18094 else
18095 type = RAID_INSTANCE_WARNING_MIN_SOON;
18096 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18097 data << uint32(type);
18098 data << uint32(mapid);
18099 data << uint32(time);
18100 GetSession()->SendPacket(&data);
18103 void Player::ApplyEquipCooldown( Item * pItem )
18105 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18107 _Spell const& spellData = pItem->GetProto()->Spells[i];
18109 // no spell
18110 if( !spellData.SpellId )
18111 continue;
18113 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18114 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18115 continue;
18117 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18119 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18120 data << pItem->GetGUID();
18121 data << uint32(spellData.SpellId);
18122 GetSession()->SendPacket(&data);
18126 void Player::resetSpells()
18128 // not need after this call
18129 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18131 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18132 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18135 // make full copy of map (spells removed and marked as deleted at another spell remove
18136 // and we can't use original map for safe iterative with visit each spell at loop end
18137 PlayerSpellMap smap = GetSpellMap();
18139 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18140 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18142 learnDefaultSpells();
18143 learnQuestRewardedSpells();
18146 void Player::learnDefaultSpells()
18148 // learn default race/class spells
18149 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18150 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18152 uint32 tspell = *itr;
18153 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18154 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18155 addSpell(tspell,true,true,true,false);
18156 else // but send in normal spell in game learn case
18157 learnSpell(tspell,true);
18161 void Player::learnQuestRewardedSpells(Quest const* quest)
18163 uint32 spell_id = quest->GetRewSpellCast();
18165 // skip quests without rewarded spell
18166 if( !spell_id )
18167 return;
18169 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18170 if(!spellInfo)
18171 return;
18173 // check learned spells state
18174 bool found = false;
18175 for(int i=0; i < 3; ++i)
18177 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18179 found = true;
18180 break;
18184 // skip quests with not teaching spell or already known spell
18185 if(!found)
18186 return;
18188 // prevent learn non first rank unknown profession and second specialization for same profession)
18189 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18190 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18192 // not have first rank learned (unlearned prof?)
18193 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18194 if( !HasSpell(first_spell) )
18195 return;
18197 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18198 if(!learnedInfo)
18199 return;
18201 // specialization
18202 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18204 // search other specialization for same prof
18205 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18207 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18208 continue;
18210 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18211 if(!itrInfo)
18212 return;
18214 // compare only specializations
18215 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18216 continue;
18218 // compare same chain spells
18219 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18220 continue;
18222 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18223 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18224 return;
18229 CastSpell( this, spell_id, true);
18232 void Player::learnQuestRewardedSpells()
18234 // learn spells received from quest completing
18235 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18237 // skip no rewarded quests
18238 if(!itr->second.m_rewarded)
18239 continue;
18241 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18242 if( !quest )
18243 continue;
18245 learnQuestRewardedSpells(quest);
18249 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18251 uint32 raceMask = getRaceMask();
18252 uint32 classMask = getClassMask();
18253 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18255 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18256 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18257 continue;
18258 // Check race if set
18259 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18260 continue;
18261 // Check class if set
18262 if (pAbility->classmask && !(pAbility->classmask & classMask))
18263 continue;
18265 if (sSpellStore.LookupEntry(pAbility->spellId))
18267 // need unlearn spell
18268 if (skill_value < pAbility->req_skill_value)
18269 removeSpell(pAbility->spellId);
18270 // need learn
18271 else if (!IsInWorld())
18272 addSpell(pAbility->spellId,true,true,true,false);
18273 else
18274 learnSpell(pAbility->spellId,true);
18279 void Player::SendAurasForTarget(Unit *target)
18281 if(target->GetVisibleAuras()->empty()) // speedup things
18282 return;
18284 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18285 data.append(target->GetPackGUID());
18287 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18288 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18290 for(uint32 j = 0; j < 3; ++j)
18292 if(Aura *aura = target->GetAura(itr->second, j))
18294 data << uint8(aura->GetAuraSlot());
18295 data << uint32(aura->GetId());
18297 if(aura->GetId())
18299 uint8 auraFlags = aura->GetAuraFlags();
18300 // flags
18301 data << uint8(auraFlags);
18302 // level
18303 data << uint8(aura->GetAuraLevel());
18304 // charges
18305 data << uint8(aura->GetAuraCharges());
18307 if(!(auraFlags & AFLAG_NOT_CASTER))
18309 data << uint8(0); // packed GUID of someone (caster?)
18312 if(auraFlags & AFLAG_DURATION) // include aura duration
18314 data << uint32(aura->GetAuraMaxDuration());
18315 data << uint32(aura->GetAuraDuration());
18318 break;
18323 GetSession()->SendPacket(&data);
18326 void Player::SetDailyQuestStatus( uint32 quest_id )
18328 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18330 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18332 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18333 m_lastDailyQuestTime = time(NULL); // last daily quest time
18334 m_DailyQuestChanged = true;
18335 break;
18340 void Player::ResetDailyQuestStatus()
18342 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18343 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18345 // DB data deleted in caller
18346 m_DailyQuestChanged = false;
18347 m_lastDailyQuestTime = 0;
18350 BattleGround* Player::GetBattleGround() const
18352 if(GetBattleGroundId()==0)
18353 return NULL;
18355 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18358 bool Player::InArena() const
18360 BattleGround *bg = GetBattleGround();
18361 if(!bg || !bg->isArena())
18362 return false;
18364 return true;
18367 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18369 // get a template bg instead of running one
18370 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18371 if(!bg)
18372 return false;
18374 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18375 return false;
18377 return true;
18380 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18382 //returned to hardcoded version of this function, because there is no way to code it dynamic
18383 uint32 level = getLevel();
18384 if( bgTypeId == BATTLEGROUND_AV )
18385 level--;
18387 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18388 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18390 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18391 return QUEUE_ID_MAX_LEVEL_80;
18393 return BGQueueIdBasedOnLevel(queue_id);
18396 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18398 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18399 if(!vendor_faction || !vendor_faction->faction)
18400 return 1.0f;
18402 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18403 if(rank <= REP_NEUTRAL)
18404 return 1.0f;
18406 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18409 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18411 uint32 racemask = getRaceMask();
18412 uint32 classmask = getClassMask();
18414 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18415 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18416 if(lower==upper)
18417 return true;
18419 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18421 // skip wrong race skills
18422 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18423 continue;
18425 // skip wrong class skills
18426 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18427 continue;
18429 return true;
18432 return false;
18435 bool Player::HasQuestForGO(int32 GOId) const
18437 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18439 uint32 questid = GetQuestSlotQuestId(i);
18440 if ( questid == 0 )
18441 continue;
18443 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18444 if(qs_itr == mQuestStatus.end())
18445 continue;
18447 QuestStatusData const& qs = qs_itr->second;
18449 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18451 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18452 if(!qinfo)
18453 continue;
18455 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18456 continue;
18458 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18460 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18461 continue;
18463 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18464 return true;
18468 return false;
18471 void Player::UpdateForQuestWorldObjects()
18473 if(m_clientGUIDs.empty())
18474 return;
18476 UpdateData udata;
18477 WorldPacket packet;
18478 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18480 if(IS_GAMEOBJECT_GUID(*itr))
18482 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18483 if(obj)
18484 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18486 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18488 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18489 if(!obj)
18490 continue;
18491 // check if this unit requires quest specific flags
18493 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
18494 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(obj->GetEntry()); itr != map.upper_bound(obj->GetEntry()); ++itr)
18496 if(itr->second.questId != 0)
18498 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18499 break;
18505 udata.BuildPacket(&packet);
18506 GetSession()->SendPacket(&packet);
18509 void Player::SummonIfPossible(bool agree)
18511 if(!agree)
18513 m_summon_expire = 0;
18514 return;
18517 // expire and auto declined
18518 if(m_summon_expire < time(NULL))
18519 return;
18521 // stop taxi flight at summon
18522 if(isInFlight())
18524 GetMotionMaster()->MovementExpired();
18525 m_taxi.ClearTaxiDestinations();
18528 // drop flag at summon
18529 // 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
18530 if(BattleGround *bg = GetBattleGround())
18531 bg->EventPlayerDroppedFlag(this);
18533 m_summon_expire = 0;
18535 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18537 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18540 void Player::RemoveItemDurations( Item *item )
18542 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18544 if(*itr==item)
18546 m_itemDuration.erase(itr);
18547 break;
18552 void Player::AddItemDurations( Item *item )
18554 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18556 m_itemDuration.push_back(item);
18557 item->SendTimeUpdate(this);
18561 void Player::AutoUnequipOffhandIfNeed()
18563 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18564 if(!offItem)
18565 return;
18567 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18568 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18569 return;
18571 ItemPosCountVec off_dest;
18572 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18573 if( off_msg == EQUIP_ERR_OK )
18575 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18576 StoreItem( off_dest, offItem, true );
18578 else
18580 MailItemsInfo mi;
18581 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18582 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18583 CharacterDatabase.BeginTransaction();
18584 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18585 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18586 CharacterDatabase.CommitTransaction();
18588 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18589 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18593 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18595 if(spellInfo->EquippedItemClass < 0)
18596 return true;
18598 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18599 // for optimize check 2 used cases only
18600 switch(spellInfo->EquippedItemClass)
18602 case ITEM_CLASS_WEAPON:
18604 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18605 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18606 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18607 return true;
18608 break;
18610 case ITEM_CLASS_ARMOR:
18612 // tabard not have dependent spells
18613 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18614 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18615 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18616 return true;
18618 // shields can be equipped to offhand slot
18619 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18620 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18621 return true;
18623 // ranged slot can have some armor subclasses
18624 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18625 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18626 return true;
18628 break;
18630 default:
18631 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18632 break;
18635 return false;
18638 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18640 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18641 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18642 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18643 return true;
18645 // Check no reagent use mask
18646 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18647 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18648 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18649 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18650 return true;
18652 return false;
18655 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18657 AuraMap& auras = GetAuras();
18658 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18660 Aura* aura = itr->second;
18662 // skip passive (passive item dependent spells work in another way) and not self applied auras
18663 SpellEntry const* spellInfo = aura->GetSpellProto();
18664 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18666 ++itr;
18667 continue;
18670 // skip if not item dependent or have alternative item
18671 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18673 ++itr;
18674 continue;
18677 // no alt item, remove aura, restart check
18678 RemoveAurasDueToSpell(aura->GetId());
18679 itr = auras.begin();
18682 // currently casted spells can be dependent from item
18683 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18685 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18686 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18687 InterruptSpell(i);
18691 uint32 Player::GetResurrectionSpellId()
18693 // search priceless resurrection possibilities
18694 uint32 prio = 0;
18695 uint32 spell_id = 0;
18696 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18697 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18699 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18700 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18702 switch((*itr)->GetId())
18704 case 20707: spell_id = 3026; break; // rank 1
18705 case 20762: spell_id = 20758; break; // rank 2
18706 case 20763: spell_id = 20759; break; // rank 3
18707 case 20764: spell_id = 20760; break; // rank 4
18708 case 20765: spell_id = 20761; break; // rank 5
18709 case 27239: spell_id = 27240; break; // rank 6
18710 case 47883: spell_id = 47882; break; // rank 7
18711 default:
18712 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18713 continue;
18716 prio = 3;
18718 // Twisting Nether // prio: 2 (max)
18719 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18721 prio = 2;
18722 spell_id = 23700;
18726 // Reincarnation (passive spell) // prio: 1
18727 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18728 spell_id = 21169;
18730 return spell_id;
18733 // Used in triggers for check "Only to targets that grant experience or honor" req
18734 bool Player::isHonorOrXPTarget(Unit* pVictim)
18736 uint32 v_level = pVictim->getLevel();
18737 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18739 // Victim level less gray level
18740 if(v_level<=k_grey)
18741 return false;
18743 if(pVictim->GetTypeId() == TYPEID_UNIT)
18745 if (((Creature*)pVictim)->isTotem() ||
18746 ((Creature*)pVictim)->isPet() ||
18747 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18748 return false;
18750 return true;
18753 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18755 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18757 // prepare data for near group iteration (PvP and !PvP cases)
18758 uint32 xp = 0;
18759 bool honored_kill = false;
18761 if(Group *pGroup = GetGroup())
18763 uint32 count = 0;
18764 uint32 sum_level = 0;
18765 Player* member_with_max_level = NULL;
18766 Player* not_gray_member_with_max_level = NULL;
18768 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18770 if(member_with_max_level)
18772 /// not get Xp in PvP or no not gray players in group
18773 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18775 /// skip in check PvP case (for speed, not used)
18776 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18777 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18778 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18780 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18782 Player* pGroupGuy = itr->getSource();
18783 if(!pGroupGuy)
18784 continue;
18786 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18787 continue; // member (alive or dead) or his corpse at req. distance
18789 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18790 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18791 honored_kill = true;
18793 // xp and reputation only in !PvP case
18794 if(!PvP)
18796 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18798 // if is in dungeon then all receive full reputation at kill
18799 // rewarded any alive/dead/near_corpse group member
18800 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18802 // XP updated only for alive group member
18803 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18804 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18806 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18808 pGroupGuy->GiveXP(itr_xp, pVictim);
18809 if(Pet* pet = pGroupGuy->GetPet())
18810 pet->GivePetXP(itr_xp/2);
18813 // quest objectives updated only for alive group member or dead but with not released body
18814 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18816 // normal creature (not pet/etc) can be only in !PvP case
18817 if(pVictim->GetTypeId()==TYPEID_UNIT)
18818 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18824 else // if (!pGroup)
18826 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18828 // honor can be in PvP and !PvP (racial leader) cases
18829 if(RewardHonor(pVictim,1))
18830 honored_kill = true;
18832 // xp and reputation only in !PvP case
18833 if(!PvP)
18835 RewardReputation(pVictim,1);
18836 GiveXP(xp, pVictim);
18838 if(Pet* pet = GetPet())
18839 pet->GivePetXP(xp);
18841 // normal creature (not pet/etc) can be only in !PvP case
18842 if(pVictim->GetTypeId()==TYPEID_UNIT)
18843 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18846 return xp || honored_kill;
18849 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18851 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18853 // prepare data for near group iteration
18854 if(Group *pGroup = GetGroup())
18856 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18858 Player* pGroupGuy = itr->getSource();
18859 if(!pGroupGuy)
18860 continue;
18862 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18863 continue; // member (alive or dead) or his corpse at req. distance
18865 // quest objectives updated only for alive group member or dead but with not released body
18866 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18867 pGroupGuy->KilledMonster(creature_id, creature_guid);
18870 else // if (!pGroup)
18871 KilledMonster(creature_id, creature_guid);
18874 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18876 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18877 return true;
18879 if (isAlive())
18880 return false;
18882 Corpse* corpse = GetCorpse();
18883 if (!corpse)
18884 return false;
18886 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18889 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18891 Item* item = GetWeaponForAttack(attType,true);
18893 // unarmed only with base attack
18894 if(attType != BASE_ATTACK && !item)
18895 return 0;
18897 // weapon skill or (unarmed for base attack)
18898 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18899 return GetBaseSkillValue(skill);
18902 void Player::ResurectUsingRequestData()
18904 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
18905 if(IS_PLAYER_GUID(m_resurrectGUID))
18906 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18908 ResurrectPlayer(0.0f,false);
18910 if(GetMaxHealth() > m_resurrectHealth)
18911 SetHealth( m_resurrectHealth );
18912 else
18913 SetHealth( GetMaxHealth() );
18915 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18916 SetPower(POWER_MANA, m_resurrectMana );
18917 else
18918 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18920 SetPower(POWER_RAGE, 0 );
18922 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18924 SpawnCorpseBones();
18927 void Player::SetClientControl(Unit* target, uint8 allowMove)
18929 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18930 data.append(target->GetPackGUID());
18931 data << uint8(allowMove);
18932 GetSession()->SendPacket(&data);
18935 void Player::UpdateZoneDependentAuras( uint32 newZone )
18937 // remove new continent flight forms
18938 if( !IsAllowUseFlyMountsHere() )
18940 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18941 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18944 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18945 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18946 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18947 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18948 if( !HasAura(itr->second->spellId,0) )
18949 CastSpell(this,itr->second->spellId,true);
18952 void Player::UpdateAreaDependentAuras( uint32 newArea )
18954 // remove auras from spells with area limitations
18955 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18957 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18958 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18959 RemoveAura(iter);
18960 else
18961 ++iter;
18964 // some auras applied at subzone enter
18965 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18966 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18967 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18968 if( !HasAura(itr->second->spellId,0) )
18969 CastSpell(this,itr->second->spellId,true);
18972 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18974 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18975 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18977 return copseReclaimDelay[0];
18980 time_t now = time(NULL);
18981 // 0..2 full period
18982 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18983 return copseReclaimDelay[count];
18986 void Player::UpdateCorpseReclaimDelay()
18988 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18990 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18991 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18992 return;
18994 time_t now = time(NULL);
18995 if(now < m_deathExpireTime)
18997 // full and partly periods 1..3
18998 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18999 if(count < MAX_DEATH_COUNT)
19000 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19001 else
19002 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19004 else
19005 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19008 void Player::SendCorpseReclaimDelay(bool load)
19010 Corpse* corpse = GetCorpse();
19011 if(!corpse)
19012 return;
19014 uint32 delay;
19015 if(load)
19017 if(corpse->GetGhostTime() > m_deathExpireTime)
19018 return;
19020 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19022 uint32 count;
19023 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19024 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19026 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19027 if(count>=MAX_DEATH_COUNT)
19028 count = MAX_DEATH_COUNT-1;
19030 else
19031 count=0;
19033 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19035 time_t now = time(NULL);
19036 if(now >= expected_time)
19037 return;
19039 delay = expected_time-now;
19041 else
19042 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19044 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19045 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19046 data << uint32(delay*IN_MILISECONDS);
19047 GetSession()->SendPacket( &data );
19050 Player* Player::GetNextRandomRaidMember(float radius)
19052 Group *pGroup = GetGroup();
19053 if(!pGroup)
19054 return NULL;
19056 std::vector<Player*> nearMembers;
19057 nearMembers.reserve(pGroup->GetMembersCount());
19059 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19061 Player* Target = itr->getSource();
19063 // IsHostileTo check duel and controlled by enemy
19064 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19065 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19066 nearMembers.push_back(Target);
19069 if (nearMembers.empty())
19070 return NULL;
19072 uint32 randTarget = urand(0,nearMembers.size()-1);
19073 return nearMembers[randTarget];
19076 PartyResult Player::CanUninviteFromGroup() const
19078 const Group* grp = GetGroup();
19079 if(!grp)
19080 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19082 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19083 return PARTY_RESULT_YOU_NOT_LEADER;
19085 if(InBattleGround())
19086 return PARTY_RESULT_INVITE_RESTRICTED;
19088 return PARTY_RESULT_OK;
19091 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19093 //we must move references from m_group to m_originalGroup
19094 SetOriginalGroup(GetGroup(), GetSubGroup());
19096 m_group.unlink();
19097 m_group.link(group, this);
19098 m_group.setSubGroup((uint8)subgroup);
19101 void Player::RemoveFromBattleGroundRaid()
19103 //remove existing reference
19104 m_group.unlink();
19105 if( Group* group = GetOriginalGroup() )
19107 m_group.link(group, this);
19108 m_group.setSubGroup(GetOriginalSubGroup());
19110 SetOriginalGroup(NULL);
19113 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19115 if( group == NULL )
19116 m_originalGroup.unlink();
19117 else
19119 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19120 assert(subgroup >= 0);
19121 m_originalGroup.link(group, this);
19122 m_originalGroup.setSubGroup((uint8)subgroup);
19126 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19128 LiquidData liquid_status;
19129 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19130 if (!res)
19132 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19133 // Small hack for enable breath in WMO
19134 if (IsInWater())
19135 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19136 return;
19139 // All liquids type - check under water position
19140 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19142 if ( res & LIQUID_MAP_UNDER_WATER)
19143 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19144 else
19145 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19148 // Allow travel in dark water on taxi or transport
19149 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19150 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19151 else
19152 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19154 // in lava check, anywhere in lava level
19155 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19157 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19158 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19159 else
19160 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19162 // in slime check, anywhere in slime level
19163 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19165 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19166 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19167 else
19168 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19172 void Player::SetCanParry( bool value )
19174 if(m_canParry==value)
19175 return;
19177 m_canParry = value;
19178 UpdateParryPercentage();
19181 void Player::SetCanBlock( bool value )
19183 if(m_canBlock==value)
19184 return;
19186 m_canBlock = value;
19187 UpdateBlockPercentage();
19190 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19192 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19193 if(itr->pos == pos)
19194 return true;
19196 return false;
19199 bool Player::CanUseBattleGroundObject()
19201 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19202 // maybe gameobject code should handle that ForceReaction usage
19203 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19204 return ( //InBattleGround() && // in battleground - not need, check in other cases
19205 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19206 //player cannot use object when he is invulnerable (immune)
19207 !isTotalImmune() && // not totally immune
19208 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19209 !HasStealthAura() && // not stealthed
19210 !HasInvisibilityAura() && // not invisible
19211 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19212 isAlive() // live player
19216 bool Player::CanCaptureTowerPoint()
19218 return ( !HasStealthAura() && // not stealthed
19219 !HasInvisibilityAura() && // not invisible
19220 isAlive() // live player
19224 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19226 uint32 level = getLevel();
19228 if(level > GT_MAX_LEVEL)
19229 level = GT_MAX_LEVEL; // max level in this dbc
19231 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19232 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19233 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19235 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19236 return 0;
19238 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19240 if(!bsc) // shouldn't happen
19241 return 0xFFFFFFFF;
19243 float cost = 0;
19245 if(hairstyle != newhairstyle)
19246 cost += bsc->cost; // full price
19248 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19249 cost += bsc->cost * 0.5f; // +1/2 of price
19251 if(facialhair != newfacialhair)
19252 cost += bsc->cost * 0.75f; // +3/4 of price
19254 return uint32(cost);
19257 void Player::InitGlyphsForLevel()
19259 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19260 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19261 if(gs->Order)
19262 SetGlyphSlot(gs->Order - 1, gs->Id);
19264 uint32 level = getLevel();
19265 uint32 value = 0;
19267 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19268 if(level >= 15)
19269 value |= (0x01 | 0x02);
19270 if(level >= 30)
19271 value |= 0x08;
19272 if(level >= 50)
19273 value |= 0x04;
19274 if(level >= 70)
19275 value |= 0x10;
19276 if(level >= 80)
19277 value |= 0x20;
19279 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19282 void Player::EnterVehicle(Vehicle *vehicle)
19284 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19285 if(!ve)
19286 return;
19288 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19289 if(!veSeat)
19290 return;
19292 vehicle->SetCharmerGUID(GetGUID());
19293 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19294 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19295 vehicle->setFaction(getFaction());
19297 SetCharm(vehicle); // charm
19298 SetFarSightGUID(vehicle->GetGUID()); // set view
19300 SetClientControl(vehicle, 1); // redirect controls to vehicle
19302 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19303 GetSession()->SendPacket(&data);
19305 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19306 data.append(GetPackGUID());
19307 data << uint32(0); // counter?
19308 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19309 data << uint16(0); // special flags
19310 data << uint32(getMSTime()); // time
19311 data << vehicle->GetPositionX(); // x
19312 data << vehicle->GetPositionY(); // y
19313 data << vehicle->GetPositionZ(); // z
19314 data << vehicle->GetOrientation(); // o
19315 // transport part, TODO: load/calculate seat offsets
19316 data << uint64(vehicle->GetGUID()); // transport guid
19317 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19318 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19319 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19320 data << float(0); // transport orientation
19321 data << uint32(getMSTime()); // transport time
19322 data << uint8(0); // seat
19323 // end of transport part
19324 data << uint32(0); // fall time
19325 GetSession()->SendPacket(&data);
19327 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
19328 data << uint64(vehicle->GetGUID());
19329 data << uint32(0);
19330 data << uint32(0);
19331 data << uint32(0x00000101);
19333 for(uint32 i = 0; i < 10; ++i)
19334 data << uint16(0) << uint8(0) << uint8(i+8);
19336 data << uint8(0);
19337 data << uint8(0);
19338 GetSession()->SendPacket(&data);
19341 void Player::ExitVehicle(Vehicle *vehicle)
19343 vehicle->SetCharmerGUID(0);
19344 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19345 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19346 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19348 SetCharm(NULL);
19349 SetFarSightGUID(0);
19351 SetClientControl(vehicle, 0);
19353 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19354 data.append(GetPackGUID());
19355 data << uint32(0); // counter?
19356 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19357 data << uint16(0x40); // special flags
19358 data << uint32(getMSTime()); // time
19359 data << vehicle->GetPositionX(); // x
19360 data << vehicle->GetPositionY(); // y
19361 data << vehicle->GetPositionZ(); // z
19362 data << vehicle->GetOrientation(); // o
19363 data << uint32(0); // fall time
19364 GetSession()->SendPacket(&data);
19366 data.Initialize(SMSG_PET_SPELLS, 8+4);
19367 data << uint64(0);
19368 data << uint32(0);
19369 GetSession()->SendPacket(&data);
19371 // maybe called at dummy aura remove?
19372 // CastSpell(this, 45472, true); // Parachute
19375 bool Player::isTotalImmune()
19377 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19379 uint32 immuneMask = 0;
19380 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19382 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19383 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19384 return true;
19386 return false;
19389 bool Player::HasTitle(uint32 bitIndex)
19391 if (bitIndex > 128)
19392 return false;
19394 uint32 fieldIndexOffset = bitIndex / 32;
19395 uint32 flag = 1 << (bitIndex % 32);
19396 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19399 void Player::SetTitle(CharTitlesEntry const* title)
19401 uint32 fieldIndexOffset = title->bit_index / 32;
19402 uint32 flag = 1 << (title->bit_index % 32);
19403 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19406 void Player::ConvertRune(uint8 index, uint8 newType)
19408 SetCurrentRune(index, newType);
19410 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19411 data << uint8(index);
19412 data << uint8(newType);
19413 GetSession()->SendPacket(&data);
19416 void Player::ResyncRunes(uint8 count)
19418 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19419 for(uint32 i = 0; i < count; ++i)
19421 data << uint8(GetCurrentRune(i)); // rune type
19422 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19424 GetSession()->SendPacket(&data);
19427 void Player::AddRunePower(uint8 index)
19429 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19430 data << uint32(1 << index); // mask (0x00-0x3F probably)
19431 GetSession()->SendPacket(&data);
19434 void Player::InitRunes()
19436 if(getClass() != CLASS_DEATH_KNIGHT)
19437 return;
19439 m_runes = new Runes;
19441 m_runes->runeState = 0;
19443 for(uint32 i = 0; i < MAX_RUNES; ++i)
19445 SetBaseRune(i, i / 2); // init base types
19446 SetCurrentRune(i, i / 2); // init current types
19447 SetRuneCooldown(i, 0); // reset cooldowns
19448 m_runes->SetRuneState(i);
19451 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19452 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19455 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19457 Loot loot;
19458 loot.FillLoot (loot_id,store,this,true);
19460 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19461 for(uint32 i = 0; i < max_slot; ++i)
19463 LootItem* lootItem = loot.LootItemInSlot(i,this);
19465 ItemPosCountVec dest;
19466 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19467 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19468 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19469 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19470 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19471 if(msg != EQUIP_ERR_OK)
19473 SendEquipError( msg, NULL, NULL );
19474 continue;
19477 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19478 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19482 uint32 Player::CalculateTalentsPoints() const
19484 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19486 if(getClass() != CLASS_DEATH_KNIGHT)
19487 return base_talent;
19489 uint32 talentPointsForLevel =
19490 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19491 + m_questRewardTalentCount;
19493 if(talentPointsForLevel > base_talent)
19494 talentPointsForLevel = base_talent;
19496 return talentPointsForLevel;
19499 bool Player::IsAllowUseFlyMountsHere() const
19501 if (isGameMaster())
19502 return true;
19504 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19505 return v_map == 530 || v_map == 571 && HasSpell(54197);
19508 void Player::learnSpellHighRank(uint32 spellid)
19510 learnSpell(spellid,false);
19512 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19513 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19514 learnSpellHighRank(itr->second);
19517 void Player::_LoadSkills()
19519 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19521 // reset skill modifiers and set correct unlearn flags
19522 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19524 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19526 // set correct unlearn bit
19527 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19528 if(!id) continue;
19530 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19531 if(!pSkill) continue;
19533 // enable unlearn button for primary professions only
19534 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19535 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19536 else
19537 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19539 // set fixed skill ranges
19540 switch(GetSkillRangeType(pSkill,false))
19542 case SKILL_RANGE_LANGUAGE: // 300..300
19543 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19544 break;
19545 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19546 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19547 break;
19548 default:
19549 break;
19552 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19553 learnSkillRewardedSpells(id, vskill);
19556 // special settings
19557 if(getClass()==CLASS_DEATH_KNIGHT)
19559 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19560 if(base_level < 1)
19561 base_level = 1;
19562 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19563 if(base_skill < 1)
19564 base_skill = 1; // skill mast be known and then > 0 in any case
19566 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19567 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19568 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19569 SetSkill(SKILL_AXES, base_skill,base_skill);
19570 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19571 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19572 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19573 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19574 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19575 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19576 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19577 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19578 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19579 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19580 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19581 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19585 uint32 Player::GetPhaseMaskForSpawn() const
19587 uint32 phase = PHASEMASK_NORMAL;
19588 if(!isGameMaster())
19589 phase = GetPhaseMask();
19590 else
19592 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19593 if(!phases.empty())
19594 phase = phases.front()->GetMiscValue();
19597 // some aura phases include 1 normal map in addition to phase itself
19598 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19599 return n_phase;
19601 return PHASEMASK_NORMAL;
19604 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19606 ItemPrototype const* pProto = pItem->GetProto();
19608 // proto based limitations
19609 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19610 return res;
19612 // check unique-equipped on gems
19613 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19615 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19616 if(!enchant_id)
19617 continue;
19618 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19619 if(!enchantEntry)
19620 continue;
19622 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19623 if(!pGem)
19624 continue;
19626 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19627 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19628 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19630 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19631 return res;
19634 return EQUIP_ERR_OK;
19637 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19639 // check unique-equipped on item
19640 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19642 // there is an equip limit on this item
19643 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19644 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19647 // check unique-equipped limit
19648 if (itemProto->ItemLimitCategory)
19650 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19651 if(!limitEntry)
19652 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19654 if(limit_count > limitEntry->maxCount)
19655 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19657 // there is an equip limit on this item
19658 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19659 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19662 return EQUIP_ERR_OK;
19665 void Player::HandleFall(MovementInfo const& movementInfo)
19667 // calculate total z distance of the fall
19668 float z_diff = m_lastFallZ - movementInfo.z;
19669 sLog.outDebug("zDiff = %f", z_diff);
19671 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19672 // 14.57 can be calculated by resolving damageperc formula below to 0
19673 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19674 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19675 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19677 //Safe fall, fall height reduction
19678 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19680 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19682 if(damageperc >0 )
19684 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19686 float height = movementInfo.z;
19687 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19689 if (damage > 0)
19691 //Prevent fall damage from being more than the player maximum health
19692 if (damage > GetMaxHealth())
19693 damage = GetMaxHealth();
19695 // Gust of Wind
19696 if (GetDummyAura(43621))
19697 damage = GetMaxHealth()/2;
19699 EnvironmentalDamage(DAMAGE_FALL, damage);
19701 // recheck alive, might have died of EnvironmentalDamage
19702 if (isAlive())
19703 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19706 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19707 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);
19712 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19714 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19717 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19719 uint32 CurTalentPoints = GetFreeTalentPoints();
19721 if(CurTalentPoints == 0)
19722 return;
19724 if (talentRank >= MAX_TALENT_RANK)
19725 return;
19727 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19729 if(!talentInfo)
19730 return;
19732 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19734 if(!talentTabInfo)
19735 return;
19737 // prevent learn talent for different class (cheating)
19738 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19739 return;
19741 // find current max talent rank
19742 int32 curtalent_maxrank = 0;
19743 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19745 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19747 curtalent_maxrank = k + 1;
19748 break;
19752 // we already have same or higher talent rank learned
19753 if(curtalent_maxrank >= (talentRank + 1))
19754 return;
19756 // check if we have enough talent points
19757 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19758 return;
19760 // Check if it requires another talent
19761 if (talentInfo->DependsOn > 0)
19763 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19765 bool hasEnoughRank = false;
19766 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19768 if (depTalentInfo->RankID[i] != 0)
19769 if (HasSpell(depTalentInfo->RankID[i]))
19770 hasEnoughRank = true;
19772 if (!hasEnoughRank)
19773 return;
19777 // Find out how many points we have in this field
19778 uint32 spentPoints = 0;
19780 uint32 tTab = talentInfo->TalentTab;
19781 if (talentInfo->Row > 0)
19783 unsigned int numRows = sTalentStore.GetNumRows();
19784 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19786 // Someday, someone needs to revamp
19787 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19788 if (tmpTalent) // the way talents are tracked
19790 if (tmpTalent->TalentTab == tTab)
19792 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19794 if (tmpTalent->RankID[j] != 0)
19796 if (HasSpell(tmpTalent->RankID[j]))
19798 spentPoints += j + 1;
19807 // not have required min points spent in talent tree
19808 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19809 return;
19811 // spell not set in talent.dbc
19812 uint32 spellid = talentInfo->RankID[talentRank];
19813 if( spellid == 0 )
19815 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19816 return;
19819 // already known
19820 if(HasSpell(spellid))
19821 return;
19823 // learn! (other talent ranks will unlearned at learning)
19824 learnSpell(spellid, false);
19825 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19827 // update free talent points
19828 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19831 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19833 Pet *pet = GetPet();
19835 if(!pet)
19836 return;
19838 if(petGuid != pet->GetGUID())
19839 return;
19841 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19843 if(CurTalentPoints == 0)
19844 return;
19846 if (talentRank >= MAX_PET_TALENT_RANK)
19847 return;
19849 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19851 if(!talentInfo)
19852 return;
19854 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19856 if(!talentTabInfo)
19857 return;
19859 CreatureInfo const *ci = pet->GetCreatureInfo();
19861 if(!ci)
19862 return;
19864 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19866 if(!pet_family)
19867 return;
19869 if(pet_family->petTalentType < 0) // not hunter pet
19870 return;
19872 // prevent learn talent for different family (cheating)
19873 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19874 return;
19876 // find current max talent rank
19877 int32 curtalent_maxrank = 0;
19878 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19880 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19882 curtalent_maxrank = k + 1;
19883 break;
19887 // we already have same or higher talent rank learned
19888 if(curtalent_maxrank >= (talentRank + 1))
19889 return;
19891 // check if we have enough talent points
19892 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19893 return;
19895 // Check if it requires another talent
19896 if (talentInfo->DependsOn > 0)
19898 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19900 bool hasEnoughRank = false;
19901 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19903 if (depTalentInfo->RankID[i] != 0)
19904 if (pet->HasSpell(depTalentInfo->RankID[i]))
19905 hasEnoughRank = true;
19907 if (!hasEnoughRank)
19908 return;
19912 // Find out how many points we have in this field
19913 uint32 spentPoints = 0;
19915 uint32 tTab = talentInfo->TalentTab;
19916 if (talentInfo->Row > 0)
19918 unsigned int numRows = sTalentStore.GetNumRows();
19919 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19921 // Someday, someone needs to revamp
19922 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19923 if (tmpTalent) // the way talents are tracked
19925 if (tmpTalent->TalentTab == tTab)
19927 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19929 if (tmpTalent->RankID[j] != 0)
19931 if (pet->HasSpell(tmpTalent->RankID[j]))
19933 spentPoints += j + 1;
19942 // not have required min points spent in talent tree
19943 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19944 return;
19946 // spell not set in talent.dbc
19947 uint32 spellid = talentInfo->RankID[talentRank];
19948 if( spellid == 0 )
19950 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19951 return;
19954 // already known
19955 if(pet->HasSpell(spellid))
19956 return;
19958 // learn! (other talent ranks will unlearned at learning)
19959 pet->learnSpell(spellid);
19960 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19962 // update free talent points
19963 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19966 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19968 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19970 if(apply)
19971 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19972 else
19973 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19977 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19979 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19980 SetFallInformation(minfo.fallTime, minfo.z);
19983 void Player::UnsummonPetTemporaryIfAny()
19985 Pet* pet = GetPet();
19986 if(!pet)
19987 return;
19989 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19991 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19992 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19995 RemovePet(pet, PET_SAVE_AS_CURRENT);
19998 void Player::ResummonPetTemporaryUnSummonedIfAny()
20000 if(!m_temporaryUnsummonedPetNumber)
20001 return;
20003 // not resummon in not appropriate state
20004 if(IsPetNeedBeTemporaryUnsummoned())
20005 return;
20007 if(GetPetGUID())
20008 return;
20010 Pet* NewPet = new Pet;
20011 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20012 delete NewPet;
20014 m_temporaryUnsummonedPetNumber = 0;
20017 bool Player::canSeeSpellClickOn(Creature const *c) const
20019 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
20020 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(c->GetEntry()); itr != map.upper_bound(c->GetEntry()); ++itr)
20022 if(itr->second.questId == 0 || GetQuestStatus(itr->second.questId) == QUEST_STATUS_INCOMPLETE)
20023 return true;
20025 return false;