[7924] Not teleport player to non-player caster at ressurection.
[getmangos.git] / src / game / Player.cpp
bloba0989e36935ca557d852bb9ef240e22941ecf578
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 InitPrimaryProffesions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA)
643 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
647 if(getPowerType() == POWER_RUNIC_POWER)
649 SetPower(POWER_RUNE, 8);
650 SetMaxPower(POWER_RUNE, 8);
651 SetPower(POWER_RUNIC_POWER, 0);
652 SetMaxPower(POWER_RUNIC_POWER, 1000);
655 // original spells
656 learnDefaultSpells();
658 // original action bar
659 std::list<uint16>::const_iterator action_itr[4];
660 for(int i=0; i<4; ++i)
661 action_itr[i] = info->action[i].begin();
663 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
665 uint16 taction[4];
666 for(int i=0; i<4 ;++i)
667 taction[i] = (*action_itr[i]);
669 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
671 for(int i=0; i<4 ;++i)
672 ++action_itr[i];
675 // original items
676 CharStartOutfitEntry const* oEntry = NULL;
677 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
679 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
681 if(entry->RaceClassGender == RaceClassGender)
683 oEntry = entry;
684 break;
689 if(oEntry)
691 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
693 if(oEntry->ItemId[j] <= 0)
694 continue;
696 uint32 item_id = oEntry->ItemId[j];
699 // Hack for not existed item id in dbc 3.0.3
700 if(item_id==40582)
701 continue;
703 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
704 if(!iProto)
706 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
707 continue;
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count = iProto->Stackable > 0 ? uint32(iProto->Stackable) : 1;
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 if(iProto->Stackable > 4)
719 count = 4;
720 break;
721 case 59: // drink
722 if(iProto->Stackable > 2)
723 count = 2;
724 break;
728 StoreNewItemInBestSlots(item_id, count);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
733 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
740 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
742 uint16 eDest;
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
745 if( msg == EQUIP_ERR_OK )
747 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
748 EquipItem( eDest, pItem, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
751 else
753 ItemPosCountVec sDest;
754 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
755 if( msg == EQUIP_ERR_OK )
757 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
758 pItem = StoreItem( sDest, pItem, true);
761 // if this is ammo then use it
762 msg = CanUseAmmo( pItem->GetEntry() );
763 if( msg == EQUIP_ERR_OK )
764 SetAmmo( pItem->GetEntry() );
768 // all item positions resolved
770 return true;
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
775 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
777 // attempt equip by one
778 while(titem_amount > 0)
780 uint16 eDest;
781 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
782 if( msg != EQUIP_ERR_OK )
783 break;
785 EquipNewItem( eDest, titem_id, true);
786 AutoUnequipOffhandIfNeed();
787 --titem_amount;
790 if(titem_amount == 0)
791 return true; // equipped
793 // attempt store
794 ItemPosCountVec sDest;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
797 if( msg == EQUIP_ERR_OK )
799 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
800 return true; // stored
803 // item can't be added
804 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
805 return false;
808 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
810 if (MaxValue == DISABLED_MIRROR_TIMER)
812 if (CurrentValue!=DISABLED_MIRROR_TIMER)
813 StopMirrorTimer(Type);
814 return;
816 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
817 data << (uint32)Type;
818 data << CurrentValue;
819 data << MaxValue;
820 data << Regen;
821 data << (uint8)0;
822 data << (uint32)0; // spell id
823 GetSession()->SendPacket( &data );
826 void Player::StopMirrorTimer(MirrorTimerType Type)
828 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
829 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
830 data << (uint32)Type;
831 GetSession()->SendPacket( &data );
834 void Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
836 if(!isAlive() || isGameMaster())
837 return;
839 // Absorb, resist some environmental damage type
840 uint32 absorb = 0;
841 uint32 resist = 0;
842 if (type == DAMAGE_LAVA)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
844 else if (type == DAMAGE_SLIME)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
847 damage-=absorb+resist;
849 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 = GetFreePrimaryProffesionPoints())
2919 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2920 SetFreePrimaryProffesions(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 = GetFreePrimaryProffesionPoints()+1;
3121 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3122 SetFreePrimaryProffesions(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);
3484 if(m_canTitanGrip)
3486 m_canTitanGrip = false;
3487 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3488 AutoUnequipOffhandIfNeed();
3491 return true;
3494 Mail* Player::GetMail(uint32 id)
3496 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3498 if ((*itr)->messageID == id)
3500 return (*itr);
3503 return NULL;
3506 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3508 if(target == this)
3510 Object::_SetCreateBits(updateMask, target);
3512 else
3514 for(uint16 index = 0; index < m_valuesCount; index++)
3516 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3517 updateMask->SetBit(index);
3522 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3524 if(target == this)
3526 Object::_SetUpdateBits(updateMask, target);
3528 else
3530 Object::_SetUpdateBits(updateMask, target);
3531 *updateMask &= updateVisualBits;
3535 void Player::InitVisibleBits()
3537 updateVisualBits.SetCount(PLAYER_END);
3539 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3540 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3541 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3542 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3543 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3544 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3545 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3546 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3547 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3548 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3549 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3550 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3551 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3552 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3553 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3554 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3555 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3556 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3557 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3558 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3559 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3560 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3561 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3562 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3563 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3564 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3565 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3566 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3567 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3568 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3569 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3570 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3571 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3572 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3573 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3574 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3575 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3576 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3577 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3578 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3579 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3580 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3581 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3582 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3583 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3584 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3585 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3586 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3587 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3588 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3589 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3590 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3591 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3592 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3593 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3595 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3596 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3597 updateVisualBits.SetBit(PLAYER_FLAGS);
3598 updateVisualBits.SetBit(PLAYER_GUILDID);
3599 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3600 updateVisualBits.SetBit(PLAYER_BYTES);
3601 updateVisualBits.SetBit(PLAYER_BYTES_2);
3602 updateVisualBits.SetBit(PLAYER_BYTES_3);
3603 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3604 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3606 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3607 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3608 updateVisualBits.SetBit(i);
3610 // Players visible items are not inventory stuff
3611 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3613 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3615 // item creator
3616 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3617 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3619 // item entry
3620 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3622 // item enchantments
3623 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3624 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3626 // random properties
3627 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3628 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3629 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3632 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3635 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3637 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3639 if(m_items[i] == NULL)
3640 continue;
3642 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3645 if(target == this)
3647 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3649 if(m_items[i] == NULL)
3650 continue;
3652 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3654 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3656 if(m_items[i] == NULL)
3657 continue;
3659 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3663 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3666 void Player::DestroyForPlayer( Player *target ) const
3668 Unit::DestroyForPlayer( target );
3670 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3672 if(m_items[i] == NULL)
3673 continue;
3675 m_items[i]->DestroyForPlayer( target );
3678 if(target == this)
3680 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3682 if(m_items[i] == NULL)
3683 continue;
3685 m_items[i]->DestroyForPlayer( target );
3687 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
3689 if(m_items[i] == NULL)
3690 continue;
3692 m_items[i]->DestroyForPlayer( target );
3697 bool Player::HasSpell(uint32 spell) const
3699 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3700 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3701 !itr->second->disabled);
3704 bool Player::HasActiveSpell(uint32 spell) const
3706 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3707 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3708 itr->second->active && !itr->second->disabled);
3711 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3713 if (!trainer_spell)
3714 return TRAINER_SPELL_RED;
3716 if (!trainer_spell->learnedSpell)
3717 return TRAINER_SPELL_RED;
3719 // known spell
3720 if(HasSpell(trainer_spell->learnedSpell))
3721 return TRAINER_SPELL_GRAY;
3723 // check race/class requirement
3724 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3725 return TRAINER_SPELL_RED;
3727 // check level requirement
3728 if(getLevel() < trainer_spell->reqLevel)
3729 return TRAINER_SPELL_RED;
3731 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->learnedSpell))
3733 // check prev.rank requirement
3734 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3735 return TRAINER_SPELL_RED;
3737 // check additional spell requirement
3738 if(spell_chain->req && !HasSpell(spell_chain->req))
3739 return TRAINER_SPELL_RED;
3742 // check skill requirement
3743 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3744 return TRAINER_SPELL_RED;
3746 // exist, already checked at loading
3747 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3749 // secondary prof. or not prof. spell
3750 uint32 skill = spell->EffectMiscValue[1];
3752 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3753 return TRAINER_SPELL_GREEN;
3755 // check primary prof. limit
3756 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3757 return TRAINER_SPELL_GREEN_DISABLED;
3759 return TRAINER_SPELL_GREEN;
3762 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3764 uint32 guid = GUID_LOPART(playerguid);
3766 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3767 // bones will be deleted by corpse/bones deleting thread shortly
3768 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3770 // remove from guild
3771 uint32 guildId = GetGuildIdFromDB(playerguid);
3772 if(guildId != 0)
3774 Guild* guild = objmgr.GetGuildById(guildId);
3775 if(guild)
3776 guild->DelMember(guid);
3779 // remove from arena teams
3780 LeaveAllArenaTeams(playerguid);
3782 // the player was uninvited already on logout so just remove from group
3783 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3784 if(resultGroup)
3786 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3787 delete resultGroup;
3788 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3789 if(group)
3791 RemoveFromGroup(group, playerguid);
3795 // remove signs from petitions (also remove petitions if owner);
3796 RemovePetitionsAndSigns(playerguid, 10);
3798 // return back all mails with COD and Item 0 1 2 3 4 5 6
3799 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);
3800 if(resultMail)
3804 Field *fields = resultMail->Fetch();
3806 uint32 mail_id = fields[0].GetUInt32();
3807 uint16 mailTemplateId= fields[1].GetUInt16();
3808 uint32 sender = fields[2].GetUInt32();
3809 std::string subject = fields[3].GetCppString();
3810 uint32 itemTextId = fields[4].GetUInt32();
3811 uint32 money = fields[5].GetUInt32();
3812 bool has_items = fields[6].GetBool();
3814 //we can return mail now
3815 //so firstly delete the old one
3816 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3818 MailItemsInfo mi;
3819 if(has_items)
3821 // data needs to be at first place for Item::LoadFromDB
3822 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);
3823 if(resultItems)
3827 Field *fields2 = resultItems->Fetch();
3829 uint32 item_guidlow = fields2[1].GetUInt32();
3830 uint32 item_template = fields2[2].GetUInt32();
3832 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3833 if(!itemProto)
3835 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3836 continue;
3839 Item *pItem = NewItemOrBag(itemProto);
3840 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
3842 pItem->FSetState(ITEM_REMOVED);
3843 pItem->SaveToDB(); // it also deletes item object !
3844 continue;
3847 mi.AddItem(item_guidlow, item_template, pItem);
3849 while (resultItems->NextRow());
3851 delete resultItems;
3855 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3857 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3859 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3861 while (resultMail->NextRow());
3863 delete resultMail;
3866 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3867 // Get guids of character's pets, will deleted in transaction
3868 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3870 // NOW we can finally clear other DB data related to character
3871 CharacterDatabase.BeginTransaction();
3872 if (resultPets)
3876 Field *fields3 = resultPets->Fetch();
3877 uint32 petguidlow = fields3[0].GetUInt32();
3878 Pet::DeleteFromDB(petguidlow);
3879 } while (resultPets->NextRow());
3880 delete resultPets;
3883 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3884 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3885 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3886 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3887 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3888 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3889 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3890 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3891 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3892 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3893 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3894 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3895 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3896 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3897 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3898 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3899 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3900 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3901 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3902 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3903 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3904 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3905 CharacterDatabase.CommitTransaction();
3907 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3908 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3911 void Player::SetMovement(PlayerMovementType pType)
3913 WorldPacket data;
3914 switch(pType)
3916 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3917 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3918 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3919 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3920 default:
3921 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3922 return;
3924 data.append(GetPackGUID());
3925 data << uint32(0);
3926 GetSession()->SendPacket( &data );
3929 /* Preconditions:
3930 - a resurrectable corpse must not be loaded for the player (only bones)
3931 - the player must be in world
3933 void Player::BuildPlayerRepop()
3935 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3936 data.append(GetPackGUID());
3937 GetSession()->SendPacket(&data);
3939 if(getRace() == RACE_NIGHTELF)
3940 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)
3941 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3943 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3944 // there must be SMSG.STOP_MIRROR_TIMER
3945 // there we must send 888 opcode
3947 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3948 if(GetCorpse())
3950 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3951 assert(false);
3954 // create a corpse and place it at the player's location
3955 CreateCorpse();
3956 Corpse *corpse = GetCorpse();
3957 if(!corpse)
3959 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3960 return;
3962 GetMap()->Add(corpse);
3964 // convert player body to ghost
3965 SetHealth( 1 );
3967 SetMovement(MOVE_WATER_WALK);
3968 if(!GetSession()->isLogingOut())
3969 SetMovement(MOVE_UNROOT);
3971 // BG - remove insignia related
3972 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3974 SendCorpseReclaimDelay();
3976 // to prevent cheating
3977 corpse->ResetGhostTime();
3979 StopMirrorTimers(); //disable timers(bars)
3981 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3983 // set and clear other
3984 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
3987 void Player::SendDelayResponse(const uint32 ml_seconds)
3989 //FIXME: is this delay time arg really need? 50msec by default in code
3990 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3991 data << (uint32)time(NULL);
3992 data << (uint32)0;
3993 GetSession()->SendPacket( &data );
3996 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3998 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3999 data << uint32(-1);
4000 data << float(0);
4001 data << float(0);
4002 data << float(0);
4003 GetSession()->SendPacket(&data);
4005 // speed change, land walk
4007 // remove death flag + set aura
4008 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4009 if(getRace() == RACE_NIGHTELF)
4010 RemoveAurasDueToSpell(20584); // speed bonuses
4011 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4013 setDeathState(ALIVE);
4015 SetMovement(MOVE_LAND_WALK);
4016 SetMovement(MOVE_UNROOT);
4018 m_deathTimer = 0;
4020 // set health/powers (0- will be set in caller)
4021 if(restore_percent>0.0f)
4023 SetHealth(uint32(GetMaxHealth()*restore_percent));
4024 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4025 SetPower(POWER_RAGE, 0);
4026 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4029 // trigger update zone for alive state zone updates
4030 uint32 newzone, newarea;
4031 GetZoneAndAreaId(newzone,newarea);
4032 UpdateZone(newzone,newarea);
4034 // update visibility
4035 ObjectAccessor::UpdateVisibilityForPlayer(this);
4037 if(!applySickness)
4038 return;
4040 //Characters from level 1-10 are not affected by resurrection sickness.
4041 //Characters from level 11-19 will suffer from one minute of sickness
4042 //for each level they are above 10.
4043 //Characters level 20 and up suffer from ten minutes of sickness.
4044 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4046 if(int32(getLevel()) >= startLevel)
4048 // set resurrection sickness
4049 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4051 // not full duration
4052 if(int32(getLevel()) < startLevel+9)
4054 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4056 for(int i =0; i < 3; ++i)
4058 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4060 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4061 Aur->SendAuraUpdate(false);
4068 void Player::KillPlayer()
4070 SetMovement(MOVE_ROOT);
4072 StopMirrorTimers(); //disable timers(bars)
4074 setDeathState(CORPSE);
4075 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4077 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4078 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4080 // 6 minutes until repop at graveyard
4081 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4083 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4085 // don't create corpse at this moment, player might be falling
4087 // update visibility
4088 ObjectAccessor::UpdateObjectVisibility(this);
4091 void Player::CreateCorpse()
4093 // prevent existence 2 corpse for player
4094 SpawnCorpseBones();
4096 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4098 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4099 SetPvPDeath(false);
4101 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4103 delete corpse;
4104 return;
4107 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4108 _pb = GetUInt32Value(PLAYER_BYTES);
4109 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4111 uint8 race = (uint8)(_uf);
4112 uint8 skin = (uint8)(_pb);
4113 uint8 face = (uint8)(_pb >> 8);
4114 uint8 hairstyle = (uint8)(_pb >> 16);
4115 uint8 haircolor = (uint8)(_pb >> 24);
4116 uint8 facialhair = (uint8)(_pb2);
4118 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4119 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4121 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4122 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4124 uint32 flags = CORPSE_FLAG_UNK2;
4125 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4126 flags |= CORPSE_FLAG_HIDE_HELM;
4127 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4128 flags |= CORPSE_FLAG_HIDE_CLOAK;
4129 if(InBattleGround() && !InArena())
4130 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4131 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4133 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4135 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4137 uint32 iDisplayID;
4138 uint16 iIventoryType;
4139 uint32 _cfi;
4140 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4142 if(m_items[i])
4144 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4145 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
4147 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
4148 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
4152 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4153 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4154 assert(entry);
4155 if(entry->map_type != MAP_BATTLEGROUND)
4156 corpse->SaveToDB();
4158 // register for player, but not show
4159 ObjectAccessor::Instance().AddCorpse(corpse);
4162 void Player::SpawnCorpseBones()
4164 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4165 SaveToDB(); // prevent loading as ghost without corpse
4168 Corpse* Player::GetCorpse() const
4170 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4173 void Player::DurabilityLossAll(double percent, bool inventory)
4175 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4176 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4177 DurabilityLoss(pItem,percent);
4179 if(inventory)
4181 // bags not have durability
4182 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4184 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4185 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4186 DurabilityLoss(pItem,percent);
4188 // keys not have durability
4189 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4191 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4192 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4193 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4194 if(Item* pItem = GetItemByPos( i, j ))
4195 DurabilityLoss(pItem,percent);
4199 void Player::DurabilityLoss(Item* item, double percent)
4201 if(!item )
4202 return;
4204 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4206 if(!pMaxDurability)
4207 return;
4209 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4211 if(pDurabilityLoss < 1 )
4212 pDurabilityLoss = 1;
4214 DurabilityPointsLoss(item,pDurabilityLoss);
4217 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4219 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4220 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4221 DurabilityPointsLoss(pItem,points);
4223 if(inventory)
4225 // bags not have durability
4226 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4228 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4229 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4230 DurabilityPointsLoss(pItem,points);
4232 // keys not have durability
4233 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4235 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4236 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4237 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4238 if(Item* pItem = GetItemByPos( i, j ))
4239 DurabilityPointsLoss(pItem,points);
4243 void Player::DurabilityPointsLoss(Item* item, int32 points)
4245 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4246 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4247 int32 pNewDurability = pOldDurability - points;
4249 if (pNewDurability < 0)
4250 pNewDurability = 0;
4251 else if (pNewDurability > pMaxDurability)
4252 pNewDurability = pMaxDurability;
4254 if (pOldDurability != pNewDurability)
4256 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4257 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4258 _ApplyItemMods(item,item->GetSlot(), false);
4260 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4262 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4263 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4264 _ApplyItemMods(item,item->GetSlot(), true);
4266 item->SetState(ITEM_CHANGED, this);
4270 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4272 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4273 DurabilityPointsLoss(pItem,1);
4276 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4278 uint32 TotalCost = 0;
4279 // equipped, backpack, bags itself
4280 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4281 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4283 // bank, buyback and keys not repaired
4285 // items in inventory bags
4286 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4287 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4288 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4289 return TotalCost;
4292 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4294 Item* item = GetItemByPos(pos);
4296 uint32 TotalCost = 0;
4297 if(!item)
4298 return TotalCost;
4300 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4301 if(!maxDurability)
4302 return TotalCost;
4304 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4306 if(cost)
4308 uint32 LostDurability = maxDurability - curDurability;
4309 if(LostDurability>0)
4311 ItemPrototype const *ditemProto = item->GetProto();
4313 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4314 if(!dcost)
4316 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4317 return TotalCost;
4320 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4321 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4322 if(!dQualitymodEntry)
4324 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4325 return TotalCost;
4328 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4329 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4331 costs = uint32(costs * discountMod);
4333 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4334 costs = 1;
4336 if (guildBank)
4338 if (GetGuildId()==0)
4340 DEBUG_LOG("You are not member of a guild");
4341 return TotalCost;
4344 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4345 if (!pGuild)
4346 return TotalCost;
4348 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4350 DEBUG_LOG("You do not have rights to withdraw for repairs");
4351 return TotalCost;
4354 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4356 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4357 return TotalCost;
4360 if (pGuild->GetGuildBankMoney() < costs)
4362 DEBUG_LOG("There is not enough money in bank");
4363 return TotalCost;
4366 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4367 TotalCost = costs;
4369 else if (GetMoney() < costs)
4371 DEBUG_LOG("You do not have enough money");
4372 return TotalCost;
4374 else
4375 ModifyMoney( -int32(costs) );
4379 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4380 item->SetState(ITEM_CHANGED, this);
4382 // reapply mods for total broken and repaired item if equipped
4383 if(IsEquipmentPos(pos) && !curDurability)
4384 _ApplyItemMods(item,pos & 255, true);
4385 return TotalCost;
4388 void Player::RepopAtGraveyard()
4390 // note: this can be called also when the player is alive
4391 // for example from WorldSession::HandleMovementOpcodes
4393 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4395 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4396 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4398 ResurrectPlayer(0.5f);
4399 SpawnCorpseBones();
4402 WorldSafeLocsEntry const *ClosestGrave = NULL;
4404 // Special handle for battleground maps
4405 if( BattleGround *bg = GetBattleGround() )
4406 ClosestGrave = bg->GetClosestGraveYard(this);
4407 else
4408 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4410 // stop countdown until repop
4411 m_deathTimer = 0;
4413 // if no grave found, stay at the current location
4414 // and don't show spirit healer location
4415 if(ClosestGrave)
4417 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4418 if(isDead()) // not send if alive, because it used in TeleportTo()
4420 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4421 data << ClosestGrave->map_id;
4422 data << ClosestGrave->x;
4423 data << ClosestGrave->y;
4424 data << ClosestGrave->z;
4425 GetSession()->SendPacket(&data);
4430 void Player::JoinedChannel(Channel *c)
4432 m_channels.push_back(c);
4435 void Player::LeftChannel(Channel *c)
4437 m_channels.remove(c);
4440 void Player::CleanupChannels()
4442 while(!m_channels.empty())
4444 Channel* ch = *m_channels.begin();
4445 m_channels.erase(m_channels.begin()); // remove from player's channel list
4446 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4447 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4448 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4451 sLog.outDebug("Player: channels cleaned up!");
4454 void Player::UpdateLocalChannels(uint32 newZone )
4456 if(m_channels.empty())
4457 return;
4459 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4460 if(!current_zone)
4461 return;
4463 ChannelMgr* cMgr = channelMgr(GetTeam());
4464 if(!cMgr)
4465 return;
4467 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4469 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4471 next = i; ++next;
4473 // skip non built-in channels
4474 if(!(*i)->IsConstant())
4475 continue;
4477 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4478 if(!ch)
4479 continue;
4481 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4482 continue;
4484 // new channel
4485 char new_channel_name_buf[100];
4486 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4487 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4489 if((*i)!=new_channel)
4491 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4493 // leave old channel
4494 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4495 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4496 LeftChannel(*i); // remove from player's channel list
4497 cMgr->LeftChannel(name); // delete if empty
4500 sLog.outDebug("Player: channels cleaned up!");
4503 void Player::LeaveLFGChannel()
4505 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4507 if((*i)->IsLFG())
4509 (*i)->Leave(GetGUID());
4510 break;
4515 void Player::UpdateDefense()
4517 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4519 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4521 // update dependent from defense skill part
4522 UpdateDefenseBonusesMod();
4526 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4528 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4530 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4531 return;
4534 float val = 1.0f;
4536 switch(modType)
4538 case FLAT_MOD:
4539 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4540 break;
4541 case PCT_MOD:
4542 if(amount <= -100.0f)
4543 amount = -200.0f;
4545 val = (100.0f + amount) / 100.0f;
4546 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4547 break;
4550 if(!CanModifyStats())
4551 return;
4553 switch(modGroup)
4555 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4556 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4557 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4558 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4559 default: break;
4563 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4565 if(modGroup >= BASEMOD_END || modType > MOD_END)
4567 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4568 return 0.0f;
4571 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4572 return 0.0f;
4574 return m_auraBaseMod[modGroup][modType];
4577 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4579 if(modGroup >= BASEMOD_END)
4581 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4582 return 0.0f;
4585 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4586 return 0.0f;
4588 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4591 uint32 Player::GetShieldBlockValue() const
4593 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4595 value = (value < 0) ? 0 : value;
4597 return uint32(value);
4600 float Player::GetMeleeCritFromAgility()
4602 uint32 level = getLevel();
4603 uint32 pclass = getClass();
4605 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4607 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4608 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4609 if (critBase==NULL || critRatio==NULL)
4610 return 0.0f;
4612 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4613 return crit*100.0f;
4616 float Player::GetDodgeFromAgility()
4618 // Table for base dodge values
4619 float dodge_base[MAX_CLASSES] = {
4620 0.0075f, // Warrior
4621 0.00652f, // Paladin
4622 -0.0545f, // Hunter
4623 -0.0059f, // Rogue
4624 0.03183f, // Priest
4625 0.0114f, // DK
4626 0.0167f, // Shaman
4627 0.034575f, // Mage
4628 0.02011f, // Warlock
4629 0.0f, // ??
4630 -0.0187f // Druid
4632 // Crit/agility to dodge/agility coefficient multipliers
4633 float crit_to_dodge[MAX_CLASSES] = {
4634 1.1f, // Warrior
4635 1.0f, // Paladin
4636 1.6f, // Hunter
4637 2.0f, // Rogue
4638 1.0f, // Priest
4639 1.0f, // DK?
4640 1.0f, // Shaman
4641 1.0f, // Mage
4642 1.0f, // Warlock
4643 0.0f, // ??
4644 1.7f // Druid
4647 uint32 level = getLevel();
4648 uint32 pclass = getClass();
4650 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4652 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4653 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4654 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4655 return 0.0f;
4657 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4658 return dodge*100.0f;
4661 float Player::GetSpellCritFromIntellect()
4663 uint32 level = getLevel();
4664 uint32 pclass = getClass();
4666 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4668 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4669 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4670 if (critBase==NULL || critRatio==NULL)
4671 return 0.0f;
4673 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4674 return crit*100.0f;
4677 float Player::GetRatingCoefficient(CombatRating cr) const
4679 uint32 level = getLevel();
4681 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4683 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4684 if (Rating == NULL)
4685 return 1.0f; // By default use minimum coefficient (not must be called)
4687 return Rating->ratio;
4690 float Player::GetRatingBonusValue(CombatRating cr) const
4692 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4695 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4697 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.2f;
4698 if (melee>33.0f) melee = 33.0f;
4699 return uint32 (melee * damage /100.0f);
4702 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4704 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.2f;
4705 if (ranged>33.0f) ranged=33.0f;
4706 return uint32 (ranged * damage /100.0f);
4709 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4711 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.2f;
4712 // In wow script resilience limited to 33%
4713 if (spell>33.0f)
4714 spell = 33.0f;
4715 return uint32 (spell * damage / 100.0f);
4718 uint32 Player::GetDotDamageReduction(uint32 damage) const
4720 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4721 // Dot resilience not limited (limit it by 100%)
4722 if (spellDot > 100.0f)
4723 spellDot = 100.0f;
4724 return uint32 (spellDot * damage / 100.0f);
4727 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4729 switch (attType)
4731 case BASE_ATTACK:
4732 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4733 case OFF_ATTACK:
4734 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4735 default:
4736 break;
4738 return 0.0f;
4741 float Player::OCTRegenHPPerSpirit()
4743 uint32 level = getLevel();
4744 uint32 pclass = getClass();
4746 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4748 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4749 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4750 if (baseRatio==NULL || moreRatio==NULL)
4751 return 0.0f;
4753 // Formula from PaperDollFrame script
4754 float spirit = GetStat(STAT_SPIRIT);
4755 float baseSpirit = spirit;
4756 if (baseSpirit>50) baseSpirit = 50;
4757 float moreSpirit = spirit - baseSpirit;
4758 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4759 return regen;
4762 float Player::OCTRegenMPPerSpirit()
4764 uint32 level = getLevel();
4765 uint32 pclass = getClass();
4767 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4769 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4770 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4771 if (moreRatio==NULL)
4772 return 0.0f;
4774 // Formula get from PaperDollFrame script
4775 float spirit = GetStat(STAT_SPIRIT);
4776 float regen = spirit * moreRatio->ratio;
4777 return regen;
4780 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4782 m_baseRatingValue[cr]+=(apply ? value : -value);
4784 int32 amount = uint32(m_baseRatingValue[cr]);
4785 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4786 // stat used stored in miscValueB for this aura
4787 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4788 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4789 if ((*i)->GetMiscValue() & (1<<cr))
4790 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4791 if (amount < 0)
4792 amount = 0;
4793 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4795 float RatingCoeffecient = GetRatingCoefficient(cr);
4796 float RatingChange = 0.0f;
4798 bool affectStats = CanModifyStats();
4800 switch (cr)
4802 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4803 case CR_DEFENSE_SKILL:
4804 UpdateDefenseBonusesMod();
4805 break;
4806 case CR_DODGE:
4807 UpdateDodgePercentage();
4808 break;
4809 case CR_PARRY:
4810 UpdateParryPercentage();
4811 break;
4812 case CR_BLOCK:
4813 UpdateBlockPercentage();
4814 break;
4815 case CR_HIT_MELEE:
4816 UpdateMeleeHitChances();
4817 break;
4818 case CR_HIT_RANGED:
4819 UpdateRangedHitChances();
4820 break;
4821 case CR_HIT_SPELL:
4822 UpdateSpellHitChances();
4823 break;
4824 case CR_CRIT_MELEE:
4825 if(affectStats)
4827 UpdateCritPercentage(BASE_ATTACK);
4828 UpdateCritPercentage(OFF_ATTACK);
4830 break;
4831 case CR_CRIT_RANGED:
4832 if(affectStats)
4833 UpdateCritPercentage(RANGED_ATTACK);
4834 break;
4835 case CR_CRIT_SPELL:
4836 if(affectStats)
4837 UpdateAllSpellCritChances();
4838 break;
4839 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4840 case CR_HIT_TAKEN_RANGED:
4841 break;
4842 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4843 break;
4844 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4845 case CR_CRIT_TAKEN_RANGED:
4846 break;
4847 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4848 break;
4849 case CR_HASTE_MELEE:
4850 RatingChange = value / RatingCoeffecient;
4851 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4852 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4853 break;
4854 case CR_HASTE_RANGED:
4855 RatingChange = value / RatingCoeffecient;
4856 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4857 break;
4858 case CR_HASTE_SPELL:
4859 RatingChange = value / RatingCoeffecient;
4860 ApplyCastTimePercentMod(RatingChange,apply);
4861 break;
4862 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4863 case CR_WEAPON_SKILL_OFFHAND:
4864 case CR_WEAPON_SKILL_RANGED:
4865 break;
4866 case CR_EXPERTISE:
4867 if(affectStats)
4869 UpdateExpertise(BASE_ATTACK);
4870 UpdateExpertise(OFF_ATTACK);
4872 break;
4873 case CR_ARMOR_PENETRATION:
4874 break;
4878 void Player::SetRegularAttackTime()
4880 for(int i = 0; i < MAX_ATTACK; ++i)
4882 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4883 if(tmpitem && !tmpitem->IsBroken())
4885 ItemPrototype const *proto = tmpitem->GetProto();
4886 if(proto->Delay)
4887 SetAttackTime(WeaponAttackType(i), proto->Delay);
4888 else
4889 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4894 //skill+step, checking for max value
4895 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4897 if(!skill_id)
4898 return false;
4900 uint16 i=0;
4901 for (; i < PLAYER_MAX_SKILLS; ++i)
4902 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4903 break;
4905 if(i>=PLAYER_MAX_SKILLS)
4906 return false;
4908 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4909 uint32 value = SKILL_VALUE(data);
4910 uint32 max = SKILL_MAX(data);
4912 if ((!max) || (!value) || (value >= max))
4913 return false;
4915 if (value*512 < max*urand(0,512))
4917 uint32 new_value = value+step;
4918 if(new_value > max)
4919 new_value = max;
4921 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4922 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
4923 return true;
4926 return false;
4929 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4931 if ( SkillValue >= GrayLevel )
4932 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4933 if ( SkillValue >= GreenLevel )
4934 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4935 if ( SkillValue >= YellowLevel )
4936 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4937 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4940 bool Player::UpdateCraftSkill(uint32 spellid)
4942 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4944 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4945 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4947 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4949 if(_spell_idx->second->skillId)
4951 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4953 // Alchemy Discoveries here
4954 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4955 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4957 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4958 learnSpell(discoveredSpell,false);
4961 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4963 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4964 _spell_idx->second->max_value,
4965 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4966 _spell_idx->second->min_value),
4967 craft_skill_gain);
4970 return false;
4973 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4975 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4977 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4979 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4980 switch (SkillId)
4982 case SKILL_HERBALISM:
4983 case SKILL_LOCKPICKING:
4984 case SKILL_JEWELCRAFTING:
4985 case SKILL_INSCRIPTION:
4986 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4987 case SKILL_SKINNING:
4988 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4989 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4990 else
4991 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4992 case SKILL_MINING:
4993 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4994 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4995 else
4996 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4998 return false;
5001 bool Player::UpdateFishingSkill()
5003 sLog.outDebug("UpdateFishingSkill");
5005 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5007 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5009 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5011 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5014 // levels sync. with spell requirement for skill levels to learn
5015 // bonus abilities in sSkillLineAbilityStore
5016 // Used only to avoid scan DBC at each skill grow
5017 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5019 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5021 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5022 if ( !SkillId )
5023 return false;
5025 if(Chance <= 0) // speedup in 0 chance case
5027 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5028 return false;
5031 uint16 i=0;
5032 for (; i < PLAYER_MAX_SKILLS; ++i)
5033 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
5034 if ( i >= PLAYER_MAX_SKILLS )
5035 return false;
5037 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5038 uint16 SkillValue = SKILL_VALUE(data);
5039 uint16 MaxValue = SKILL_MAX(data);
5041 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5042 return false;
5044 int32 Roll = irand(1,1000);
5046 if ( Roll <= Chance )
5048 uint32 new_value = SkillValue+step;
5049 if(new_value > MaxValue)
5050 new_value = MaxValue;
5052 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
5053 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5055 if((SkillValue < *bsl && new_value >= *bsl))
5057 learnSkillRewardedSpells( SkillId, new_value);
5058 break;
5061 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5062 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5063 return true;
5066 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5067 return false;
5070 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5072 // no skill gain in pvp
5073 Unit *pVictim = getVictim();
5074 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
5075 return;
5077 if(IsInFeralForm())
5078 return; // always maximized SKILL_FERAL_COMBAT in fact
5080 if(m_form == FORM_TREE)
5081 return; // use weapon but not skill up
5083 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5085 switch(attType)
5087 case BASE_ATTACK:
5089 Item *tmpitem = GetWeaponForAttack(attType,true);
5091 if (!tmpitem)
5092 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5093 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5094 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5095 break;
5097 case OFF_ATTACK:
5098 case RANGED_ATTACK:
5100 Item *tmpitem = GetWeaponForAttack(attType,true);
5101 if (tmpitem)
5102 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5103 break;
5106 UpdateAllCritPercentages();
5109 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5111 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5112 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5113 uint32 moblevel = pVictim->getLevelForTarget(this);
5114 if(moblevel < greylevel)
5115 return;
5117 if (moblevel > plevel + 5)
5118 moblevel = plevel + 5;
5120 uint32 lvldif = moblevel - greylevel;
5121 if(lvldif < 3)
5122 lvldif = 3;
5124 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5125 if(skilldif <= 0)
5126 return;
5128 float chance = float(3 * lvldif * skilldif) / plevel;
5129 if(!defence)
5131 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5132 chance *= 0.1f * GetStat(STAT_INTELLECT);
5135 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5137 if(roll_chance_f(chance))
5139 if(defence)
5140 UpdateDefense();
5141 else
5142 UpdateWeaponSkill(attType);
5144 else
5145 return;
5148 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5150 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5151 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
5153 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5154 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5155 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5157 if(talent) // permanent bonus stored in high part
5158 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5159 else // temporary/item bonus stored in low part
5160 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5161 return;
5165 void Player::UpdateSkillsForLevel()
5167 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5168 uint32 maxSkill = GetMaxSkillValueForLevel();
5170 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5172 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5173 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5175 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5177 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5178 if(!pSkill)
5179 continue;
5181 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5182 continue;
5184 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5185 uint32 max = SKILL_MAX(data);
5186 uint32 val = SKILL_VALUE(data);
5188 /// update only level dependent max skill values
5189 if(max!=1)
5191 /// miximize skill always
5192 if(alwaysMaxSkill)
5193 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
5194 /// update max skill value if current max skill not maximized
5195 else if(max != maxconfskill)
5196 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
5201 void Player::UpdateSkillsToMaxSkillsForLevel()
5203 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5204 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5206 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
5207 if( IsProfessionOrRidingSkill(pskill))
5208 continue;
5209 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
5211 uint32 max = SKILL_MAX(data);
5213 if(max > 1)
5214 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
5216 if(pskill == SKILL_DEFENSE)
5217 UpdateDefenseBonusesMod();
5221 // This functions sets a skill line value (and adds if doesn't exist yet)
5222 // To "remove" a skill line, set it's values to zero
5223 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5225 if(!id)
5226 return;
5228 uint16 i=0;
5229 for (; i < PLAYER_MAX_SKILLS; ++i)
5230 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
5232 if(i<PLAYER_MAX_SKILLS) //has skill
5234 if(currVal)
5236 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5237 learnSkillRewardedSpells(id, currVal);
5238 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5239 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5241 else //remove
5243 // clear skill fields
5244 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
5245 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
5246 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5248 // remove all spells that related to this skill
5249 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5250 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5251 if (pAbility->skillId==id)
5252 removeSpell(spellmgr.GetFirstSpellInChain(pAbility->spellId));
5255 else if(currVal) //add
5257 for (i=0; i < PLAYER_MAX_SKILLS; ++i)
5258 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5260 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5261 if(!pSkill)
5263 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5264 return;
5266 // enable unlearn button for primary professions only
5267 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5268 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5269 else
5270 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5271 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5272 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5273 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5275 // apply skill bonuses
5276 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5278 // temporary bonuses
5279 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5280 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5281 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5282 (*j)->ApplyModifier(true);
5284 // permanent bonuses
5285 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5286 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5287 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5288 (*j)->ApplyModifier(true);
5290 // Learn all spells for skill
5291 learnSkillRewardedSpells(id, currVal);
5292 return;
5297 bool Player::HasSkill(uint32 skill) const
5299 if(!skill)return false;
5300 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5302 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5304 return true;
5307 return false;
5310 uint16 Player::GetSkillValue(uint32 skill) const
5312 if(!skill)
5313 return 0;
5315 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5317 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5319 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5321 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5322 result += SKILL_TEMP_BONUS(bonus);
5323 result += SKILL_PERM_BONUS(bonus);
5324 return result < 0 ? 0 : result;
5327 return 0;
5330 uint16 Player::GetMaxSkillValue(uint32 skill) const
5332 if(!skill)return 0;
5333 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5335 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5337 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5339 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5340 result += SKILL_TEMP_BONUS(bonus);
5341 result += SKILL_PERM_BONUS(bonus);
5342 return result < 0 ? 0 : result;
5345 return 0;
5348 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5350 if(!skill)return 0;
5351 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5353 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5355 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5358 return 0;
5361 uint16 Player::GetBaseSkillValue(uint32 skill) const
5363 if(!skill)return 0;
5364 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5366 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5368 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5369 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5370 return result < 0 ? 0 : result;
5373 return 0;
5376 uint16 Player::GetPureSkillValue(uint32 skill) const
5378 if(!skill)return 0;
5379 for (uint16 i=0; i < PLAYER_MAX_SKILLS; ++i)
5381 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5383 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5386 return 0;
5389 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5391 if(!skill)
5392 return 0;
5394 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5396 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5398 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5402 return 0;
5405 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5407 if(!skill)
5408 return 0;
5410 for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
5412 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5414 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5418 return 0;
5421 void Player::SendInitialActionButtons() const
5423 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5425 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5426 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5428 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5429 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5431 data << uint16(itr->second.action);
5432 data << uint8(itr->second.misc);
5433 data << uint8(itr->second.type);
5435 else
5437 data << uint32(0);
5441 GetSession()->SendPacket( &data );
5442 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5445 bool Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5447 if(button >= MAX_ACTION_BUTTONS)
5449 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5450 return false;
5453 // check cheating with adding non-known spells to action bar
5454 if(type==ACTION_BUTTON_SPELL)
5456 if(!sSpellStore.LookupEntry(action))
5458 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5459 return false;
5462 if(!HasSpell(action))
5464 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5465 return false;
5469 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5471 if (buttonItr==m_actionButtons.end())
5472 { // just add new button
5473 m_actionButtons[button] = ActionButton(action,type,misc);
5475 else
5476 { // change state of current button
5477 ActionButtonUpdateState uState = buttonItr->second.uState;
5478 buttonItr->second = ActionButton(action,type,misc);
5479 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5482 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5483 return true;
5486 void Player::removeActionButton(uint8 button)
5488 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5489 if (buttonItr==m_actionButtons.end())
5490 return;
5492 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5493 m_actionButtons.erase(buttonItr); // new and not saved
5494 else
5495 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5497 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5500 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5502 // prevent crash when a bad coord is sent by the client
5503 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5505 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5506 return false;
5509 Map *m = GetMap();
5511 const float old_x = GetPositionX();
5512 const float old_y = GetPositionY();
5513 const float old_z = GetPositionZ();
5514 const float old_r = GetOrientation();
5516 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5518 if (teleport || old_x != x || old_y != y || old_z != z)
5519 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5520 else
5521 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5523 // move and update visible state if need
5524 m->PlayerRelocation(this, x, y, z, orientation);
5526 // reread after Map::Relocation
5527 m = GetMap();
5528 x = GetPositionX();
5529 y = GetPositionY();
5530 z = GetPositionZ();
5532 // group update
5533 if(GetGroup() && (old_x != x || old_y != y))
5534 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5537 // code block for underwater state update
5538 UpdateUnderwaterState(m, x, y, z);
5540 CheckExploreSystem();
5542 return true;
5545 void Player::SaveRecallPosition()
5547 m_recallMap = GetMapId();
5548 m_recallX = GetPositionX();
5549 m_recallY = GetPositionY();
5550 m_recallZ = GetPositionZ();
5551 m_recallO = GetOrientation();
5554 void Player::SendMessageToSet(WorldPacket *data, bool self)
5556 GetMap()->MessageBroadcast(this, data, self);
5559 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5561 GetMap()->MessageDistBroadcast(this, data, dist, self);
5564 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5566 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5569 void Player::SendDirectMessage(WorldPacket *data)
5571 GetSession()->SendPacket(data);
5574 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5576 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5577 data << uint32(CinematicSequenceId);
5578 SendDirectMessage(&data);
5581 void Player::SendMovieStart(uint32 MovieId)
5583 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5584 data << uint32(MovieId);
5585 SendDirectMessage(&data);
5588 void Player::CheckExploreSystem()
5590 if (!isAlive())
5591 return;
5593 if (isInFlight())
5594 return;
5596 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5597 if(areaFlag==0xffff)
5598 return;
5599 int offset = areaFlag / 32;
5601 if(offset >= 128)
5603 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);
5604 return;
5607 uint32 val = (uint32)(1 << (areaFlag % 32));
5608 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5610 if( !(currFields & val) )
5612 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5614 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5616 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5617 if(!p)
5619 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5621 else if(p->area_level > 0)
5623 uint32 area = p->ID;
5624 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5626 SendExplorationExperience(area,0);
5628 else
5630 int32 diff = int32(getLevel()) - p->area_level;
5631 uint32 XP = 0;
5632 if (diff < -5)
5634 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5636 else if (diff > 5)
5638 int32 exploration_percent = (100-((diff-5)*5));
5639 if (exploration_percent > 100)
5640 exploration_percent = 100;
5641 else if (exploration_percent < 0)
5642 exploration_percent = 0;
5644 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5646 else
5648 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5651 GiveXP( XP, NULL );
5652 SendExplorationExperience(area,XP);
5654 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5659 uint32 Player::TeamForRace(uint8 race)
5661 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5662 if(!rEntry)
5664 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5665 return ALLIANCE;
5668 switch(rEntry->TeamID)
5670 case 7: return ALLIANCE;
5671 case 1: return HORDE;
5674 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5675 return ALLIANCE;
5678 uint32 Player::getFactionForRace(uint8 race)
5680 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5681 if(!rEntry)
5683 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5684 return 0;
5687 return rEntry->FactionID;
5690 void Player::setFactionForRace(uint8 race)
5692 m_team = TeamForRace(race);
5693 setFaction( getFactionForRace(race) );
5696 ReputationRank Player::GetReputationRank(uint32 faction) const
5698 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5699 return GetReputationMgr().GetRank(factionEntry);
5702 //Calculate total reputation percent player gain with quest/creature level
5703 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5705 float percent = 100.0f;
5707 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5709 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5710 percent *= rate;
5712 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5714 if (!for_quest)
5715 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5717 percent += rep > 0 ? repMod : -repMod;
5719 if (percent <= 0.0f)
5720 return 0;
5722 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5725 //Calculates how many reputation points player gains in victim's enemy factions
5726 void Player::RewardReputation(Unit *pVictim, float rate)
5728 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5729 return;
5731 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5733 if(!Rep)
5734 return;
5736 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5738 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
5739 donerep1 = int32(donerep1*rate);
5740 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5741 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
5742 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5743 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
5745 // Wiki: Team factions value divided by 2
5746 if (factionEntry1 && Rep->is_teamaward1)
5748 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5749 if(team1_factionEntry)
5750 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
5754 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5756 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
5757 donerep2 = int32(donerep2*rate);
5758 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5759 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
5760 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5761 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
5763 // Wiki: Team factions value divided by 2
5764 if (factionEntry2 && Rep->is_teamaward2)
5766 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5767 if(team2_factionEntry)
5768 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
5773 //Calculate how many reputation points player gain with the quest
5774 void Player::RewardReputation(Quest const *pQuest)
5776 // quest reputation reward/loss
5777 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5779 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5781 int32 rep = CalculateReputationGain(GetQuestLevel(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
5782 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5783 if(factionEntry)
5784 GetReputationMgr().ModifyReputation(factionEntry, rep);
5788 // TODO: implement reputation spillover
5791 void Player::UpdateArenaFields(void)
5793 /* arena calcs go here */
5796 void Player::UpdateHonorFields()
5798 /// called when rewarding honor and at each save
5799 uint64 now = time(NULL);
5800 uint64 today = uint64(time(NULL) / DAY) * DAY;
5802 if(m_lastHonorUpdateTime < today)
5804 uint64 yesterday = today - DAY;
5806 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5808 // update yesterday's contribution
5809 if(m_lastHonorUpdateTime >= yesterday )
5811 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5813 // this is the first update today, reset today's contribution
5814 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5815 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5817 else
5819 // no honor/kills yesterday or today, reset
5820 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5821 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5825 m_lastHonorUpdateTime = now;
5828 ///Calculate the amount of honor gained based on the victim
5829 ///and the size of the group for which the honor is divided
5830 ///An exact honor value can also be given (overriding the calcs)
5831 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5833 // do not reward honor in arenas, but enable onkill spellproc
5834 if(InArena())
5836 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5837 return false;
5839 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5840 return false;
5842 return true;
5845 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5846 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5847 return false;
5849 uint64 victim_guid = 0;
5850 uint32 victim_rank = 0;
5852 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5853 UpdateHonorFields();
5855 if(honor <= 0)
5857 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5858 return false;
5860 victim_guid = uVictim->GetGUID();
5862 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5864 Player *pVictim = (Player *)uVictim;
5866 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5867 return false;
5869 float f = 1; //need for total kills (?? need more info)
5870 uint32 k_grey = 0;
5871 uint32 k_level = getLevel();
5872 uint32 v_level = pVictim->getLevel();
5875 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5876 // [0] Just name
5877 // [1..14] Alliance honor titles and player name
5878 // [15..28] Horde honor titles and player name
5879 // [29..38] Other title and player name
5880 // [39+] Nothing
5881 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5882 // Get Killer titles, CharTitlesEntry::bit_index
5883 // Ranks:
5884 // title[1..14] -> rank[5..18]
5885 // title[15..28] -> rank[5..18]
5886 // title[other] -> 0
5887 if (victim_title == 0)
5888 victim_guid = 0; // Don't show HK: <rank> message, only log.
5889 else if (victim_title < 15)
5890 victim_rank = victim_title + 4;
5891 else if (victim_title < 29)
5892 victim_rank = victim_title - 14 + 4;
5893 else
5894 victim_guid = 0; // Don't show HK: <rank> message, only log.
5897 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
5899 if(v_level<=k_grey)
5900 return false;
5902 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5904 int32 v_rank =1; //need more info
5906 honor = ((f * diff_level * (190 + v_rank*10))/6);
5907 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5909 // count the number of playerkills in one day
5910 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5911 // and those in a lifetime
5912 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5913 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
5914 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
5915 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
5917 else
5919 Creature *cVictim = (Creature *)uVictim;
5921 if (!cVictim->isRacialLeader())
5922 return false;
5924 honor = 100; // ??? need more info
5925 victim_rank = 19; // HK: Leader
5929 if (uVictim != NULL)
5931 honor *= sWorld.getRate(RATE_HONOR);
5933 if(groupsize > 1)
5934 honor /= groupsize;
5936 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5939 // honor - for show honor points in log
5940 // victim_guid - for show victim name in log
5941 // victim_rank [1..4] HK: <dishonored rank>
5942 // victim_rank [5..19] HK: <alliance\horde rank>
5943 // victim_rank [0,20+] HK: <>
5944 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5945 data << (uint32) honor;
5946 data << (uint64) victim_guid;
5947 data << (uint32) victim_rank;
5949 GetSession()->SendPacket(&data);
5951 // add honor points
5952 ModifyHonorPoints(int32(honor));
5954 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5955 return true;
5958 void Player::ModifyHonorPoints( int32 value )
5960 if(value < 0)
5962 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5963 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5964 else
5965 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5967 else
5968 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5971 void Player::ModifyArenaPoints( int32 value )
5973 if(value < 0)
5975 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5976 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5977 else
5978 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5980 else
5981 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5984 uint32 Player::GetGuildIdFromDB(uint64 guid)
5986 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
5987 if(!result)
5988 return 0;
5990 uint32 id = result->Fetch()[0].GetUInt32();
5991 delete result;
5992 return id;
5995 uint32 Player::GetRankFromDB(uint64 guid)
5997 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
5998 if( result )
6000 uint32 v = result->Fetch()[0].GetUInt32();
6001 delete result;
6002 return v;
6004 else
6005 return 0;
6008 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6010 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);
6011 if(!result)
6012 return 0;
6014 uint32 id = (*result)[0].GetUInt32();
6015 delete result;
6016 return id;
6019 uint32 Player::GetZoneIdFromDB(uint64 guid)
6021 uint32 guidLow = GUID_LOPART(guid);
6022 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6023 if (!result)
6024 return 0;
6025 Field* fields = result->Fetch();
6026 uint32 zone = fields[0].GetUInt32();
6027 delete result;
6029 if (!zone)
6031 // stored zone is zero, use generic and slow zone detection
6032 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6033 if( !result )
6034 return 0;
6035 fields = result->Fetch();
6036 uint32 map = fields[0].GetUInt32();
6037 float posx = fields[1].GetFloat();
6038 float posy = fields[2].GetFloat();
6039 float posz = fields[3].GetFloat();
6040 delete result;
6042 zone = MapManager::Instance().GetZoneId(map,posx,posy,posz);
6044 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6047 return zone;
6050 void Player::UpdateArea(uint32 newArea)
6052 // FFA_PVP flags are area and not zone id dependent
6053 // so apply them accordingly
6054 m_areaUpdateId = newArea;
6056 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6058 if(area && (area->flags & AREA_FLAG_ARENA))
6060 if(!isGameMaster())
6061 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6063 else
6065 // remove ffa flag only if not ffapvp realm
6066 // removal in sanctuaries and capitals is handled in zone update
6067 if(HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6068 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6071 UpdateAreaDependentAuras(newArea);
6074 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6076 if(m_zoneUpdateId != newZone)
6077 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6079 m_zoneUpdateId = newZone;
6080 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6082 // zone changed, so area changed as well, update it
6083 UpdateArea(newArea);
6085 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6086 if(!zone)
6087 return;
6089 if (sWorld.getConfig(CONFIG_WEATHER))
6091 Weather *wth = sWorld.FindWeather(zone->ID);
6092 if(wth)
6094 wth->SendWeatherUpdateToPlayer(this);
6096 else
6098 if(!sWorld.AddWeather(zone->ID))
6100 // send fine weather packet to remove old zone's weather
6101 Weather::SendFineWeatherUpdateToPlayer(this);
6106 // in PvP, any not controlled zone (except zone->team == 6, default case)
6107 // in PvE, only opposition team capital
6108 switch(zone->team)
6110 case AREATEAM_ALLY:
6111 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6112 break;
6113 case AREATEAM_HORDE:
6114 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6115 break;
6116 case AREATEAM_NONE:
6117 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6118 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6119 break;
6120 default: // 6 in fact
6121 pvpInfo.inHostileArea = false;
6122 break;
6125 if(pvpInfo.inHostileArea) // in hostile area
6127 if(!IsPvP() || pvpInfo.endTimer != 0)
6128 UpdatePvP(true, true);
6130 else // in friendly area
6132 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6133 pvpInfo.endTimer = time(0); // start toggle-off
6136 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6138 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6139 if(sWorld.IsFFAPvPRealm())
6140 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6142 else
6144 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6147 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6149 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6150 SetRestType(REST_TYPE_IN_CITY);
6151 InnEnter(time(0),GetMapId(),0,0,0);
6153 if(sWorld.IsFFAPvPRealm())
6154 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6156 else // anywhere else
6158 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6160 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6162 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6164 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6165 SetRestType(REST_TYPE_NO);
6167 if(sWorld.IsFFAPvPRealm())
6168 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6171 else // not in tavern (leave city then)
6173 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6174 SetRestType(REST_TYPE_NO);
6176 // Set player to FFA PVP when not in rested environment.
6177 if(sWorld.IsFFAPvPRealm())
6178 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
6183 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6184 // if player resurrected at teleport this will be applied in resurrect code
6185 if(isAlive())
6186 DestroyZoneLimitedItem( true, newZone );
6188 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6189 AutoUnequipOffhandIfNeed();
6191 // recent client version not send leave/join channel packets for built-in local channels
6192 UpdateLocalChannels( newZone );
6194 // group update
6195 if(GetGroup())
6196 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6198 UpdateZoneDependentAuras(newZone);
6201 //If players are too far way of duel flag... then player loose the duel
6202 void Player::CheckDuelDistance(time_t currTime)
6204 if(!duel)
6205 return;
6207 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6208 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6209 if(!obj)
6210 return;
6212 if(duel->outOfBound == 0)
6214 if(!IsWithinDistInMap(obj, 50))
6216 duel->outOfBound = currTime;
6218 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6219 GetSession()->SendPacket(&data);
6222 else
6224 if(IsWithinDistInMap(obj, 40))
6226 duel->outOfBound = 0;
6228 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6229 GetSession()->SendPacket(&data);
6231 else if(currTime >= (duel->outOfBound+10))
6233 DuelComplete(DUEL_FLED);
6238 void Player::DuelComplete(DuelCompleteType type)
6240 // duel not requested
6241 if(!duel)
6242 return;
6244 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6245 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6246 GetSession()->SendPacket(&data);
6247 duel->opponent->GetSession()->SendPacket(&data);
6249 if(type != DUEL_INTERUPTED)
6251 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6252 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6253 data << duel->opponent->GetName();
6254 data << GetName();
6255 SendMessageToSet(&data,true);
6258 if (type == DUEL_WON)
6260 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6261 if (duel->opponent)
6262 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6265 // cool-down duel spell
6266 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6268 data<<GetGUID();
6269 data<<uint8(0x0);
6271 data<<(uint32)7266;
6272 data<<uint32(0x0);
6273 GetSession()->SendPacket(&data);
6274 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6275 data<<duel->opponent->GetGUID();
6276 data<<uint8(0x0);
6277 data<<(uint32)7266;
6278 data<<uint32(0x0);
6279 duel->opponent->GetSession()->SendPacket(&data);*/
6281 //Remove Duel Flag object
6282 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6283 if(obj)
6284 duel->initiator->RemoveGameObject(obj,true);
6286 /* remove auras */
6287 std::vector<uint32> auras2remove;
6288 AuraMap const& vAuras = duel->opponent->GetAuras();
6289 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6291 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6292 auras2remove.push_back(i->second->GetId());
6295 for(size_t i=0; i<auras2remove.size(); ++i)
6296 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6298 auras2remove.clear();
6299 AuraMap const& auras = GetAuras();
6300 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6302 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6303 auras2remove.push_back(i->second->GetId());
6305 for(size_t i=0; i<auras2remove.size(); ++i)
6306 RemoveAurasDueToSpell(auras2remove[i]);
6308 // cleanup combo points
6309 if(GetComboTarget()==duel->opponent->GetGUID())
6310 ClearComboPoints();
6311 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6312 ClearComboPoints();
6314 if(duel->opponent->GetComboTarget()==GetGUID())
6315 duel->opponent->ClearComboPoints();
6316 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6317 duel->opponent->ClearComboPoints();
6319 //cleanups
6320 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6321 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6322 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6323 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6325 delete duel->opponent->duel;
6326 duel->opponent->duel = NULL;
6327 delete duel;
6328 duel = NULL;
6331 //---------------------------------------------------------//
6333 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6335 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6336 return;
6338 // not apply/remove mods for broken item
6339 if(item->IsBroken())
6340 return;
6342 ItemPrototype const *proto = item->GetProto();
6344 if(!proto)
6345 return;
6347 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6349 uint32 attacktype = Player::GetAttackBySlot(slot);
6350 if(attacktype < MAX_ATTACK)
6351 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6353 _ApplyItemBonuses(proto,slot,apply);
6355 if( slot==EQUIPMENT_SLOT_RANGED )
6356 _ApplyAmmoBonuses();
6358 ApplyItemEquipSpell(item,apply);
6359 ApplyEnchantment(item, apply);
6361 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6362 CorrectMetaGemEnchants(slot, apply);
6364 sLog.outDebug("_ApplyItemMods complete.");
6367 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6369 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6370 return;
6372 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : 0;
6373 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(getLevel()) : 0;
6375 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6377 uint32 statType = 0;
6378 int32 val = 0;
6379 // If set ScalingStatDistribution need get stats and values from it
6380 if (ssd && ssv)
6382 if (ssd->StatMod[i] < 0)
6383 continue;
6384 statType = ssd->StatMod[i];
6385 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6387 else
6389 if (i >= proto->StatsCount)
6390 continue;
6391 statType = proto->ItemStat[i].ItemStatType;
6392 val = proto->ItemStat[i].ItemStatValue;
6395 if(val == 0)
6396 continue;
6398 switch (statType)
6400 case ITEM_MOD_MANA:
6401 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6402 break;
6403 case ITEM_MOD_HEALTH: // modify HP
6404 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6405 break;
6406 case ITEM_MOD_AGILITY: // modify agility
6407 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6408 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6409 break;
6410 case ITEM_MOD_STRENGTH: //modify strength
6411 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6412 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6413 break;
6414 case ITEM_MOD_INTELLECT: //modify intellect
6415 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6416 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6417 break;
6418 case ITEM_MOD_SPIRIT: //modify spirit
6419 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6420 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6421 break;
6422 case ITEM_MOD_STAMINA: //modify stamina
6423 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6424 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6425 break;
6426 case ITEM_MOD_DEFENSE_SKILL_RATING:
6427 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6428 break;
6429 case ITEM_MOD_DODGE_RATING:
6430 ApplyRatingMod(CR_DODGE, int32(val), apply);
6431 break;
6432 case ITEM_MOD_PARRY_RATING:
6433 ApplyRatingMod(CR_PARRY, int32(val), apply);
6434 break;
6435 case ITEM_MOD_BLOCK_RATING:
6436 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6437 break;
6438 case ITEM_MOD_HIT_MELEE_RATING:
6439 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6440 break;
6441 case ITEM_MOD_HIT_RANGED_RATING:
6442 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6443 break;
6444 case ITEM_MOD_HIT_SPELL_RATING:
6445 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6446 break;
6447 case ITEM_MOD_CRIT_MELEE_RATING:
6448 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6449 break;
6450 case ITEM_MOD_CRIT_RANGED_RATING:
6451 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6452 break;
6453 case ITEM_MOD_CRIT_SPELL_RATING:
6454 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6455 break;
6456 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6457 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6458 break;
6459 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6460 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6461 break;
6462 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6463 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6464 break;
6465 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6466 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6467 break;
6468 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6469 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6470 break;
6471 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6472 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6473 break;
6474 case ITEM_MOD_HASTE_MELEE_RATING:
6475 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6476 break;
6477 case ITEM_MOD_HASTE_RANGED_RATING:
6478 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6479 break;
6480 case ITEM_MOD_HASTE_SPELL_RATING:
6481 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6482 break;
6483 case ITEM_MOD_HIT_RATING:
6484 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6485 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6486 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6487 break;
6488 case ITEM_MOD_CRIT_RATING:
6489 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6490 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6491 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6492 break;
6493 case ITEM_MOD_HIT_TAKEN_RATING:
6494 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6495 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6496 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6497 break;
6498 case ITEM_MOD_CRIT_TAKEN_RATING:
6499 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6500 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6501 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6502 break;
6503 case ITEM_MOD_RESILIENCE_RATING:
6504 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6505 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6506 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6507 break;
6508 case ITEM_MOD_HASTE_RATING:
6509 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6510 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6511 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6512 break;
6513 case ITEM_MOD_EXPERTISE_RATING:
6514 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6515 break;
6516 case ITEM_MOD_ATTACK_POWER:
6517 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6518 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6519 break;
6520 case ITEM_MOD_RANGED_ATTACK_POWER:
6521 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6522 break;
6523 case ITEM_MOD_FERAL_ATTACK_POWER:
6524 ApplyFeralAPBonus(int32(val), apply);
6525 break;
6526 case ITEM_MOD_SPELL_HEALING_DONE:
6527 ApplySpellHealingBonus(int32(val), apply);
6528 break;
6529 case ITEM_MOD_SPELL_DAMAGE_DONE:
6530 ApplySpellDamageBonus(int32(val), apply);
6531 break;
6532 case ITEM_MOD_MANA_REGENERATION:
6533 ApplyManaRegenBonus(int32(val), apply);
6534 break;
6535 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6536 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6537 break;
6538 case ITEM_MOD_SPELL_POWER:
6539 ApplySpellHealingBonus(int32(val), apply);
6540 ApplySpellDamageBonus(int32(val), apply);
6541 break;
6545 // If set ScalingStatValue armor get it or use item armor
6546 uint32 armor = proto->Armor;
6547 if (ssv)
6549 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6550 armor = ssvarmor;
6552 // Add armor bonus from ArmorDamageModifier if > 0
6553 if (proto->ArmorDamageModifier > 0)
6554 armor+=proto->ArmorDamageModifier;
6555 if (armor)
6556 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6558 if (proto->Block)
6559 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6561 if (proto->HolyRes)
6562 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6564 if (proto->FireRes)
6565 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6567 if (proto->NatureRes)
6568 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6570 if (proto->FrostRes)
6571 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6573 if (proto->ShadowRes)
6574 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6576 if (proto->ArcaneRes)
6577 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6579 WeaponAttackType attType = BASE_ATTACK;
6580 float damage = 0.0f;
6582 if( slot == EQUIPMENT_SLOT_RANGED && (
6583 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6584 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6586 attType = RANGED_ATTACK;
6588 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6590 attType = OFF_ATTACK;
6593 float minDamage = proto->Damage[0].DamageMin;
6594 float maxDamage = proto->Damage[0].DamageMax;
6595 int32 extraDPS = 0;
6596 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6597 if (ssv)
6599 if (extraDPS = ssv->getDPSMod(proto->ScalingStatValue))
6601 float average = extraDPS * proto->Delay / 1000.0f;
6602 minDamage = 0.7f * average;
6603 maxDamage = 1.3f * average;
6606 if (minDamage > 0 )
6608 damage = apply ? minDamage : BASE_MINDAMAGE;
6609 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6610 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6613 if (maxDamage > 0 )
6615 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6616 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6619 // Apply feral bonus from ScalingStatValue if set
6620 if (ssv)
6622 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6623 ApplyFeralAPBonus(feral_bonus, apply);
6625 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6626 if(getClass() == CLASS_DRUID)
6628 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6629 if (feral_bonus > 0)
6630 ApplyFeralAPBonus(feral_bonus, apply);
6633 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6634 return;
6636 if (proto->Delay)
6638 if(slot == EQUIPMENT_SLOT_RANGED)
6639 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6640 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6641 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6642 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6643 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6646 if(CanModifyStats() && (damage || proto->Delay))
6647 UpdateDamagePhysical(attType);
6650 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6652 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6653 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6654 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6656 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6657 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6658 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6660 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6661 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6662 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6665 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6667 // generic not weapon specific case processes in aura code
6668 if(aura->GetSpellProto()->EquippedItemClass == -1)
6669 return;
6671 BaseModGroup mod = BASEMOD_END;
6672 switch(attackType)
6674 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6675 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6676 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6677 default: return;
6680 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6682 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6686 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6688 // ignore spell mods for not wands
6689 Modifier const* modifier = aura->GetModifier();
6690 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6691 return;
6693 // generic not weapon specific case processes in aura code
6694 if(aura->GetSpellProto()->EquippedItemClass == -1)
6695 return;
6697 UnitMods unitMod = UNIT_MOD_END;
6698 switch(attackType)
6700 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6701 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6702 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6703 default: return;
6706 UnitModifierType unitModType = TOTAL_VALUE;
6707 switch(modifier->m_auraname)
6709 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6710 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6711 default: return;
6714 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6716 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6720 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6722 if(!item)
6723 return;
6725 ItemPrototype const *proto = item->GetProto();
6726 if(!proto)
6727 return;
6729 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6731 _Spell const& spellData = proto->Spells[i];
6733 // no spell
6734 if(!spellData.SpellId )
6735 continue;
6737 // wrong triggering type
6738 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6739 continue;
6741 // check if it is valid spell
6742 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6743 if(!spellproto)
6744 continue;
6746 ApplyEquipSpell(spellproto,item,apply,form_change);
6750 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6752 if(apply)
6754 // Cannot be used in this stance/form
6755 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
6756 return;
6758 if(form_change) // check aura active state from other form
6760 bool found = false;
6761 for (int k=0; k < 3; ++k)
6763 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6764 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6766 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6768 found = true;
6769 break;
6772 if(found)
6773 break;
6776 if(found) // and skip re-cast already active aura at form change
6777 return;
6780 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6782 CastSpell(this,spellInfo,true,item);
6784 else
6786 if(form_change) // check aura compatibility
6788 // Cannot be used in this stance/form
6789 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
6790 return; // and remove only not compatible at form change
6793 if(item)
6794 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6795 else
6796 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6800 void Player::UpdateEquipSpellsAtFormChange()
6802 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
6804 if(m_items[i] && !m_items[i]->IsBroken())
6806 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6807 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6811 // item set bonuses not dependent from item broken state
6812 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6814 ItemSetEffect* eff = ItemSetEff[setindex];
6815 if(!eff)
6816 continue;
6818 for(uint32 y=0;y<8; ++y)
6820 SpellEntry const* spellInfo = eff->spells[y];
6821 if(!spellInfo)
6822 continue;
6824 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6825 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6830 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6832 if(!item || item->IsBroken())
6833 return;
6835 ItemPrototype const *proto = item->GetProto();
6836 if(!proto)
6837 return;
6839 if (!Target || Target == this )
6840 return;
6842 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6844 _Spell const& spellData = proto->Spells[i];
6846 // no spell
6847 if(!spellData.SpellId )
6848 continue;
6850 // wrong triggering type
6851 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6852 continue;
6854 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6855 if(!spellInfo)
6857 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6858 continue;
6861 // not allow proc extra attack spell at extra attack
6862 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6863 return;
6865 float chance = spellInfo->procChance;
6867 if(spellData.SpellPPMRate)
6869 uint32 WeaponSpeed = GetAttackTime(attType);
6870 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6872 else if(chance > 100.0f)
6874 chance = GetWeaponProcChance();
6877 if (roll_chance_f(chance))
6878 CastSpell(Target, spellInfo->Id, true, item);
6881 // item combat enchantments
6882 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6884 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6885 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6886 if(!pEnchant) continue;
6887 for (int s=0;s<3;s++)
6889 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6890 continue;
6892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6893 if (!spellInfo)
6895 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6896 continue;
6899 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6900 if (roll_chance_f(chance))
6902 if(IsPositiveSpell(pEnchant->spellid[s]))
6903 CastSpell(this, pEnchant->spellid[s], true, item);
6904 else
6905 CastSpell(Target, pEnchant->spellid[s], true, item);
6911 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
6913 ItemPrototype const* proto = item->GetProto();
6914 // special learning case
6915 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
6917 uint32 learn_spell_id = proto->Spells[0].SpellId;
6918 uint32 learning_spell_id = proto->Spells[1].SpellId;
6920 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
6921 if(!spellInfo)
6923 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
6924 SendEquipError(EQUIP_ERR_NONE,item,NULL);
6925 return;
6928 Spell *spell = new Spell(this, spellInfo, false);
6929 spell->m_CastItem = item;
6930 spell->m_cast_count = cast_count; //set count of casts
6931 spell->m_currentBasePoints[0] = learning_spell_id;
6932 spell->prepare(&targets);
6933 return;
6936 // use triggered flag only for items with many spell casts and for not first cast
6937 int count = 0;
6939 // item spells casted at use
6940 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
6942 _Spell const& spellData = proto->Spells[i];
6944 // no spell
6945 if(!spellData.SpellId)
6946 continue;
6948 // wrong triggering type
6949 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
6950 continue;
6952 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6953 if(!spellInfo)
6955 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
6956 continue;
6959 Spell *spell = new Spell(this, spellInfo, (count > 0));
6960 spell->m_CastItem = item;
6961 spell->m_cast_count = cast_count; // set count of casts
6962 spell->m_glyphIndex = glyphIndex; // glyph index
6963 spell->prepare(&targets);
6965 ++count;
6968 // Item enchantments spells casted at use
6969 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6971 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6972 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6973 if(!pEnchant) continue;
6974 for (int s=0;s<3;s++)
6976 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
6977 continue;
6979 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6980 if (!spellInfo)
6982 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6983 continue;
6986 Spell *spell = new Spell(this, spellInfo, (count > 0));
6987 spell->m_CastItem = item;
6988 spell->m_cast_count = cast_count; // set count of casts
6989 spell->m_glyphIndex = glyphIndex; // glyph index
6990 spell->prepare(&targets);
6992 ++count;
6997 void Player::_RemoveAllItemMods()
6999 sLog.outDebug("_RemoveAllItemMods start.");
7001 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7003 if(m_items[i])
7005 ItemPrototype const *proto = m_items[i]->GetProto();
7006 if(!proto)
7007 continue;
7009 // item set bonuses not dependent from item broken state
7010 if(proto->ItemSet)
7011 RemoveItemsSetItem(this,proto);
7013 if(m_items[i]->IsBroken())
7014 continue;
7016 ApplyItemEquipSpell(m_items[i],false);
7017 ApplyEnchantment(m_items[i], false);
7021 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7023 if(m_items[i])
7025 if(m_items[i]->IsBroken())
7026 continue;
7027 ItemPrototype const *proto = m_items[i]->GetProto();
7028 if(!proto)
7029 continue;
7031 uint32 attacktype = Player::GetAttackBySlot(i);
7032 if(attacktype < MAX_ATTACK)
7033 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7035 _ApplyItemBonuses(proto,i, false);
7037 if( i == EQUIPMENT_SLOT_RANGED )
7038 _ApplyAmmoBonuses();
7042 sLog.outDebug("_RemoveAllItemMods complete.");
7045 void Player::_ApplyAllItemMods()
7047 sLog.outDebug("_ApplyAllItemMods start.");
7049 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7051 if(m_items[i])
7053 if(m_items[i]->IsBroken())
7054 continue;
7056 ItemPrototype const *proto = m_items[i]->GetProto();
7057 if(!proto)
7058 continue;
7060 uint32 attacktype = Player::GetAttackBySlot(i);
7061 if(attacktype < MAX_ATTACK)
7062 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7064 _ApplyItemBonuses(proto,i, true);
7066 if( i == EQUIPMENT_SLOT_RANGED )
7067 _ApplyAmmoBonuses();
7071 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7073 if(m_items[i])
7075 ItemPrototype const *proto = m_items[i]->GetProto();
7076 if(!proto)
7077 continue;
7079 // item set bonuses not dependent from item broken state
7080 if(proto->ItemSet)
7081 AddItemsSetItem(this,m_items[i]);
7083 if(m_items[i]->IsBroken())
7084 continue;
7086 ApplyItemEquipSpell(m_items[i],true);
7087 ApplyEnchantment(m_items[i], true);
7091 sLog.outDebug("_ApplyAllItemMods complete.");
7094 void Player::_ApplyAmmoBonuses()
7096 // check ammo
7097 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7098 if(!ammo_id)
7099 return;
7101 float currentAmmoDPS;
7103 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7104 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7105 currentAmmoDPS = 0.0f;
7106 else
7107 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7109 if(currentAmmoDPS == GetAmmoDPS())
7110 return;
7112 m_ammoDPS = currentAmmoDPS;
7114 if(CanModifyStats())
7115 UpdateDamagePhysical(RANGED_ATTACK);
7118 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7120 if(!ammo_proto)
7121 return false;
7123 // check ranged weapon
7124 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7125 if(!weapon || weapon->IsBroken() )
7126 return false;
7128 ItemPrototype const* weapon_proto = weapon->GetProto();
7129 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7130 return false;
7132 // check ammo ws. weapon compatibility
7133 switch(weapon_proto->SubClass)
7135 case ITEM_SUBCLASS_WEAPON_BOW:
7136 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7137 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7138 return false;
7139 break;
7140 case ITEM_SUBCLASS_WEAPON_GUN:
7141 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7142 return false;
7143 break;
7144 default:
7145 return false;
7148 return true;
7151 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7152 Called by remove insignia spell effect */
7153 void Player::RemovedInsignia(Player* looterPlr)
7155 if (!GetBattleGroundId())
7156 return;
7158 // If not released spirit, do it !
7159 if(m_deathTimer > 0)
7161 m_deathTimer = 0;
7162 BuildPlayerRepop();
7163 RepopAtGraveyard();
7166 Corpse *corpse = GetCorpse();
7167 if (!corpse)
7168 return;
7170 // We have to convert player corpse to bones, not to be able to resurrect there
7171 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7172 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7173 if (!bones)
7174 return;
7176 // Now we must make bones lootable, and send player loot
7177 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7179 // We store the level of our player in the gold field
7180 // We retrieve this information at Player::SendLoot()
7181 bones->loot.gold = getLevel();
7182 bones->lootRecipient = looterPlr;
7183 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7186 void Player::SendLootRelease( uint64 guid )
7188 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7189 data << uint64(guid) << uint8(1);
7190 SendDirectMessage( &data );
7193 void Player::SendLoot(uint64 guid, LootType loot_type)
7195 if (uint64 lguid = GetLootGUID())
7196 m_session->DoLootRelease(lguid);
7198 Loot *loot = 0;
7199 PermissionTypes permission = ALL_PERMISSION;
7201 sLog.outDebug("Player::SendLoot");
7202 if (IS_GAMEOBJECT_GUID(guid))
7204 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7205 GameObject *go = GetMap()->GetGameObject(guid);
7207 // not check distance for GO in case owned GO (fishing bobber case, for example)
7208 // And permit out of range GO with no owner in case fishing hole
7209 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7211 SendLootRelease(guid);
7212 return;
7215 loot = &go->loot;
7217 if (go->getLootState() == GO_READY)
7219 uint32 lootid = go->GetLootId();
7221 if (lootid)
7223 sLog.outDebug(" if(lootid)");
7224 loot->clear();
7225 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7228 if (loot_type == LOOT_FISHING)
7229 go->getFishLoot(loot,this);
7231 go->SetLootState(GO_ACTIVATED);
7234 else if (IS_ITEM_GUID(guid))
7236 Item *item = GetItemByGuid( guid );
7238 if (!item)
7240 SendLootRelease(guid);
7241 return;
7244 loot = &item->loot;
7246 if (!item->m_lootGenerated)
7248 item->m_lootGenerated = true;
7249 loot->clear();
7251 switch(loot_type)
7253 case LOOT_DISENCHANTING:
7254 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7255 break;
7256 case LOOT_PROSPECTING:
7257 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7258 break;
7259 case LOOT_MILLING:
7260 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7261 break;
7262 default:
7263 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7264 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7265 break;
7269 else if (IS_CORPSE_GUID(guid)) // remove insignia
7271 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7273 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7275 SendLootRelease(guid);
7276 return;
7279 loot = &bones->loot;
7281 if (!bones->lootForBody)
7283 bones->lootForBody = true;
7284 uint32 pLevel = bones->loot.gold;
7285 bones->loot.clear();
7286 // It may need a better formula
7287 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7288 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7291 if (bones->lootRecipient != this)
7292 permission = NONE_PERMISSION;
7294 else
7296 Creature *creature = GetMap()->GetCreature(guid);
7298 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7299 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7301 SendLootRelease(guid);
7302 return;
7305 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7307 SendLootRelease(guid);
7308 return;
7311 loot = &creature->loot;
7313 if (loot_type == LOOT_PICKPOCKETING)
7315 if (!creature->lootForPickPocketed)
7317 creature->lootForPickPocketed = true;
7318 loot->clear();
7320 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7321 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7323 // Generate extra money for pick pocket loot
7324 const uint32 a = urand(0, creature->getLevel()/2);
7325 const uint32 b = urand(0, getLevel()/2);
7326 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7329 else
7331 // the player whose group may loot the corpse
7332 Player *recipient = creature->GetLootRecipient();
7333 if (!recipient)
7335 creature->SetLootRecipient(this);
7336 recipient = this;
7339 if (creature->lootForPickPocketed)
7341 creature->lootForPickPocketed = false;
7342 loot->clear();
7345 if (!creature->lootForBody)
7347 creature->lootForBody = true;
7348 loot->clear();
7350 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7351 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7353 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7355 if (Group* group = recipient->GetGroup())
7357 group->UpdateLooterGuid(creature,true);
7359 switch (group->GetLootMethod())
7361 case GROUP_LOOT:
7362 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7363 group->GroupLoot(recipient->GetGUID(), loot, creature);
7364 break;
7365 case NEED_BEFORE_GREED:
7366 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7367 break;
7368 case MASTER_LOOT:
7369 group->MasterLoot(recipient->GetGUID(), loot, creature);
7370 break;
7371 default:
7372 break;
7377 // possible only if creature->lootForBody && loot->empty() at spell cast check
7378 if (loot_type == LOOT_SKINNING)
7380 loot->clear();
7381 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7383 // set group rights only for loot_type != LOOT_SKINNING
7384 else
7386 if(Group* group = GetGroup())
7388 if (group == recipient->GetGroup())
7390 if (group->GetLootMethod() == FREE_FOR_ALL)
7391 permission = ALL_PERMISSION;
7392 else if (group->GetLooterGuid() == GetGUID())
7394 if (group->GetLootMethod() == MASTER_LOOT)
7395 permission = MASTER_PERMISSION;
7396 else
7397 permission = ALL_PERMISSION;
7399 else
7400 permission = GROUP_PERMISSION;
7402 else
7403 permission = NONE_PERMISSION;
7405 else if (recipient == this)
7406 permission = ALL_PERMISSION;
7407 else
7408 permission = NONE_PERMISSION;
7413 SetLootGUID(guid);
7415 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7416 switch(loot_type)
7418 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7419 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7420 default: break;
7423 // need know merged fishing/corpse loot type for achievements
7424 loot->loot_type = loot_type;
7426 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7428 data << uint64(guid);
7429 data << uint8(loot_type);
7430 data << LootView(*loot, this, permission);
7432 SendDirectMessage(&data);
7434 // add 'this' player as one of the players that are looting 'loot'
7435 if (permission != NONE_PERMISSION)
7436 loot->AddLooter(GetGUID());
7438 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7439 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7442 void Player::SendNotifyLootMoneyRemoved()
7444 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7445 GetSession()->SendPacket( &data );
7448 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7450 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7451 data << uint8(lootSlot);
7452 GetSession()->SendPacket( &data );
7455 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7457 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7458 data << Field;
7459 data << Value;
7460 GetSession()->SendPacket(&data);
7463 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7465 // data depends on zoneid/mapid...
7466 BattleGround* bg = GetBattleGround();
7467 uint16 NumberOfFields = 0;
7468 uint32 mapid = GetMapId();
7470 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7472 // may be exist better way to do this...
7473 switch(zoneid)
7475 case 0:
7476 case 1:
7477 case 4:
7478 case 8:
7479 case 10:
7480 case 11:
7481 case 12:
7482 case 36:
7483 case 38:
7484 case 40:
7485 case 41:
7486 case 51:
7487 case 267:
7488 case 1519:
7489 case 1537:
7490 case 2257:
7491 case 2918:
7492 NumberOfFields = 8;
7493 break;
7494 case 139:
7495 NumberOfFields = 41;
7496 break;
7497 case 1377:
7498 NumberOfFields = 15;
7499 break;
7500 case 2597:
7501 NumberOfFields = 83;
7502 break;
7503 case 3277:
7504 NumberOfFields = 16;
7505 break;
7506 case 3358:
7507 case 3820:
7508 NumberOfFields = 40;
7509 break;
7510 case 3483:
7511 NumberOfFields = 27;
7512 break;
7513 case 3518:
7514 NumberOfFields = 39;
7515 break;
7516 case 3519:
7517 NumberOfFields = 38;
7518 break;
7519 case 3521:
7520 NumberOfFields = 37;
7521 break;
7522 case 3698:
7523 case 3702:
7524 case 3968:
7525 NumberOfFields = 11;
7526 break;
7527 case 3703:
7528 NumberOfFields = 11;
7529 break;
7530 default:
7531 NumberOfFields = 12;
7532 break;
7535 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7536 data << uint32(mapid); // mapid
7537 data << uint32(zoneid); // zone id
7538 data << uint32(areaid); // area id, new 2.1.0
7539 data << uint16(NumberOfFields); // count of uint64 blocks
7540 data << uint32(0x8d8) << uint32(0x0); // 1
7541 data << uint32(0x8d7) << uint32(0x0); // 2
7542 data << uint32(0x8d6) << uint32(0x0); // 3
7543 data << uint32(0x8d5) << uint32(0x0); // 4
7544 data << uint32(0x8d4) << uint32(0x0); // 5
7545 data << uint32(0x8d3) << uint32(0x0); // 6
7546 // 7 1 - Arena season in progress, 0 - end of season
7547 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7548 // 8 Arena season id
7549 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7550 if(mapid == 530) // Outland
7552 data << uint32(0x9bf) << uint32(0x0); // 7
7553 data << uint32(0x9bd) << uint32(0xF); // 8
7554 data << uint32(0x9bb) << uint32(0xF); // 9
7556 switch(zoneid)
7558 case 1:
7559 case 11:
7560 case 12:
7561 case 38:
7562 case 40:
7563 case 51:
7564 case 1519:
7565 case 1537:
7566 case 2257:
7567 break;
7568 case 2597: // AV
7569 data << uint32(0x7ae) << uint32(0x1); // 7
7570 data << uint32(0x532) << uint32(0x1); // 8
7571 data << uint32(0x531) << uint32(0x0); // 9
7572 data << uint32(0x52e) << uint32(0x0); // 10
7573 data << uint32(0x571) << uint32(0x0); // 11
7574 data << uint32(0x570) << uint32(0x0); // 12
7575 data << uint32(0x567) << uint32(0x1); // 13
7576 data << uint32(0x566) << uint32(0x1); // 14
7577 data << uint32(0x550) << uint32(0x1); // 15
7578 data << uint32(0x544) << uint32(0x0); // 16
7579 data << uint32(0x536) << uint32(0x0); // 17
7580 data << uint32(0x535) << uint32(0x1); // 18
7581 data << uint32(0x518) << uint32(0x0); // 19
7582 data << uint32(0x517) << uint32(0x0); // 20
7583 data << uint32(0x574) << uint32(0x0); // 21
7584 data << uint32(0x573) << uint32(0x0); // 22
7585 data << uint32(0x572) << uint32(0x0); // 23
7586 data << uint32(0x56f) << uint32(0x0); // 24
7587 data << uint32(0x56e) << uint32(0x0); // 25
7588 data << uint32(0x56d) << uint32(0x0); // 26
7589 data << uint32(0x56c) << uint32(0x0); // 27
7590 data << uint32(0x56b) << uint32(0x0); // 28
7591 data << uint32(0x56a) << uint32(0x1); // 29
7592 data << uint32(0x569) << uint32(0x1); // 30
7593 data << uint32(0x568) << uint32(0x1); // 13
7594 data << uint32(0x565) << uint32(0x0); // 32
7595 data << uint32(0x564) << uint32(0x0); // 33
7596 data << uint32(0x563) << uint32(0x0); // 34
7597 data << uint32(0x562) << uint32(0x0); // 35
7598 data << uint32(0x561) << uint32(0x0); // 36
7599 data << uint32(0x560) << uint32(0x0); // 37
7600 data << uint32(0x55f) << uint32(0x0); // 38
7601 data << uint32(0x55e) << uint32(0x0); // 39
7602 data << uint32(0x55d) << uint32(0x0); // 40
7603 data << uint32(0x3c6) << uint32(0x4); // 41
7604 data << uint32(0x3c4) << uint32(0x6); // 42
7605 data << uint32(0x3c2) << uint32(0x4); // 43
7606 data << uint32(0x516) << uint32(0x1); // 44
7607 data << uint32(0x515) << uint32(0x0); // 45
7608 data << uint32(0x3b6) << uint32(0x6); // 46
7609 data << uint32(0x55c) << uint32(0x0); // 47
7610 data << uint32(0x55b) << uint32(0x0); // 48
7611 data << uint32(0x55a) << uint32(0x0); // 49
7612 data << uint32(0x559) << uint32(0x0); // 50
7613 data << uint32(0x558) << uint32(0x0); // 51
7614 data << uint32(0x557) << uint32(0x0); // 52
7615 data << uint32(0x556) << uint32(0x0); // 53
7616 data << uint32(0x555) << uint32(0x0); // 54
7617 data << uint32(0x554) << uint32(0x1); // 55
7618 data << uint32(0x553) << uint32(0x1); // 56
7619 data << uint32(0x552) << uint32(0x1); // 57
7620 data << uint32(0x551) << uint32(0x1); // 58
7621 data << uint32(0x54f) << uint32(0x0); // 59
7622 data << uint32(0x54e) << uint32(0x0); // 60
7623 data << uint32(0x54d) << uint32(0x1); // 61
7624 data << uint32(0x54c) << uint32(0x0); // 62
7625 data << uint32(0x54b) << uint32(0x0); // 63
7626 data << uint32(0x545) << uint32(0x0); // 64
7627 data << uint32(0x543) << uint32(0x1); // 65
7628 data << uint32(0x542) << uint32(0x0); // 66
7629 data << uint32(0x540) << uint32(0x0); // 67
7630 data << uint32(0x53f) << uint32(0x0); // 68
7631 data << uint32(0x53e) << uint32(0x0); // 69
7632 data << uint32(0x53d) << uint32(0x0); // 70
7633 data << uint32(0x53c) << uint32(0x0); // 71
7634 data << uint32(0x53b) << uint32(0x0); // 72
7635 data << uint32(0x53a) << uint32(0x1); // 73
7636 data << uint32(0x539) << uint32(0x0); // 74
7637 data << uint32(0x538) << uint32(0x0); // 75
7638 data << uint32(0x537) << uint32(0x0); // 76
7639 data << uint32(0x534) << uint32(0x0); // 77
7640 data << uint32(0x533) << uint32(0x0); // 78
7641 data << uint32(0x530) << uint32(0x0); // 79
7642 data << uint32(0x52f) << uint32(0x0); // 80
7643 data << uint32(0x52d) << uint32(0x1); // 81
7644 break;
7645 case 3277: // WS
7646 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7647 bg->FillInitialWorldStates(data);
7648 else
7650 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7651 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7652 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7653 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7654 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7655 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7656 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7657 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7659 break;
7660 case 3358: // AB
7661 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7662 bg->FillInitialWorldStates(data);
7663 else
7665 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7666 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7667 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7668 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7669 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7670 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7671 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7672 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7673 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7674 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7675 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7676 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7677 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7678 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7679 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7680 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7681 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7682 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7683 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7684 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7685 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7686 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7687 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7688 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7689 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7690 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7691 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7692 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7693 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7694 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7695 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7696 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7698 break;
7699 case 3820: // EY
7700 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7701 bg->FillInitialWorldStates(data);
7702 else
7704 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7705 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7706 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7707 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7708 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7709 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7710 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7711 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7712 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7713 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7714 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7715 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7716 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7717 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7718 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7719 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7720 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7721 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7722 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7723 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7724 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7725 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7726 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7727 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7728 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7729 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7730 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7731 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7732 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7733 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7734 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7735 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7736 // and some more ... unknown
7738 break;
7739 case 3483: // Hellfire Peninsula
7740 data << uint32(0x9ba) << uint32(0x1); // 10
7741 data << uint32(0x9b9) << uint32(0x1); // 11
7742 data << uint32(0x9b5) << uint32(0x0); // 12
7743 data << uint32(0x9b4) << uint32(0x1); // 13
7744 data << uint32(0x9b3) << uint32(0x0); // 14
7745 data << uint32(0x9b2) << uint32(0x0); // 15
7746 data << uint32(0x9b1) << uint32(0x1); // 16
7747 data << uint32(0x9b0) << uint32(0x0); // 17
7748 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7749 data << uint32(0x9ac) << uint32(0x0); // 19
7750 data << uint32(0x9a8) << uint32(0x0); // 20
7751 data << uint32(0x9a7) << uint32(0x0); // 21
7752 data << uint32(0x9a6) << uint32(0x1); // 22
7753 break;
7754 case 3519: // Terokkar Forest
7755 data << uint32(0xa41) << uint32(0x0); // 10
7756 data << uint32(0xa40) << uint32(0x14); // 11
7757 data << uint32(0xa3f) << uint32(0x0); // 12
7758 data << uint32(0xa3e) << uint32(0x0); // 13
7759 data << uint32(0xa3d) << uint32(0x5); // 14
7760 data << uint32(0xa3c) << uint32(0x0); // 15
7761 data << uint32(0xa87) << uint32(0x0); // 16
7762 data << uint32(0xa86) << uint32(0x0); // 17
7763 data << uint32(0xa85) << uint32(0x0); // 18
7764 data << uint32(0xa84) << uint32(0x0); // 19
7765 data << uint32(0xa83) << uint32(0x0); // 20
7766 data << uint32(0xa82) << uint32(0x0); // 21
7767 data << uint32(0xa81) << uint32(0x0); // 22
7768 data << uint32(0xa80) << uint32(0x0); // 23
7769 data << uint32(0xa7e) << uint32(0x0); // 24
7770 data << uint32(0xa7d) << uint32(0x0); // 25
7771 data << uint32(0xa7c) << uint32(0x0); // 26
7772 data << uint32(0xa7b) << uint32(0x0); // 27
7773 data << uint32(0xa7a) << uint32(0x0); // 28
7774 data << uint32(0xa79) << uint32(0x0); // 29
7775 data << uint32(0x9d0) << uint32(0x5); // 30
7776 data << uint32(0x9ce) << uint32(0x0); // 31
7777 data << uint32(0x9cd) << uint32(0x0); // 32
7778 data << uint32(0x9cc) << uint32(0x0); // 33
7779 data << uint32(0xa88) << uint32(0x0); // 34
7780 data << uint32(0xad0) << uint32(0x0); // 35
7781 data << uint32(0xacf) << uint32(0x1); // 36
7782 break;
7783 case 3521: // Zangarmarsh
7784 data << uint32(0x9e1) << uint32(0x0); // 10
7785 data << uint32(0x9e0) << uint32(0x0); // 11
7786 data << uint32(0x9df) << uint32(0x0); // 12
7787 data << uint32(0xa5d) << uint32(0x1); // 13
7788 data << uint32(0xa5c) << uint32(0x0); // 14
7789 data << uint32(0xa5b) << uint32(0x1); // 15
7790 data << uint32(0xa5a) << uint32(0x0); // 16
7791 data << uint32(0xa59) << uint32(0x1); // 17
7792 data << uint32(0xa58) << uint32(0x0); // 18
7793 data << uint32(0xa57) << uint32(0x0); // 19
7794 data << uint32(0xa56) << uint32(0x0); // 20
7795 data << uint32(0xa55) << uint32(0x1); // 21
7796 data << uint32(0xa54) << uint32(0x0); // 22
7797 data << uint32(0x9e7) << uint32(0x0); // 23
7798 data << uint32(0x9e6) << uint32(0x0); // 24
7799 data << uint32(0x9e5) << uint32(0x0); // 25
7800 data << uint32(0xa00) << uint32(0x0); // 26
7801 data << uint32(0x9ff) << uint32(0x1); // 27
7802 data << uint32(0x9fe) << uint32(0x0); // 28
7803 data << uint32(0x9fd) << uint32(0x0); // 29
7804 data << uint32(0x9fc) << uint32(0x1); // 30
7805 data << uint32(0x9fb) << uint32(0x0); // 31
7806 data << uint32(0xa62) << uint32(0x0); // 32
7807 data << uint32(0xa61) << uint32(0x1); // 33
7808 data << uint32(0xa60) << uint32(0x1); // 34
7809 data << uint32(0xa5f) << uint32(0x0); // 35
7810 break;
7811 case 3698: // Nagrand Arena
7812 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
7813 bg->FillInitialWorldStates(data);
7814 else
7816 data << uint32(0xa0f) << uint32(0x0); // 7
7817 data << uint32(0xa10) << uint32(0x0); // 8
7818 data << uint32(0xa11) << uint32(0x0); // 9 show
7820 break;
7821 case 3702: // Blade's Edge Arena
7822 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
7823 bg->FillInitialWorldStates(data);
7824 else
7826 data << uint32(0x9f0) << uint32(0x0); // 7 gold
7827 data << uint32(0x9f1) << uint32(0x0); // 8 green
7828 data << uint32(0x9f3) << uint32(0x0); // 9 show
7830 break;
7831 case 3968: // Ruins of Lordaeron
7832 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
7833 bg->FillInitialWorldStates(data);
7834 else
7836 data << uint32(0xbb8) << uint32(0x0); // 7 gold
7837 data << uint32(0xbb9) << uint32(0x0); // 8 green
7838 data << uint32(0xbba) << uint32(0x0); // 9 show
7840 break;
7841 case 3703: // Shattrath City
7842 break;
7843 default:
7844 data << uint32(0x914) << uint32(0x0); // 7
7845 data << uint32(0x913) << uint32(0x0); // 8
7846 data << uint32(0x912) << uint32(0x0); // 9
7847 data << uint32(0x915) << uint32(0x0); // 10
7848 break;
7850 GetSession()->SendPacket(&data);
7853 uint32 Player::GetXPRestBonus(uint32 xp)
7855 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7857 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7858 rested_bonus = xp;
7860 SetRestBonus( GetRestBonus() - rested_bonus);
7862 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7863 return rested_bonus;
7866 void Player::SetBindPoint(uint64 guid)
7868 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7869 data << uint64(guid);
7870 GetSession()->SendPacket( &data );
7873 void Player::SendTalentWipeConfirm(uint64 guid)
7875 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7876 data << uint64(guid);
7877 data << uint32(resetTalentsCost());
7878 GetSession()->SendPacket( &data );
7881 void Player::SendPetSkillWipeConfirm()
7883 Pet* pet = GetPet();
7884 if(!pet)
7885 return;
7886 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7887 data << pet->GetGUID();
7888 data << uint32(pet->resetTalentsCost());
7889 GetSession()->SendPacket( &data );
7892 /*********************************************************/
7893 /*** STORAGE SYSTEM ***/
7894 /*********************************************************/
7896 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7898 assert(i < 3);
7899 if(i < 2 && item)
7901 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7902 return;
7903 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7904 if(charges == 0)
7905 return;
7906 if(charges > 1)
7907 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7908 else if(charges <= 1)
7910 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7911 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7916 void Player::SetSheath( SheathState sheathed )
7918 switch (sheathed)
7920 case SHEATH_STATE_UNARMED: // no prepared weapon
7921 SetVirtualItemSlot(0,NULL);
7922 SetVirtualItemSlot(1,NULL);
7923 SetVirtualItemSlot(2,NULL);
7924 break;
7925 case SHEATH_STATE_MELEE: // prepared melee weapon
7927 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7928 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7929 SetVirtualItemSlot(2,NULL);
7930 }; break;
7931 case SHEATH_STATE_RANGED: // prepared ranged weapon
7932 SetVirtualItemSlot(0,NULL);
7933 SetVirtualItemSlot(1,NULL);
7934 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7935 break;
7936 default:
7937 SetVirtualItemSlot(0,NULL);
7938 SetVirtualItemSlot(1,NULL);
7939 SetVirtualItemSlot(2,NULL);
7940 break;
7942 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
7945 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7947 uint8 pClass = getClass();
7949 uint8 slots[4];
7950 slots[0] = NULL_SLOT;
7951 slots[1] = NULL_SLOT;
7952 slots[2] = NULL_SLOT;
7953 slots[3] = NULL_SLOT;
7954 switch( proto->InventoryType )
7956 case INVTYPE_HEAD:
7957 slots[0] = EQUIPMENT_SLOT_HEAD;
7958 break;
7959 case INVTYPE_NECK:
7960 slots[0] = EQUIPMENT_SLOT_NECK;
7961 break;
7962 case INVTYPE_SHOULDERS:
7963 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7964 break;
7965 case INVTYPE_BODY:
7966 slots[0] = EQUIPMENT_SLOT_BODY;
7967 break;
7968 case INVTYPE_CHEST:
7969 slots[0] = EQUIPMENT_SLOT_CHEST;
7970 break;
7971 case INVTYPE_ROBE:
7972 slots[0] = EQUIPMENT_SLOT_CHEST;
7973 break;
7974 case INVTYPE_WAIST:
7975 slots[0] = EQUIPMENT_SLOT_WAIST;
7976 break;
7977 case INVTYPE_LEGS:
7978 slots[0] = EQUIPMENT_SLOT_LEGS;
7979 break;
7980 case INVTYPE_FEET:
7981 slots[0] = EQUIPMENT_SLOT_FEET;
7982 break;
7983 case INVTYPE_WRISTS:
7984 slots[0] = EQUIPMENT_SLOT_WRISTS;
7985 break;
7986 case INVTYPE_HANDS:
7987 slots[0] = EQUIPMENT_SLOT_HANDS;
7988 break;
7989 case INVTYPE_FINGER:
7990 slots[0] = EQUIPMENT_SLOT_FINGER1;
7991 slots[1] = EQUIPMENT_SLOT_FINGER2;
7992 break;
7993 case INVTYPE_TRINKET:
7994 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7995 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7996 break;
7997 case INVTYPE_CLOAK:
7998 slots[0] = EQUIPMENT_SLOT_BACK;
7999 break;
8000 case INVTYPE_WEAPON:
8002 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8004 // suggest offhand slot only if know dual wielding
8005 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8006 if(CanDualWield())
8007 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8008 break;
8010 case INVTYPE_SHIELD:
8011 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8012 break;
8013 case INVTYPE_RANGED:
8014 slots[0] = EQUIPMENT_SLOT_RANGED;
8015 break;
8016 case INVTYPE_2HWEAPON:
8017 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8018 if (CanDualWield() && CanTitanGrip())
8019 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8020 break;
8021 case INVTYPE_TABARD:
8022 slots[0] = EQUIPMENT_SLOT_TABARD;
8023 break;
8024 case INVTYPE_WEAPONMAINHAND:
8025 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8026 break;
8027 case INVTYPE_WEAPONOFFHAND:
8028 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8029 break;
8030 case INVTYPE_HOLDABLE:
8031 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8032 break;
8033 case INVTYPE_THROWN:
8034 slots[0] = EQUIPMENT_SLOT_RANGED;
8035 break;
8036 case INVTYPE_RANGEDRIGHT:
8037 slots[0] = EQUIPMENT_SLOT_RANGED;
8038 break;
8039 case INVTYPE_BAG:
8040 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8041 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8042 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8043 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8044 break;
8045 case INVTYPE_RELIC:
8047 switch(proto->SubClass)
8049 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8050 if (pClass == CLASS_PALADIN)
8051 slots[0] = EQUIPMENT_SLOT_RANGED;
8052 break;
8053 case ITEM_SUBCLASS_ARMOR_IDOL:
8054 if (pClass == CLASS_DRUID)
8055 slots[0] = EQUIPMENT_SLOT_RANGED;
8056 break;
8057 case ITEM_SUBCLASS_ARMOR_TOTEM:
8058 if (pClass == CLASS_SHAMAN)
8059 slots[0] = EQUIPMENT_SLOT_RANGED;
8060 break;
8061 case ITEM_SUBCLASS_ARMOR_MISC:
8062 if (pClass == CLASS_WARLOCK)
8063 slots[0] = EQUIPMENT_SLOT_RANGED;
8064 break;
8065 case ITEM_SUBCLASS_ARMOR_SIGIL:
8066 if (pClass == CLASS_DEATH_KNIGHT)
8067 slots[0] = EQUIPMENT_SLOT_RANGED;
8068 break;
8070 break;
8072 default :
8073 return NULL_SLOT;
8076 if( slot != NULL_SLOT )
8078 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8080 for (int i = 0; i < 4; ++i)
8082 if ( slots[i] == slot )
8083 return slot;
8087 else
8089 // search free slot at first
8090 for (int i = 0; i < 4; ++i)
8092 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8094 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8095 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8096 return slots[i];
8100 // if not found free and can swap return first appropriate from used
8101 for (int i = 0; i < 4; ++i)
8103 if ( slots[i] != NULL_SLOT && swap )
8104 return slots[i];
8108 // no free position
8109 return NULL_SLOT;
8112 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8114 Item *pItem;
8115 uint32 tempcount = 0;
8117 uint8 res = EQUIP_ERR_OK;
8119 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8121 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8122 if( pItem && pItem->GetEntry() == item )
8124 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8125 if(ires==EQUIP_ERR_OK)
8127 tempcount += pItem->GetCount();
8128 if( tempcount >= count )
8129 return EQUIP_ERR_OK;
8131 else
8132 res = ires;
8135 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8137 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8138 if( pItem && pItem->GetEntry() == item )
8140 tempcount += pItem->GetCount();
8141 if( tempcount >= count )
8142 return EQUIP_ERR_OK;
8145 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8147 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8148 if( pItem && pItem->GetEntry() == item )
8150 tempcount += pItem->GetCount();
8151 if( tempcount >= count )
8152 return EQUIP_ERR_OK;
8155 Bag *pBag;
8156 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8158 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8159 if( pBag )
8161 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8163 pItem = GetItemByPos( i, j );
8164 if( pItem && pItem->GetEntry() == item )
8166 tempcount += pItem->GetCount();
8167 if( tempcount >= count )
8168 return EQUIP_ERR_OK;
8174 // not found req. item count and have unequippable items
8175 return res;
8178 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8180 uint32 count = 0;
8181 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8183 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8184 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8185 count += pItem->GetCount();
8187 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8189 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8190 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8191 count += pItem->GetCount();
8193 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8195 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8196 if( pBag )
8197 count += pBag->GetItemCount(item,skipItem);
8200 if(skipItem && skipItem->GetProto()->GemProperties)
8202 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8204 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8205 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8206 count += pItem->GetGemCountWithID(item);
8210 if(inBankAlso)
8212 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8214 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8215 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8216 count += pItem->GetCount();
8218 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8220 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8221 if( pBag )
8222 count += pBag->GetItemCount(item,skipItem);
8225 if(skipItem && skipItem->GetProto()->GemProperties)
8227 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8229 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8230 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8231 count += pItem->GetGemCountWithID(item);
8236 return count;
8239 Item* Player::GetItemByGuid( uint64 guid ) const
8241 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8243 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8244 if( pItem && pItem->GetGUID() == guid )
8245 return pItem;
8247 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8249 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8250 if( pItem && pItem->GetGUID() == guid )
8251 return pItem;
8254 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8256 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8257 if( pBag )
8259 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8261 Item* pItem = pBag->GetItemByPos( j );
8262 if( pItem && pItem->GetGUID() == guid )
8263 return pItem;
8267 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8269 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8270 if( pBag )
8272 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8274 Item* pItem = pBag->GetItemByPos( j );
8275 if( pItem && pItem->GetGUID() == guid )
8276 return pItem;
8281 return NULL;
8284 Item* Player::GetItemByPos( uint16 pos ) const
8286 uint8 bag = pos >> 8;
8287 uint8 slot = pos & 255;
8288 return GetItemByPos( bag, slot );
8291 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8293 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8294 return m_items[slot];
8295 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8296 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8298 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8299 if ( pBag )
8300 return pBag->GetItemByPos(slot);
8302 return NULL;
8305 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8307 uint16 slot;
8308 switch (attackType)
8310 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8311 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8312 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8313 default: return NULL;
8316 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8317 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8318 return NULL;
8320 if(!useable)
8321 return item;
8323 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8324 return NULL;
8326 return item;
8329 Item* Player::GetShield(bool useable) const
8331 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8332 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8333 return NULL;
8335 if(!useable)
8336 return item;
8338 if( item->IsBroken())
8339 return NULL;
8341 return item;
8344 uint32 Player::GetAttackBySlot( uint8 slot )
8346 switch(slot)
8348 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8349 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8350 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8351 default: return MAX_ATTACK;
8355 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8357 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8358 return true;
8359 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8360 return true;
8361 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8362 return true;
8363 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8364 return true;
8365 return false;
8368 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8370 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8371 return true;
8372 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8373 return true;
8374 return false;
8377 bool Player::IsBankPos( uint8 bag, uint8 slot )
8379 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8380 return true;
8381 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8382 return true;
8383 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8384 return true;
8385 return false;
8388 bool Player::IsBagPos( uint16 pos )
8390 uint8 bag = pos >> 8;
8391 uint8 slot = pos & 255;
8392 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8393 return true;
8394 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8395 return true;
8396 return false;
8399 bool Player::IsValidPos( uint8 bag, uint8 slot )
8401 // post selected
8402 if(bag == NULL_BAG)
8403 return true;
8405 if (bag == INVENTORY_SLOT_BAG_0)
8407 // any post selected
8408 if (slot == NULL_SLOT)
8409 return true;
8411 // equipment
8412 if (slot < EQUIPMENT_SLOT_END)
8413 return true;
8415 // bag equip slots
8416 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8417 return true;
8419 // backpack slots
8420 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8421 return true;
8423 // keyring slots
8424 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8425 return true;
8427 // bank main slots
8428 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8429 return true;
8431 // bank bag slots
8432 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8433 return true;
8435 return false;
8438 // bag content slots
8439 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8441 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8442 if(!pBag)
8443 return false;
8445 // any post selected
8446 if (slot == NULL_SLOT)
8447 return true;
8449 return slot < pBag->GetBagSize();
8452 // bank bag content slots
8453 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8455 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8456 if(!pBag)
8457 return false;
8459 // any post selected
8460 if (slot == NULL_SLOT)
8461 return true;
8463 return slot < pBag->GetBagSize();
8466 // where this?
8467 return false;
8471 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8473 uint32 tempcount = 0;
8474 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8476 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8477 if( pItem && pItem->GetEntry() == item )
8479 tempcount += pItem->GetCount();
8480 if( tempcount >= count )
8481 return true;
8484 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8486 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8487 if( pItem && pItem->GetEntry() == item )
8489 tempcount += pItem->GetCount();
8490 if( tempcount >= count )
8491 return true;
8494 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8496 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8498 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8500 Item* pItem = GetItemByPos( i, j );
8501 if( pItem && pItem->GetEntry() == item )
8503 tempcount += pItem->GetCount();
8504 if( tempcount >= count )
8505 return true;
8511 if(inBankAlso)
8513 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8515 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8516 if( pItem && pItem->GetEntry() == item )
8518 tempcount += pItem->GetCount();
8519 if( tempcount >= count )
8520 return true;
8523 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8525 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8527 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8529 Item* pItem = GetItemByPos( i, j );
8530 if( pItem && pItem->GetEntry() == item )
8532 tempcount += pItem->GetCount();
8533 if( tempcount >= count )
8534 return true;
8541 return false;
8544 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8546 uint32 tempcount = 0;
8547 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8549 if(i==int(except_slot))
8550 continue;
8552 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8553 if( pItem && pItem->GetEntry() == item)
8555 tempcount += pItem->GetCount();
8556 if( tempcount >= count )
8557 return true;
8561 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8562 if (pProto && pProto->GemProperties)
8564 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8566 if(i==int(except_slot))
8567 continue;
8569 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8570 if( pItem && pItem->GetProto()->Socket[0].Color)
8572 tempcount += pItem->GetGemCountWithID(item);
8573 if( tempcount >= count )
8574 return true;
8579 return false;
8582 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8584 uint32 tempcount = 0;
8585 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8587 if(i==int(except_slot))
8588 continue;
8590 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8591 if (!pItem)
8592 continue;
8594 ItemPrototype const *pProto = pItem->GetProto();
8595 if (!pProto)
8596 continue;
8598 if (pProto->ItemLimitCategory == limitCategory)
8600 tempcount += pItem->GetCount();
8601 if( tempcount >= count )
8602 return true;
8605 if( pProto->Socket[0].Color)
8607 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8608 if( tempcount >= count )
8609 return true;
8613 return false;
8616 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8618 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8619 if( !pProto )
8621 if(no_space_count)
8622 *no_space_count = count;
8623 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8626 // no maximum
8627 if(pProto->MaxCount <= 0)
8628 return EQUIP_ERR_OK;
8630 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8632 if (curcount + count > uint32(pProto->MaxCount))
8634 if(no_space_count)
8635 *no_space_count = count +curcount - pProto->MaxCount;
8636 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8639 return EQUIP_ERR_OK;
8642 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8644 Item *pItem;
8645 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8647 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8648 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8649 return true;
8651 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8653 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8654 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8655 return true;
8657 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8659 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8661 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8663 pItem = GetItemByPos( i, j );
8664 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8665 return true;
8669 return false;
8672 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8674 Item* pItem2 = GetItemByPos( bag, slot );
8676 // ignore move item (this slot will be empty at move)
8677 if(pItem2==pSrcItem)
8678 pItem2 = NULL;
8680 uint32 need_space;
8682 // empty specific slot - check item fit to slot
8683 if( !pItem2 || swap )
8685 if( bag == INVENTORY_SLOT_BAG_0 )
8687 // keyring case
8688 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8689 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8691 // vanitypet case (not use, vanity pets stored as spells)
8692 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END)
8693 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8695 // currencytoken case
8696 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8697 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8699 // guestbag case (not use)
8700 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END)
8701 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8703 // prevent cheating
8704 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8705 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8707 else
8709 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8710 if( !pBag )
8711 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8713 ItemPrototype const* pBagProto = pBag->GetProto();
8714 if( !pBagProto )
8715 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8717 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8718 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8721 // non empty stack with space
8722 need_space = pProto->GetMaxStackSize();
8724 // non empty slot, check item type
8725 else
8727 // check item type
8728 if(pItem2->GetEntry() != pProto->ItemId)
8729 return EQUIP_ERR_ITEM_CANT_STACK;
8731 // check free space
8732 if(pItem2->GetCount() >= pProto->GetMaxStackSize())
8733 return EQUIP_ERR_ITEM_CANT_STACK;
8735 // free stack space or infinity
8736 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8739 if(need_space > count)
8740 need_space = count;
8742 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8743 if(!newPosition.isContainedIn(dest))
8745 dest.push_back(newPosition);
8746 count -= need_space;
8748 return EQUIP_ERR_OK;
8751 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
8753 // skip specific bag already processed in first called _CanStoreItem_InBag
8754 if(bag==skip_bag)
8755 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8757 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8758 if( !pBag )
8759 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8761 ItemPrototype const* pBagProto = pBag->GetProto();
8762 if( !pBagProto )
8763 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8765 // specialized bag mode or non-specilized
8766 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8767 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8769 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8770 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8772 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8774 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8775 if(j==skip_slot)
8776 continue;
8778 Item* pItem2 = GetItemByPos( bag, j );
8780 // ignore move item (this slot will be empty at move)
8781 if(pItem2==pSrcItem)
8782 pItem2 = NULL;
8784 // if merge skip empty, if !merge skip non-empty
8785 if((pItem2!=NULL)!=merge)
8786 continue;
8788 if( pItem2 )
8790 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8792 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8793 if(need_space > count)
8794 need_space = count;
8796 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8797 if(!newPosition.isContainedIn(dest))
8799 dest.push_back(newPosition);
8800 count -= need_space;
8802 if(count==0)
8803 return EQUIP_ERR_OK;
8807 else
8809 uint32 need_space = pProto->GetMaxStackSize();
8810 if(need_space > count)
8811 need_space = count;
8813 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8814 if(!newPosition.isContainedIn(dest))
8816 dest.push_back(newPosition);
8817 count -= need_space;
8819 if(count==0)
8820 return EQUIP_ERR_OK;
8824 return EQUIP_ERR_OK;
8827 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
8829 for(uint32 j = slot_begin; j < slot_end; ++j)
8831 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8832 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8833 continue;
8835 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8837 // ignore move item (this slot will be empty at move)
8838 if(pItem2==pSrcItem)
8839 pItem2 = NULL;
8841 // if merge skip empty, if !merge skip non-empty
8842 if((pItem2!=NULL)!=merge)
8843 continue;
8845 if( pItem2 )
8847 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->GetMaxStackSize())
8849 uint32 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
8850 if(need_space > count)
8851 need_space = count;
8852 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8853 if(!newPosition.isContainedIn(dest))
8855 dest.push_back(newPosition);
8856 count -= need_space;
8858 if(count==0)
8859 return EQUIP_ERR_OK;
8863 else
8865 uint32 need_space = pProto->GetMaxStackSize();
8866 if(need_space > count)
8867 need_space = count;
8869 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8870 if(!newPosition.isContainedIn(dest))
8872 dest.push_back(newPosition);
8873 count -= need_space;
8875 if(count==0)
8876 return EQUIP_ERR_OK;
8880 return EQUIP_ERR_OK;
8883 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8885 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8887 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8888 if( !pProto )
8890 if(no_space_count)
8891 *no_space_count = count;
8892 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8895 if(pItem && pItem->IsBindedNotWith(this))
8897 if(no_space_count)
8898 *no_space_count = count;
8899 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8902 // check count of items (skip for auto move for same player from bank)
8903 uint32 no_similar_count = 0; // can't store this amount similar items
8904 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8905 if(res!=EQUIP_ERR_OK)
8907 if(count==no_similar_count)
8909 if(no_space_count)
8910 *no_space_count = no_similar_count;
8911 return res;
8913 count -= no_similar_count;
8916 // in specific slot
8917 if( bag != NULL_BAG && slot != NULL_SLOT )
8919 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8920 if(res!=EQUIP_ERR_OK)
8922 if(no_space_count)
8923 *no_space_count = count + no_similar_count;
8924 return res;
8927 if(count==0)
8929 if(no_similar_count==0)
8930 return EQUIP_ERR_OK;
8932 if(no_space_count)
8933 *no_space_count = count + no_similar_count;
8934 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8938 // not specific slot or have space for partly store only in specific slot
8940 // in specific bag
8941 if( bag != NULL_BAG )
8943 // search stack in bag for merge to
8944 if( pProto->Stackable != 1 )
8946 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8948 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8949 if(res!=EQUIP_ERR_OK)
8951 if(no_space_count)
8952 *no_space_count = count + no_similar_count;
8953 return res;
8956 if(count==0)
8958 if(no_similar_count==0)
8959 return EQUIP_ERR_OK;
8961 if(no_space_count)
8962 *no_space_count = count + no_similar_count;
8963 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8966 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8967 if(res!=EQUIP_ERR_OK)
8969 if(no_space_count)
8970 *no_space_count = count + no_similar_count;
8971 return res;
8974 if(count==0)
8976 if(no_similar_count==0)
8977 return EQUIP_ERR_OK;
8979 if(no_space_count)
8980 *no_space_count = count + no_similar_count;
8981 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8984 else // equipped bag
8986 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8987 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8988 if(res!=EQUIP_ERR_OK)
8989 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8991 if(res!=EQUIP_ERR_OK)
8993 if(no_space_count)
8994 *no_space_count = count + no_similar_count;
8995 return res;
8998 if(count==0)
9000 if(no_similar_count==0)
9001 return EQUIP_ERR_OK;
9003 if(no_space_count)
9004 *no_space_count = count + no_similar_count;
9005 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9010 // search free slot in bag for place to
9011 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
9013 // search free slot - keyring case
9014 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9016 uint32 keyringSize = GetMaxKeyringSize();
9017 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9018 if(res!=EQUIP_ERR_OK)
9020 if(no_space_count)
9021 *no_space_count = count + no_similar_count;
9022 return res;
9025 if(count==0)
9027 if(no_similar_count==0)
9028 return EQUIP_ERR_OK;
9030 if(no_space_count)
9031 *no_space_count = count + no_similar_count;
9032 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9035 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9036 if(res!=EQUIP_ERR_OK)
9038 if(no_space_count)
9039 *no_space_count = count + no_similar_count;
9040 return res;
9043 if(count==0)
9045 if(no_similar_count==0)
9046 return EQUIP_ERR_OK;
9048 if(no_space_count)
9049 *no_space_count = count + no_similar_count;
9050 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9053 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9055 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9056 if(res!=EQUIP_ERR_OK)
9058 if(no_space_count)
9059 *no_space_count = count + no_similar_count;
9060 return res;
9063 if(count==0)
9065 if(no_similar_count==0)
9066 return EQUIP_ERR_OK;
9068 if(no_space_count)
9069 *no_space_count = count + no_similar_count;
9070 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9074 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9075 if(res!=EQUIP_ERR_OK)
9077 if(no_space_count)
9078 *no_space_count = count + no_similar_count;
9079 return res;
9082 if(count==0)
9084 if(no_similar_count==0)
9085 return EQUIP_ERR_OK;
9087 if(no_space_count)
9088 *no_space_count = count + no_similar_count;
9089 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9092 else // equipped bag
9094 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9095 if(res!=EQUIP_ERR_OK)
9096 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9098 if(res!=EQUIP_ERR_OK)
9100 if(no_space_count)
9101 *no_space_count = count + no_similar_count;
9102 return res;
9105 if(count==0)
9107 if(no_similar_count==0)
9108 return EQUIP_ERR_OK;
9110 if(no_space_count)
9111 *no_space_count = count + no_similar_count;
9112 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9117 // not specific bag or have space for partly store only in specific bag
9119 // search stack for merge to
9120 if( pProto->Stackable != 1 )
9122 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9123 if(res!=EQUIP_ERR_OK)
9125 if(no_space_count)
9126 *no_space_count = count + no_similar_count;
9127 return res;
9130 if(count==0)
9132 if(no_similar_count==0)
9133 return EQUIP_ERR_OK;
9135 if(no_space_count)
9136 *no_space_count = count + no_similar_count;
9137 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9140 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9141 if(res!=EQUIP_ERR_OK)
9143 if(no_space_count)
9144 *no_space_count = count + no_similar_count;
9145 return res;
9148 if(count==0)
9150 if(no_similar_count==0)
9151 return EQUIP_ERR_OK;
9153 if(no_space_count)
9154 *no_space_count = count + no_similar_count;
9155 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9158 if( pProto->BagFamily )
9160 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9162 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9163 if(res!=EQUIP_ERR_OK)
9164 continue;
9166 if(count==0)
9168 if(no_similar_count==0)
9169 return EQUIP_ERR_OK;
9171 if(no_space_count)
9172 *no_space_count = count + no_similar_count;
9173 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9178 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9180 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9181 if(res!=EQUIP_ERR_OK)
9182 continue;
9184 if(count==0)
9186 if(no_similar_count==0)
9187 return EQUIP_ERR_OK;
9189 if(no_space_count)
9190 *no_space_count = count + no_similar_count;
9191 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9196 // search free slot - special bag case
9197 if( pProto->BagFamily )
9199 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9201 uint32 keyringSize = GetMaxKeyringSize();
9202 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9203 if(res!=EQUIP_ERR_OK)
9205 if(no_space_count)
9206 *no_space_count = count + no_similar_count;
9207 return res;
9210 if(count==0)
9212 if(no_similar_count==0)
9213 return EQUIP_ERR_OK;
9215 if(no_space_count)
9216 *no_space_count = count + no_similar_count;
9217 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9220 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9222 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9223 if(res!=EQUIP_ERR_OK)
9225 if(no_space_count)
9226 *no_space_count = count + no_similar_count;
9227 return res;
9230 if(count==0)
9232 if(no_similar_count==0)
9233 return EQUIP_ERR_OK;
9235 if(no_space_count)
9236 *no_space_count = count + no_similar_count;
9237 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9241 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9243 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9244 if(res!=EQUIP_ERR_OK)
9245 continue;
9247 if(count==0)
9249 if(no_similar_count==0)
9250 return EQUIP_ERR_OK;
9252 if(no_space_count)
9253 *no_space_count = count + no_similar_count;
9254 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9259 // search free slot
9260 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9261 if(res!=EQUIP_ERR_OK)
9263 if(no_space_count)
9264 *no_space_count = count + no_similar_count;
9265 return res;
9268 if(count==0)
9270 if(no_similar_count==0)
9271 return EQUIP_ERR_OK;
9273 if(no_space_count)
9274 *no_space_count = count + no_similar_count;
9275 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9278 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9280 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9281 if(res!=EQUIP_ERR_OK)
9282 continue;
9284 if(count==0)
9286 if(no_similar_count==0)
9287 return EQUIP_ERR_OK;
9289 if(no_space_count)
9290 *no_space_count = count + no_similar_count;
9291 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9295 if(no_space_count)
9296 *no_space_count = count + no_similar_count;
9298 return EQUIP_ERR_INVENTORY_FULL;
9301 //////////////////////////////////////////////////////////////////////////
9302 uint8 Player::CanStoreItems( Item **pItems,int count) const
9304 Item *pItem2;
9306 // fill space table
9307 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9308 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9309 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9310 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9312 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9313 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9314 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9315 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9317 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9319 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9321 if (pItem2 && !pItem2->IsInTrade())
9323 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9327 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9329 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9331 if (pItem2 && !pItem2->IsInTrade())
9333 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9337 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9339 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9341 if (pItem2 && !pItem2->IsInTrade())
9343 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9347 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9349 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9351 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9353 pItem2 = GetItemByPos( i, j );
9354 if (pItem2 && !pItem2->IsInTrade())
9356 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9362 // check free space for all items
9363 for (int k = 0; k < count; ++k)
9365 Item *pItem = pItems[k];
9367 // no item
9368 if (!pItem) continue;
9370 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9371 ItemPrototype const *pProto = pItem->GetProto();
9373 // strange item
9374 if( !pProto )
9375 return EQUIP_ERR_ITEM_NOT_FOUND;
9377 // item it 'bind'
9378 if(pItem->IsBindedNotWith(this))
9379 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9381 Bag *pBag;
9382 ItemPrototype const *pBagProto;
9384 // item is 'one item only'
9385 uint8 res = CanTakeMoreSimilarItems(pItem);
9386 if(res != EQUIP_ERR_OK)
9387 return res;
9389 // search stack for merge to
9390 if( pProto->Stackable != 1 )
9392 bool b_found = false;
9394 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9396 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9397 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9399 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9400 b_found = true;
9401 break;
9404 if (b_found) continue;
9406 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9408 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9409 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9411 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9412 b_found = true;
9413 break;
9416 if (b_found) continue;
9418 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9420 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9421 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9423 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9424 b_found = true;
9425 break;
9428 if (b_found) continue;
9430 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9432 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9433 if( pBag )
9435 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9437 pItem2 = GetItemByPos( t, j );
9438 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9440 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9441 b_found = true;
9442 break;
9447 if (b_found) continue;
9450 // special bag case
9451 if( pProto->BagFamily )
9453 bool b_found = false;
9454 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9456 uint32 keyringSize = GetMaxKeyringSize();
9457 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9459 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9461 inv_keys[t-KEYRING_SLOT_START] = 1;
9462 b_found = true;
9463 break;
9468 if (b_found) continue;
9470 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9472 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9474 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9476 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9477 b_found = true;
9478 break;
9483 if (b_found) continue;
9485 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9487 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9488 if( pBag )
9490 pBagProto = pBag->GetProto();
9492 // not plain container check
9493 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9494 ItemCanGoIntoBag(pProto,pBagProto) )
9496 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9498 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9500 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9501 b_found = true;
9502 break;
9508 if (b_found) continue;
9511 // search free slot
9512 bool b_found = false;
9513 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9515 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9517 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9518 b_found = true;
9519 break;
9522 if (b_found) continue;
9524 // search free slot in bags
9525 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9527 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9528 if( pBag )
9530 pBagProto = pBag->GetProto();
9532 // special bag already checked
9533 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9534 continue;
9536 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9538 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9540 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9541 b_found = true;
9542 break;
9548 // no free slot found?
9549 if (!b_found)
9550 return EQUIP_ERR_INVENTORY_FULL;
9553 return EQUIP_ERR_OK;
9556 //////////////////////////////////////////////////////////////////////////
9557 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9559 dest = 0;
9560 Item *pItem = Item::CreateItem( item, 1, this );
9561 if( pItem )
9563 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9564 delete pItem;
9565 return result;
9568 return EQUIP_ERR_ITEM_NOT_FOUND;
9571 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9573 dest = 0;
9574 if( pItem )
9576 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9577 ItemPrototype const *pProto = pItem->GetProto();
9578 if( pProto )
9580 if(pItem->IsBindedNotWith(this))
9581 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9583 // check count of items (skip for auto move for same player from bank)
9584 uint8 res = CanTakeMoreSimilarItems(pItem);
9585 if(res != EQUIP_ERR_OK)
9586 return res;
9588 // check this only in game
9589 if(not_loading)
9591 // May be here should be more stronger checks; STUNNED checked
9592 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9593 if (hasUnitState(UNIT_STAT_STUNNED))
9594 return EQUIP_ERR_YOU_ARE_STUNNED;
9596 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9597 // - combat
9598 // - in-progress arenas
9599 if( !pProto->CanChangeEquipStateInCombat() )
9601 if( isInCombat() )
9602 return EQUIP_ERR_NOT_IN_COMBAT;
9604 if(BattleGround* bg = GetBattleGround())
9605 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9606 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9609 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9610 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9612 if(IsNonMeleeSpellCasted(false))
9613 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9616 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9617 if (ssd && ssd->MaxLevel < getLevel())
9618 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9620 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9621 if (eslot == NULL_SLOT)
9622 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9624 uint8 msg = CanUseItem(pItem , not_loading);
9625 if (msg != EQUIP_ERR_OK)
9626 return msg;
9627 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9628 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9630 // if swap ignore item (equipped also)
9631 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9632 return res2;
9634 // check unique-equipped special item classes
9635 if (pProto->Class == ITEM_CLASS_QUIVER)
9637 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9639 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9641 if (pBag != pItem)
9643 if (ItemPrototype const* pBagProto = pBag->GetProto())
9645 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9646 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9647 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9648 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9655 uint32 type = pProto->InventoryType;
9657 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9659 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9661 if (!CanDualWield())
9662 return EQUIP_ERR_CANT_DUAL_WIELD;
9664 else if (type == INVTYPE_2HWEAPON)
9666 if (!CanDualWield() || !CanTitanGrip())
9667 return EQUIP_ERR_CANT_DUAL_WIELD;
9670 if (IsTwoHandUsed())
9671 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9674 // equip two-hand weapon case (with possible unequip 2 items)
9675 if (type == INVTYPE_2HWEAPON)
9677 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9679 if (!CanTitanGrip())
9680 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9682 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9683 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9685 if (!CanTitanGrip())
9687 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9688 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9689 ItemPosCountVec off_dest;
9690 if (offItem && (!not_loading ||
9691 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9692 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
9693 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9696 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9697 return EQUIP_ERR_OK;
9701 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9704 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9706 // Applied only to equipped items and bank bags
9707 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9708 return EQUIP_ERR_OK;
9710 Item* pItem = GetItemByPos(pos);
9712 // Applied only to existed equipped item
9713 if( !pItem )
9714 return EQUIP_ERR_OK;
9716 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9718 ItemPrototype const *pProto = pItem->GetProto();
9719 if( !pProto )
9720 return EQUIP_ERR_ITEM_NOT_FOUND;
9722 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9723 // - combat
9724 // - in-progress arenas
9725 if( !pProto->CanChangeEquipStateInCombat() )
9727 if( isInCombat() )
9728 return EQUIP_ERR_NOT_IN_COMBAT;
9730 if(BattleGround* bg = GetBattleGround())
9731 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9732 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9735 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9736 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9738 return EQUIP_ERR_OK;
9741 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9743 if (!pItem)
9744 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9746 uint32 count = pItem->GetCount();
9748 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9749 ItemPrototype const *pProto = pItem->GetProto();
9750 if (!pProto)
9751 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9753 if (pItem->IsBindedNotWith(this))
9754 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9756 // check count of items (skip for auto move for same player from bank)
9757 uint8 res = CanTakeMoreSimilarItems(pItem);
9758 if (res != EQUIP_ERR_OK)
9759 return res;
9761 // in specific slot
9762 if (bag != NULL_BAG && slot != NULL_SLOT)
9764 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
9766 if (!pItem->IsBag())
9767 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9769 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
9770 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9772 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
9773 return cantuse;
9776 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9777 if (res!=EQUIP_ERR_OK)
9778 return res;
9780 if (count==0)
9781 return EQUIP_ERR_OK;
9784 // not specific slot or have space for partly store only in specific slot
9786 // in specific bag
9787 if( bag != NULL_BAG )
9789 if( pProto->InventoryType == INVTYPE_BAG )
9791 Bag *pBag = (Bag*)pItem;
9792 if( pBag && !pBag->IsEmpty() )
9793 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9796 // search stack in bag for merge to
9797 if( pProto->Stackable != 1 )
9799 if( bag == INVENTORY_SLOT_BAG_0 )
9801 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9802 if(res!=EQUIP_ERR_OK)
9803 return res;
9805 if(count==0)
9806 return EQUIP_ERR_OK;
9808 else
9810 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9811 if(res!=EQUIP_ERR_OK)
9812 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9814 if(res!=EQUIP_ERR_OK)
9815 return res;
9817 if(count==0)
9818 return EQUIP_ERR_OK;
9822 // search free slot in bag
9823 if( bag == INVENTORY_SLOT_BAG_0 )
9825 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9826 if(res!=EQUIP_ERR_OK)
9827 return res;
9829 if(count==0)
9830 return EQUIP_ERR_OK;
9832 else
9834 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
9835 if(res != EQUIP_ERR_OK)
9836 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
9838 if(res != EQUIP_ERR_OK)
9839 return res;
9841 if(count == 0)
9842 return EQUIP_ERR_OK;
9846 // not specific bag or have space for partly store only in specific bag
9848 // search stack for merge to
9849 if( pProto->Stackable != 1 )
9851 // in slots
9852 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9853 if(res != EQUIP_ERR_OK)
9854 return res;
9856 if(count == 0)
9857 return EQUIP_ERR_OK;
9859 // in special bags
9860 if( pProto->BagFamily )
9862 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9864 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9865 if(res!=EQUIP_ERR_OK)
9866 continue;
9868 if(count==0)
9869 return EQUIP_ERR_OK;
9873 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9875 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9876 if(res!=EQUIP_ERR_OK)
9877 continue;
9879 if(count==0)
9880 return EQUIP_ERR_OK;
9884 // search free place in special bag
9885 if( pProto->BagFamily )
9887 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9889 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9890 if(res!=EQUIP_ERR_OK)
9891 continue;
9893 if(count==0)
9894 return EQUIP_ERR_OK;
9898 // search free space
9899 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9900 if(res!=EQUIP_ERR_OK)
9901 return res;
9903 if(count==0)
9904 return EQUIP_ERR_OK;
9906 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
9908 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9909 if(res!=EQUIP_ERR_OK)
9910 continue;
9912 if(count==0)
9913 return EQUIP_ERR_OK;
9915 return EQUIP_ERR_BANK_FULL;
9918 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9920 if (pItem)
9922 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9924 if (!isAlive() && not_loading)
9925 return EQUIP_ERR_YOU_ARE_DEAD;
9927 //if (isStunned())
9928 // return EQUIP_ERR_YOU_ARE_STUNNED;
9930 ItemPrototype const *pProto = pItem->GetProto();
9931 if (pProto)
9933 if (pItem->IsBindedNotWith(this))
9934 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9936 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
9937 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9939 if (pItem->GetSkill() != 0)
9941 if (GetSkillValue( pItem->GetSkill() ) == 0)
9942 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9945 if (pProto->RequiredSkill != 0)
9947 if (GetSkillValue( pProto->RequiredSkill ) == 0)
9948 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9950 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
9951 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9954 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
9955 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9957 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
9958 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9960 if (getLevel() < pProto->RequiredLevel)
9961 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9963 return EQUIP_ERR_OK;
9966 return EQUIP_ERR_ITEM_NOT_FOUND;
9969 bool Player::CanUseItem( ItemPrototype const *pProto )
9971 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9973 if( pProto )
9975 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9976 return false;
9977 if( pProto->RequiredSkill != 0 )
9979 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9980 return false;
9981 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9982 return false;
9984 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9985 return false;
9986 if( getLevel() < pProto->RequiredLevel )
9987 return false;
9988 return true;
9990 return false;
9993 uint8 Player::CanUseAmmo( uint32 item ) const
9995 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9996 if( !isAlive() )
9997 return EQUIP_ERR_YOU_ARE_DEAD;
9998 //if( isStunned() )
9999 // return EQUIP_ERR_YOU_ARE_STUNNED;
10000 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10001 if( pProto )
10003 if( pProto->InventoryType!= INVTYPE_AMMO )
10004 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10005 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10006 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10007 if( pProto->RequiredSkill != 0 )
10009 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10010 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10011 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10012 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10014 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10015 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10016 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10017 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10019 if( getLevel() < pProto->RequiredLevel )
10020 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10022 // Requires No Ammo
10023 if(GetDummyAura(46699))
10024 return EQUIP_ERR_BAG_FULL6;
10026 return EQUIP_ERR_OK;
10028 return EQUIP_ERR_ITEM_NOT_FOUND;
10031 void Player::SetAmmo( uint32 item )
10033 if(!item)
10034 return;
10036 // already set
10037 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10038 return;
10040 // check ammo
10041 if(item)
10043 uint8 msg = CanUseAmmo( item );
10044 if( msg != EQUIP_ERR_OK )
10046 SendEquipError( msg, NULL, NULL );
10047 return;
10051 SetUInt32Value(PLAYER_AMMO_ID, item);
10053 _ApplyAmmoBonuses();
10056 void Player::RemoveAmmo()
10058 SetUInt32Value(PLAYER_AMMO_ID, 0);
10060 m_ammoDPS = 0.0f;
10062 if(CanModifyStats())
10063 UpdateDamagePhysical(RANGED_ATTACK);
10066 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10067 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10069 uint32 count = 0;
10070 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10071 count += itr->count;
10073 Item *pItem = Item::CreateItem( item, count, this );
10074 if( pItem )
10076 ItemAddedQuestCheck( item, count );
10077 if(randomPropertyId)
10078 pItem->SetItemRandomProperties(randomPropertyId);
10079 pItem = StoreItem( dest, pItem, update );
10081 return pItem;
10084 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10086 if( !pItem )
10087 return NULL;
10089 Item* lastItem = pItem;
10090 uint32 entry = pItem->GetEntry();
10091 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10093 uint16 pos = itr->pos;
10094 uint32 count = itr->count;
10096 ++itr;
10098 if(itr == dest.end())
10100 lastItem = _StoreItem(pos,pItem,count,false,update);
10101 break;
10104 lastItem = _StoreItem(pos,pItem,count,true,update);
10106 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10107 return lastItem;
10110 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10111 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10113 if( !pItem )
10114 return NULL;
10116 uint8 bag = pos >> 8;
10117 uint8 slot = pos & 255;
10119 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10121 Item *pItem2 = GetItemByPos( bag, slot );
10123 if (!pItem2)
10125 if (clone)
10126 pItem = pItem->CloneItem(count, this);
10127 else
10128 pItem->SetCount(count);
10130 if (!pItem)
10131 return NULL;
10133 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10134 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10135 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10136 pItem->SetBinding( true );
10138 if (bag == INVENTORY_SLOT_BAG_0)
10140 m_items[slot] = pItem;
10141 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10142 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10143 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10145 pItem->SetSlot( slot );
10146 pItem->SetContainer( NULL );
10148 // need update known currency
10149 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10150 UpdateKnownCurrencies(pItem->GetEntry(), true);
10152 if (IsInWorld() && update)
10154 pItem->AddToWorld();
10155 pItem->SendUpdateToPlayer( this );
10158 pItem->SetState(ITEM_CHANGED, this);
10160 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10162 pBag->StoreItem( slot, pItem, update );
10163 if( IsInWorld() && update )
10165 pItem->AddToWorld();
10166 pItem->SendUpdateToPlayer( this );
10168 pItem->SetState(ITEM_CHANGED, this);
10169 pBag->SetState(ITEM_CHANGED, this);
10172 AddEnchantmentDurations(pItem);
10173 AddItemDurations(pItem);
10175 return pItem;
10177 else
10179 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10180 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10181 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10182 pItem2->SetBinding( true );
10184 pItem2->SetCount( pItem2->GetCount() + count );
10185 if (IsInWorld() && update)
10186 pItem2->SendUpdateToPlayer( this );
10188 if (!clone)
10190 // delete item (it not in any slot currently)
10191 if (IsInWorld() && update)
10193 pItem->RemoveFromWorld();
10194 pItem->DestroyForPlayer( this );
10197 RemoveEnchantmentDurations(pItem);
10198 RemoveItemDurations(pItem);
10200 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10201 pItem->SetState(ITEM_REMOVED, this);
10204 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10205 AddEnchantmentDurations(pItem2);
10207 pItem2->SetState(ITEM_CHANGED, this);
10209 return pItem2;
10213 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10215 if (Item *pItem = Item::CreateItem( item, 1, this ))
10217 ItemAddedQuestCheck( item, 1 );
10218 return EquipItem( pos, pItem, update );
10221 return NULL;
10224 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10227 AddEnchantmentDurations(pItem);
10228 AddItemDurations(pItem);
10230 uint8 bag = pos >> 8;
10231 uint8 slot = pos & 255;
10233 Item *pItem2 = GetItemByPos( bag, slot );
10235 if( !pItem2 )
10237 VisualizeItem( slot, pItem);
10239 if(isAlive())
10241 ItemPrototype const *pProto = pItem->GetProto();
10243 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10244 if(pProto && pProto->ItemSet)
10245 AddItemsSetItem(this, pItem);
10247 _ApplyItemMods(pItem, slot, true);
10249 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10251 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10253 if (getClass() == CLASS_ROGUE)
10254 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10256 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10258 if (!spellProto)
10259 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10260 else
10262 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10264 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10265 data << uint64(GetGUID());
10266 data << uint8(1);
10267 data << uint32(cooldownSpell);
10268 data << uint32(0);
10269 GetSession()->SendPacket(&data);
10274 if( IsInWorld() && update )
10276 pItem->AddToWorld();
10277 pItem->SendUpdateToPlayer( this );
10280 ApplyEquipCooldown(pItem);
10282 if( slot == EQUIPMENT_SLOT_MAINHAND )
10283 UpdateExpertise(BASE_ATTACK);
10284 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10285 UpdateExpertise(OFF_ATTACK);
10287 else
10289 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10290 if( IsInWorld() && update )
10291 pItem2->SendUpdateToPlayer( this );
10293 // delete item (it not in any slot currently)
10294 //pItem->DeleteFromDB();
10295 if( IsInWorld() && update )
10297 pItem->RemoveFromWorld();
10298 pItem->DestroyForPlayer( this );
10301 RemoveEnchantmentDurations(pItem);
10302 RemoveItemDurations(pItem);
10304 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10305 pItem->SetState(ITEM_REMOVED, this);
10306 pItem2->SetState(ITEM_CHANGED, this);
10308 ApplyEquipCooldown(pItem2);
10310 return pItem2;
10313 // only for full equip instead adding to stack
10314 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10316 return pItem;
10319 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10321 if( pItem )
10323 AddEnchantmentDurations(pItem);
10324 AddItemDurations(pItem);
10326 uint8 slot = pos & 255;
10327 VisualizeItem( slot, pItem);
10329 if( IsInWorld() )
10331 pItem->AddToWorld();
10332 pItem->SendUpdateToPlayer( this );
10337 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10339 if(pItem)
10341 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10343 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10344 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10346 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10347 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10349 // Use SetInt16Value to prevent set high part to FFFF for negative value
10350 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10351 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10353 else
10355 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10357 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10358 SetUInt32Value(VisibleBase + 0, 0);
10360 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10361 SetUInt32Value(VisibleBase + 1 + i, 0);
10363 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10364 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10368 void Player::VisualizeItem( uint8 slot, Item *pItem)
10370 if(!pItem)
10371 return;
10373 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10374 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10375 pItem->SetBinding( true );
10377 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10379 m_items[slot] = pItem;
10380 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10381 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10382 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10383 pItem->SetSlot( slot );
10384 pItem->SetContainer( NULL );
10386 if( slot < EQUIPMENT_SLOT_END )
10387 SetVisibleItemSlot(slot, pItem);
10389 pItem->SetState(ITEM_CHANGED, this);
10392 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10394 // note: removeitem does not actually change the item
10395 // it only takes the item out of storage temporarily
10396 // note2: if removeitem is to be used for delinking
10397 // the item must be removed from the player's updatequeue
10399 Item *pItem = GetItemByPos( bag, slot );
10400 if( pItem )
10402 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10404 RemoveEnchantmentDurations(pItem);
10405 RemoveItemDurations(pItem);
10407 if( bag == INVENTORY_SLOT_BAG_0 )
10409 if ( slot < INVENTORY_SLOT_BAG_END )
10411 ItemPrototype const *pProto = pItem->GetProto();
10412 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10414 if(pProto && pProto->ItemSet)
10415 RemoveItemsSetItem(this, pProto);
10417 _ApplyItemMods(pItem, slot, false);
10419 // remove item dependent auras and casts (only weapon and armor slots)
10420 if(slot < EQUIPMENT_SLOT_END)
10422 RemoveItemDependentAurasAndCasts(pItem);
10424 // remove held enchantments, update expertise
10425 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10427 if (pItem->GetItemSuffixFactor())
10429 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10430 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10432 else
10434 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10435 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10438 UpdateExpertise(BASE_ATTACK);
10440 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10441 UpdateExpertise(OFF_ATTACK);
10444 // need update known currency
10445 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10446 UpdateKnownCurrencies(pItem->GetEntry(), false);
10448 m_items[slot] = NULL;
10449 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10451 if ( slot < EQUIPMENT_SLOT_END )
10452 SetVisibleItemSlot(slot, NULL);
10454 else
10456 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10457 if( pBag )
10458 pBag->RemoveItem(slot, update);
10460 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10461 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10462 pItem->SetSlot( NULL_SLOT );
10463 if( IsInWorld() && update )
10464 pItem->SendUpdateToPlayer( this );
10468 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10469 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10471 if(Item* it = GetItemByPos(bag,slot))
10473 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10474 RemoveItem(bag, slot, update);
10475 it->RemoveFromUpdateQueueOf(this);
10476 if(it->IsInWorld())
10478 it->RemoveFromWorld();
10479 it->DestroyForPlayer( this );
10484 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10485 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10487 // update quest counters
10488 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10490 // store item
10491 Item* pLastItem = StoreItem(dest, pItem, update);
10493 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10494 if(pLastItem == pItem)
10496 // update owner for last item (this can be original item with wrong owner
10497 if(pLastItem->GetOwnerGUID() != GetGUID())
10498 pLastItem->SetOwnerGUID(GetGUID());
10500 // if this original item then it need create record in inventory
10501 // in case trade we already have item in other player inventory
10502 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10506 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10508 Item *pItem = GetItemByPos( bag, slot );
10509 if( pItem )
10511 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10513 // start from destroy contained items (only equipped bag can have its)
10514 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10516 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10517 DestroyItem(slot, i, update);
10520 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10521 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10523 RemoveEnchantmentDurations(pItem);
10524 RemoveItemDurations(pItem);
10526 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10528 if( bag == INVENTORY_SLOT_BAG_0 )
10530 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10532 // equipment and equipped bags can have applied bonuses
10533 if ( slot < INVENTORY_SLOT_BAG_END )
10535 ItemPrototype const *pProto = pItem->GetProto();
10537 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10538 if(pProto && pProto->ItemSet)
10539 RemoveItemsSetItem(this, pProto);
10541 _ApplyItemMods(pItem, slot, false);
10544 if ( slot < EQUIPMENT_SLOT_END )
10546 // remove item dependent auras and casts (only weapon and armor slots)
10547 RemoveItemDependentAurasAndCasts(pItem);
10549 // update expertise
10550 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10551 UpdateExpertise(BASE_ATTACK);
10552 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10553 UpdateExpertise(OFF_ATTACK);
10555 // equipment visual show
10556 SetVisibleItemSlot(slot, NULL);
10558 // need update known currency
10559 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10560 UpdateKnownCurrencies(pItem->GetEntry(), false);
10562 m_items[slot] = NULL;
10564 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10565 pBag->RemoveItem(slot, update);
10567 if( IsInWorld() && update )
10569 pItem->RemoveFromWorld();
10570 pItem->DestroyForPlayer(this);
10573 //pItem->SetOwnerGUID(0);
10574 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10575 pItem->SetSlot( NULL_SLOT );
10576 pItem->SetState(ITEM_REMOVED, this);
10580 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10582 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10583 uint32 remcount = 0;
10585 // in inventory
10586 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10588 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10590 if (pItem->GetEntry() == item)
10592 if (pItem->GetCount() + remcount <= count)
10594 // all items in inventory can unequipped
10595 remcount += pItem->GetCount();
10596 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10598 if (remcount >= count)
10599 return;
10601 else
10603 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10604 pItem->SetCount( pItem->GetCount() - count + remcount );
10605 if (IsInWorld() & update)
10606 pItem->SendUpdateToPlayer( this );
10607 pItem->SetState(ITEM_CHANGED, this);
10608 return;
10614 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10616 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10618 if (pItem->GetEntry() == item)
10620 if (pItem->GetCount() + remcount <= count)
10622 // all keys can be unequipped
10623 remcount += pItem->GetCount();
10624 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10626 if (remcount >= count)
10627 return;
10629 else
10631 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10632 pItem->SetCount( pItem->GetCount() - count + remcount );
10633 if (IsInWorld() & update)
10634 pItem->SendUpdateToPlayer( this );
10635 pItem->SetState(ITEM_CHANGED, this);
10636 return;
10642 // in inventory bags
10643 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10645 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10647 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10649 if(Item* pItem = pBag->GetItemByPos(j))
10651 if (pItem->GetEntry() == item)
10653 // all items in bags can be unequipped
10654 if (pItem->GetCount() + remcount <= count)
10656 remcount += pItem->GetCount();
10657 DestroyItem( i, j, update );
10659 if (remcount >= count)
10660 return;
10662 else
10664 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10665 pItem->SetCount( pItem->GetCount() - count + remcount );
10666 if (IsInWorld() && update)
10667 pItem->SendUpdateToPlayer( this );
10668 pItem->SetState(ITEM_CHANGED, this);
10669 return;
10677 // in equipment and bag list
10678 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10680 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10682 if (pItem && pItem->GetEntry() == item)
10684 if (pItem->GetCount() + remcount <= count)
10686 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
10688 remcount += pItem->GetCount();
10689 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10691 if (remcount >= count)
10692 return;
10695 else
10697 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10698 pItem->SetCount( pItem->GetCount() - count + remcount );
10699 if (IsInWorld() & update)
10700 pItem->SendUpdateToPlayer( this );
10701 pItem->SetState(ITEM_CHANGED, this);
10702 return;
10709 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10711 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10713 // in inventory
10714 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10715 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10716 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10717 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10719 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
10720 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10721 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10722 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10724 // in inventory bags
10725 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10726 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10727 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10728 if (Item* pItem = pBag->GetItemByPos(j))
10729 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10730 DestroyItem(i, j, update);
10732 // in equipment and bag list
10733 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10734 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10735 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
10736 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10739 void Player::DestroyConjuredItems( bool update )
10741 // used when entering arena
10742 // destroys all conjured items
10743 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10745 // in inventory
10746 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10747 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10748 if (pItem->IsConjuredConsumable())
10749 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10751 // in inventory bags
10752 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
10753 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10754 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
10755 if (Item* pItem = pBag->GetItemByPos(j))
10756 if (pItem->IsConjuredConsumable())
10757 DestroyItem( i, j, update);
10759 // in equipment and bag list
10760 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
10761 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10762 if (pItem->IsConjuredConsumable())
10763 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10766 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10768 if(!pItem)
10769 return;
10771 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10773 if( pItem->GetCount() <= count )
10775 count -= pItem->GetCount();
10777 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10779 else
10781 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10782 pItem->SetCount( pItem->GetCount() - count );
10783 count = 0;
10784 if( IsInWorld() & update )
10785 pItem->SendUpdateToPlayer( this );
10786 pItem->SetState(ITEM_CHANGED, this);
10790 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10792 uint8 srcbag = src >> 8;
10793 uint8 srcslot = src & 255;
10795 uint8 dstbag = dst >> 8;
10796 uint8 dstslot = dst & 255;
10798 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10799 if( !pSrcItem )
10801 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10802 return;
10805 // not let split all items (can be only at cheating)
10806 if(pSrcItem->GetCount() == count)
10808 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10809 return;
10812 // not let split more existed items (can be only at cheating)
10813 if(pSrcItem->GetCount() < count)
10815 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10816 return;
10819 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10821 //best error message found for attempting to split while looting
10822 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10823 return;
10826 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10827 Item *pNewItem = pSrcItem->CloneItem( count, this );
10828 if( !pNewItem )
10830 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10831 return;
10834 if( IsInventoryPos( dst ) )
10836 // change item amount before check (for unique max count check)
10837 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10839 ItemPosCountVec dest;
10840 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10841 if( msg != EQUIP_ERR_OK )
10843 delete pNewItem;
10844 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10845 SendEquipError( msg, pSrcItem, NULL );
10846 return;
10849 if( IsInWorld() )
10850 pSrcItem->SendUpdateToPlayer( this );
10851 pSrcItem->SetState(ITEM_CHANGED, this);
10852 StoreItem( dest, pNewItem, true);
10854 else if( IsBankPos ( dst ) )
10856 // change item amount before check (for unique max count check)
10857 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10859 ItemPosCountVec dest;
10860 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10861 if( msg != EQUIP_ERR_OK )
10863 delete pNewItem;
10864 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10865 SendEquipError( msg, pSrcItem, NULL );
10866 return;
10869 if( IsInWorld() )
10870 pSrcItem->SendUpdateToPlayer( this );
10871 pSrcItem->SetState(ITEM_CHANGED, this);
10872 BankItem( dest, pNewItem, true);
10874 else if( IsEquipmentPos ( dst ) )
10876 // change item amount before check (for unique max count check), provide space for splitted items
10877 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10879 uint16 dest;
10880 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10881 if( msg != EQUIP_ERR_OK )
10883 delete pNewItem;
10884 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10885 SendEquipError( msg, pSrcItem, NULL );
10886 return;
10889 if( IsInWorld() )
10890 pSrcItem->SendUpdateToPlayer( this );
10891 pSrcItem->SetState(ITEM_CHANGED, this);
10892 EquipItem( dest, pNewItem, true);
10893 AutoUnequipOffhandIfNeed();
10897 void Player::SwapItem( uint16 src, uint16 dst )
10899 uint8 srcbag = src >> 8;
10900 uint8 srcslot = src & 255;
10902 uint8 dstbag = dst >> 8;
10903 uint8 dstslot = dst & 255;
10905 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10906 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10908 if( !pSrcItem )
10909 return;
10911 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10913 if(!isAlive() )
10915 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10916 return;
10919 // SRC checks
10921 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10923 //best error message found for attempting to swap while looting
10924 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10925 return;
10928 // check unequip potability for equipped items and bank bags
10929 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10931 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10932 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty());
10933 if(msg != EQUIP_ERR_OK)
10935 SendEquipError( msg, pSrcItem, pDstItem );
10936 return;
10940 // prevent put equipped/bank bag in self
10941 if( IsBagPos ( src ) && srcslot == dstbag)
10943 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10944 return;
10947 // DST checks
10949 if (pDstItem)
10951 if(pDstItem->m_lootGenerated) // prevent swap looting item
10953 //best error message found for attempting to swap while looting
10954 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10955 return;
10958 // check unequip potability for equipped items and bank bags
10959 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10961 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10962 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty());
10963 if(msg != EQUIP_ERR_OK)
10965 SendEquipError( msg, pSrcItem, pDstItem );
10966 return;
10971 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10972 // or swap empty bag with another empty or not empty bag (with items exchange)
10974 // Move case
10975 if( !pDstItem )
10977 if( IsInventoryPos( dst ) )
10979 ItemPosCountVec dest;
10980 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10981 if( msg != EQUIP_ERR_OK )
10983 SendEquipError( msg, pSrcItem, NULL );
10984 return;
10987 RemoveItem(srcbag, srcslot, true);
10988 StoreItem( dest, pSrcItem, true);
10990 else if( IsBankPos ( dst ) )
10992 ItemPosCountVec dest;
10993 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10994 if( msg != EQUIP_ERR_OK )
10996 SendEquipError( msg, pSrcItem, NULL );
10997 return;
11000 RemoveItem(srcbag, srcslot, true);
11001 BankItem( dest, pSrcItem, true);
11003 else if( IsEquipmentPos ( dst ) )
11005 uint16 dest;
11006 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11007 if( msg != EQUIP_ERR_OK )
11009 SendEquipError( msg, pSrcItem, NULL );
11010 return;
11013 RemoveItem(srcbag, srcslot, true);
11014 EquipItem(dest, pSrcItem, true);
11015 AutoUnequipOffhandIfNeed();
11018 return;
11021 // attempt merge to / fill target item
11022 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11024 uint8 msg;
11025 ItemPosCountVec sDest;
11026 uint16 eDest;
11027 if( IsInventoryPos( dst ) )
11028 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11029 else if( IsBankPos ( dst ) )
11030 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11031 else if( IsEquipmentPos ( dst ) )
11032 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11033 else
11034 return;
11036 // can be merge/fill
11037 if(msg == EQUIP_ERR_OK)
11039 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11041 RemoveItem(srcbag, srcslot, true);
11043 if( IsInventoryPos( dst ) )
11044 StoreItem( sDest, pSrcItem, true);
11045 else if( IsBankPos ( dst ) )
11046 BankItem( sDest, pSrcItem, true);
11047 else if( IsEquipmentPos ( dst ) )
11049 EquipItem( eDest, pSrcItem, true);
11050 AutoUnequipOffhandIfNeed();
11053 else
11055 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11056 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11057 pSrcItem->SetState(ITEM_CHANGED, this);
11058 pDstItem->SetState(ITEM_CHANGED, this);
11059 if( IsInWorld() )
11061 pSrcItem->SendUpdateToPlayer( this );
11062 pDstItem->SendUpdateToPlayer( this );
11065 return;
11069 // impossible merge/fill, do real swap
11070 uint8 msg;
11072 // check src->dest move possibility
11073 ItemPosCountVec sDest;
11074 uint16 eDest = 0;
11075 if( IsInventoryPos( dst ) )
11076 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11077 else if( IsBankPos( dst ) )
11078 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11079 else if( IsEquipmentPos( dst ) )
11081 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11082 if( msg == EQUIP_ERR_OK )
11083 msg = CanUnequipItem( eDest, true );
11086 if( msg != EQUIP_ERR_OK )
11088 SendEquipError( msg, pSrcItem, pDstItem );
11089 return;
11092 // check dest->src move possibility
11093 ItemPosCountVec sDest2;
11094 uint16 eDest2 = 0;
11095 if( IsInventoryPos( src ) )
11096 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11097 else if( IsBankPos( src ) )
11098 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11099 else if( IsEquipmentPos( src ) )
11101 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11102 if( msg == EQUIP_ERR_OK )
11103 msg = CanUnequipItem( eDest2, true);
11106 if( msg != EQUIP_ERR_OK )
11108 SendEquipError( msg, pDstItem, pSrcItem );
11109 return;
11112 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11113 if(pSrcItem->IsBag() && pDstItem->IsBag())
11115 Bag* emptyBag = NULL;
11116 Bag* fullBag = NULL;
11117 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11119 emptyBag = (Bag*)pSrcItem;
11120 fullBag = (Bag*)pDstItem;
11122 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11124 emptyBag = (Bag*)pDstItem;
11125 fullBag = (Bag*)pSrcItem;
11128 // bag swap (with items exchange) case
11129 if(emptyBag && fullBag)
11131 ItemPrototype const* emotyProto = emptyBag->GetProto();
11133 uint32 count = 0;
11135 for(int i=0; i < fullBag->GetBagSize(); ++i)
11137 Item *bagItem = fullBag->GetItemByPos(i);
11138 if (!bagItem)
11139 continue;
11141 ItemPrototype const* bagItemProto = bagItem->GetProto();
11142 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11144 // one from items not go to empty target bag
11145 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11146 return;
11149 ++count;
11153 if (count > emptyBag->GetBagSize())
11155 // too small targeted bag
11156 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11157 return;
11160 // Items swap
11161 count = 0; // will pos in new bag
11162 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11164 Item *bagItem = fullBag->GetItemByPos(i);
11165 if (!bagItem)
11166 continue;
11168 fullBag->RemoveItem(i, true);
11169 emptyBag->StoreItem(count, bagItem, true);
11170 bagItem->SetState(ITEM_CHANGED, this);
11172 ++count;
11177 // now do moves, remove...
11178 RemoveItem(dstbag, dstslot, false);
11179 RemoveItem(srcbag, srcslot, false);
11181 // add to dest
11182 if( IsInventoryPos( dst ) )
11183 StoreItem(sDest, pSrcItem, true);
11184 else if( IsBankPos( dst ) )
11185 BankItem(sDest, pSrcItem, true);
11186 else if( IsEquipmentPos( dst ) )
11187 EquipItem(eDest, pSrcItem, true);
11189 // add to src
11190 if( IsInventoryPos( src ) )
11191 StoreItem(sDest2, pDstItem, true);
11192 else if( IsBankPos( src ) )
11193 BankItem(sDest2, pDstItem, true);
11194 else if( IsEquipmentPos( src ) )
11195 EquipItem(eDest2, pDstItem, true);
11197 AutoUnequipOffhandIfNeed();
11200 void Player::AddItemToBuyBackSlot( Item *pItem )
11202 if( pItem )
11204 uint32 slot = m_currentBuybackSlot;
11205 // if current back slot non-empty search oldest or free
11206 if(m_items[slot])
11208 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11209 uint32 oldest_slot = BUYBACK_SLOT_START;
11211 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11213 // found empty
11214 if(!m_items[i])
11216 slot = i;
11217 break;
11220 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11222 if(oldest_time > i_time)
11224 oldest_time = i_time;
11225 oldest_slot = i;
11229 // find oldest
11230 slot = oldest_slot;
11233 RemoveItemFromBuyBackSlot( slot, true );
11234 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11236 m_items[slot] = pItem;
11237 time_t base = time(NULL);
11238 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11239 uint32 eslot = slot - BUYBACK_SLOT_START;
11241 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11242 ItemPrototype const *pProto = pItem->GetProto();
11243 if( pProto )
11244 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11245 else
11246 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11247 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11249 // move to next (for non filled list is move most optimized choice)
11250 if(m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11251 ++m_currentBuybackSlot;
11255 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11257 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11258 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11259 return m_items[slot];
11260 return NULL;
11263 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11265 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11266 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11268 Item *pItem = m_items[slot];
11269 if( pItem )
11271 pItem->RemoveFromWorld();
11272 if(del) pItem->SetState(ITEM_REMOVED, this);
11275 m_items[slot] = NULL;
11277 uint32 eslot = slot - BUYBACK_SLOT_START;
11278 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11279 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11280 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11282 // if current backslot is filled set to now free slot
11283 if(m_items[m_currentBuybackSlot])
11284 m_currentBuybackSlot = slot;
11288 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11290 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11291 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11292 data << uint8(msg);
11294 if(msg)
11296 data << uint64(pItem ? pItem->GetGUID() : 0);
11297 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11298 data << uint8(0); // not 0 there...
11300 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11302 uint32 level = 0;
11304 if(pItem)
11305 if(ItemPrototype const* proto = pItem->GetProto())
11306 level = proto->RequiredLevel;
11308 data << uint32(level); // new 2.4.0
11311 GetSession()->SendPacket(&data);
11314 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11316 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11317 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11318 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11319 data << uint32(item);
11320 if( param > 0 )
11321 data << uint32(param);
11322 data << uint8(msg);
11323 GetSession()->SendPacket(&data);
11326 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11328 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11329 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11330 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11331 data << uint64(guid);
11332 if( param > 0 )
11333 data << uint32(param);
11334 data << uint8(msg);
11335 GetSession()->SendPacket(&data);
11338 void Player::ClearTrade()
11340 tradeGold = 0;
11341 acceptTrade = false;
11342 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11343 tradeItems[i] = NULL_SLOT;
11346 void Player::TradeCancel(bool sendback)
11348 if(pTrader)
11350 // send yellow "Trade canceled" message to both traders
11351 WorldSession* ws;
11352 ws = GetSession();
11353 if(sendback)
11354 ws->SendCancelTrade();
11355 ws = pTrader->GetSession();
11356 if(!ws->PlayerLogout())
11357 ws->SendCancelTrade();
11359 // cleanup
11360 ClearTrade();
11361 pTrader->ClearTrade();
11362 // prevent loss of reference
11363 pTrader->pTrader = NULL;
11364 pTrader = NULL;
11368 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11370 if(m_itemDuration.empty())
11371 return;
11373 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11375 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11377 Item* item = *itr;
11378 ++itr; // current element can be erased in UpdateDuration
11380 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11381 item->UpdateDuration(this,time);
11385 void Player::UpdateEnchantTime(uint32 time)
11387 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11389 assert(itr->item);
11390 next = itr;
11391 if(!itr->item->GetEnchantmentId(itr->slot))
11393 next = m_enchantDuration.erase(itr);
11395 else if(itr->leftduration <= time)
11397 ApplyEnchantment(itr->item, itr->slot, false, false);
11398 itr->item->ClearEnchantment(itr->slot);
11399 next = m_enchantDuration.erase(itr);
11401 else if(itr->leftduration > time)
11403 itr->leftduration -= time;
11404 ++next;
11409 void Player::AddEnchantmentDurations(Item *item)
11411 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11413 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11414 continue;
11416 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11417 if( duration > 0 )
11418 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11422 void Player::RemoveEnchantmentDurations(Item *item)
11424 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11426 if(itr->item == item)
11428 // save duration in item
11429 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11430 itr = m_enchantDuration.erase(itr);
11432 else
11433 ++itr;
11437 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11439 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11440 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11442 next = itr;
11443 if(itr->slot == slot)
11445 if(itr->item && itr->item->GetEnchantmentId(slot))
11447 // remove from stats
11448 ApplyEnchantment(itr->item, slot, false, false);
11449 // remove visual
11450 itr->item->ClearEnchantment(slot);
11452 // remove from update list
11453 next = m_enchantDuration.erase(itr);
11455 else
11456 ++next;
11459 // remove enchants from inventory items
11460 // NOTE: no need to remove these from stats, since these aren't equipped
11461 // in inventory
11462 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11464 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11465 if( pItem && pItem->GetEnchantmentId(slot) )
11466 pItem->ClearEnchantment(slot);
11469 // in inventory bags
11470 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11472 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11473 if( pBag )
11475 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11477 Item* pItem = pBag->GetItemByPos(j);
11478 if( pItem && pItem->GetEnchantmentId(slot) )
11479 pItem->ClearEnchantment(slot);
11485 // duration == 0 will remove item enchant
11486 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11488 if(!item)
11489 return;
11491 if(slot >= MAX_ENCHANTMENT_SLOT)
11492 return;
11494 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11496 if(itr->item == item && itr->slot == slot)
11498 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11499 m_enchantDuration.erase(itr);
11500 break;
11503 if(item && duration > 0 )
11505 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11506 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11510 void Player::ApplyEnchantment(Item *item,bool apply)
11512 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11513 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11516 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11518 if(!item)
11519 return;
11521 if(!item->IsEquipped())
11522 return;
11524 if(slot >= MAX_ENCHANTMENT_SLOT)
11525 return;
11527 uint32 enchant_id = item->GetEnchantmentId(slot);
11528 if(!enchant_id)
11529 return;
11531 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11532 if(!pEnchant)
11533 return;
11535 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11536 return;
11538 if (!item->IsBroken())
11540 for (int s = 0; s < 3; ++s)
11542 uint32 enchant_display_type = pEnchant->type[s];
11543 uint32 enchant_amount = pEnchant->amount[s];
11544 uint32 enchant_spell_id = pEnchant->spellid[s];
11546 switch(enchant_display_type)
11548 case ITEM_ENCHANTMENT_TYPE_NONE:
11549 break;
11550 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11551 // processed in Player::CastItemCombatSpell
11552 break;
11553 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11554 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11555 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11556 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11557 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11558 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11559 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11560 break;
11561 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11562 if(enchant_spell_id)
11564 if(apply)
11566 int32 basepoints = 0;
11567 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11568 if (item->GetItemRandomPropertyId())
11570 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11571 if (item_rand)
11573 // Search enchant_amount
11574 for (int k = 0; k < 3; ++k)
11576 if(item_rand->enchant_id[k] == enchant_id)
11578 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11579 break;
11584 // Cast custom spell vs all equal basepoints getted from enchant_amount
11585 if (basepoints)
11586 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11587 else
11588 CastSpell(this, enchant_spell_id, true, item);
11590 else
11591 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11593 break;
11594 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11595 if (!enchant_amount)
11597 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11598 if(item_rand)
11600 for (int k = 0; k < 3; ++k)
11602 if(item_rand->enchant_id[k] == enchant_id)
11604 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11605 break;
11611 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11612 break;
11613 case ITEM_ENCHANTMENT_TYPE_STAT:
11615 if (!enchant_amount)
11617 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11618 if(item_rand_suffix)
11620 for (int k = 0; k < 3; ++k)
11622 if(item_rand_suffix->enchant_id[k] == enchant_id)
11624 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11625 break;
11631 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11632 switch (enchant_spell_id)
11634 case ITEM_MOD_MANA:
11635 sLog.outDebug("+ %u MANA",enchant_amount);
11636 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11637 break;
11638 case ITEM_MOD_HEALTH:
11639 sLog.outDebug("+ %u HEALTH",enchant_amount);
11640 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11641 break;
11642 case ITEM_MOD_AGILITY:
11643 sLog.outDebug("+ %u AGILITY",enchant_amount);
11644 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11645 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11646 break;
11647 case ITEM_MOD_STRENGTH:
11648 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11649 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11650 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11651 break;
11652 case ITEM_MOD_INTELLECT:
11653 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11654 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11655 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11656 break;
11657 case ITEM_MOD_SPIRIT:
11658 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11659 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11660 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11661 break;
11662 case ITEM_MOD_STAMINA:
11663 sLog.outDebug("+ %u STAMINA",enchant_amount);
11664 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11665 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11666 break;
11667 case ITEM_MOD_DEFENSE_SKILL_RATING:
11668 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11669 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11670 break;
11671 case ITEM_MOD_DODGE_RATING:
11672 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11673 sLog.outDebug("+ %u DODGE", enchant_amount);
11674 break;
11675 case ITEM_MOD_PARRY_RATING:
11676 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11677 sLog.outDebug("+ %u PARRY", enchant_amount);
11678 break;
11679 case ITEM_MOD_BLOCK_RATING:
11680 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11681 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11682 break;
11683 case ITEM_MOD_HIT_MELEE_RATING:
11684 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11685 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11686 break;
11687 case ITEM_MOD_HIT_RANGED_RATING:
11688 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11689 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11690 break;
11691 case ITEM_MOD_HIT_SPELL_RATING:
11692 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11693 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11694 break;
11695 case ITEM_MOD_CRIT_MELEE_RATING:
11696 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11697 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11698 break;
11699 case ITEM_MOD_CRIT_RANGED_RATING:
11700 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11701 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11702 break;
11703 case ITEM_MOD_CRIT_SPELL_RATING:
11704 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11705 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11706 break;
11707 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11708 // in Enchantments
11709 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11710 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11711 // break;
11712 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11713 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11714 // break;
11715 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11716 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11717 // break;
11718 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11719 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11720 // break;
11721 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11722 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11723 // break;
11724 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11725 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11726 // break;
11727 // case ITEM_MOD_HASTE_MELEE_RATING:
11728 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11729 // break;
11730 // case ITEM_MOD_HASTE_RANGED_RATING:
11731 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11732 // break;
11733 case ITEM_MOD_HASTE_SPELL_RATING:
11734 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11735 break;
11736 case ITEM_MOD_HIT_RATING:
11737 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11738 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11739 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11740 sLog.outDebug("+ %u HIT", enchant_amount);
11741 break;
11742 case ITEM_MOD_CRIT_RATING:
11743 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11744 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11745 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11746 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11747 break;
11748 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11749 // case ITEM_MOD_HIT_TAKEN_RATING:
11750 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11751 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11752 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11753 // break;
11754 // case ITEM_MOD_CRIT_TAKEN_RATING:
11755 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11756 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11757 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11758 // break;
11759 case ITEM_MOD_RESILIENCE_RATING:
11760 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11761 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11762 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11763 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11764 break;
11765 case ITEM_MOD_HASTE_RATING:
11766 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11767 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11768 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11769 sLog.outDebug("+ %u HASTE", enchant_amount);
11770 break;
11771 case ITEM_MOD_EXPERTISE_RATING:
11772 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11773 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11774 break;
11775 case ITEM_MOD_ATTACK_POWER:
11776 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
11777 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11778 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
11779 break;
11780 case ITEM_MOD_RANGED_ATTACK_POWER:
11781 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11782 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
11783 break;
11784 case ITEM_MOD_FERAL_ATTACK_POWER:
11785 ((Player*)this)->ApplyFeralAPBonus(enchant_amount, apply);
11786 sLog.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount);
11787 break;
11788 case ITEM_MOD_SPELL_HEALING_DONE:
11789 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11790 sLog.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount);
11791 break;
11792 case ITEM_MOD_SPELL_DAMAGE_DONE:
11793 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11794 sLog.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount);
11795 break;
11796 case ITEM_MOD_MANA_REGENERATION:
11797 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
11798 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
11799 break;
11800 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11801 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11802 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11803 break;
11804 case ITEM_MOD_SPELL_POWER:
11805 ((Player*)this)->ApplySpellHealingBonus(enchant_amount, apply);
11806 ((Player*)this)->ApplySpellDamageBonus(enchant_amount, apply);
11807 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
11808 break;
11809 default:
11810 break;
11812 break;
11814 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11816 if(getClass() == CLASS_SHAMAN)
11818 float addValue = 0.0f;
11819 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11821 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11822 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11824 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11826 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
11827 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11830 break;
11832 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
11833 // processed in Player::CastItemUseSpell
11834 break;
11835 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
11836 // nothing do..
11837 break;
11838 default:
11839 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
11840 break;
11841 } /*switch(enchant_display_type)*/
11842 } /*for*/
11845 // visualize enchantment at player and equipped items
11846 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11848 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11849 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11852 if(apply_dur)
11854 if(apply)
11856 // set duration
11857 uint32 duration = item->GetEnchantmentDuration(slot);
11858 if(duration > 0)
11859 AddEnchantmentDuration(item, slot, duration);
11861 else
11863 // duration == 0 will remove EnchantDuration
11864 AddEnchantmentDuration(item, slot, 0);
11869 void Player::SendEnchantmentDurations()
11871 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11873 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
11877 void Player::SendItemDurations()
11879 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
11881 (*itr)->SendTimeUpdate(this);
11885 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11887 if(!item) // prevent crash
11888 return;
11890 // last check 2.0.10
11891 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11892 data << uint64(GetGUID()); // player GUID
11893 data << uint32(received); // 0=looted, 1=from npc
11894 data << uint32(created); // 0=received, 1=created
11895 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11896 data << uint8(item->GetBagSlot()); // bagslot
11897 // item slot, but when added to stack: 0xFFFFFFFF
11898 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
11899 data << uint32(item->GetEntry()); // item id
11900 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11901 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11902 data << uint32(count); // count of items
11903 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
11905 if (broadcast && GetGroup())
11906 GetGroup()->BroadcastPacket(&data, true);
11907 else
11908 GetSession()->SendPacket(&data);
11911 /*********************************************************/
11912 /*** QUEST SYSTEM ***/
11913 /*********************************************************/
11915 void Player::PrepareQuestMenu( uint64 guid )
11917 Object *pObject;
11918 QuestRelations* pObjectQR;
11919 QuestRelations* pObjectQIR;
11921 // pets also can have quests
11922 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
11923 if( pCreature )
11925 pObject = (Object*)pCreature;
11926 pObjectQR = &objmgr.mCreatureQuestRelations;
11927 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11929 else
11931 GameObject *pGameObject = GetMap()->GetGameObject(guid);
11932 if( pGameObject )
11934 pObject = (Object*)pGameObject;
11935 pObjectQR = &objmgr.mGOQuestRelations;
11936 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11938 else
11939 return;
11942 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11943 qm.ClearMenu();
11945 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11947 uint32 quest_id = i->second;
11948 QuestStatus status = GetQuestStatus( quest_id );
11949 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11950 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11951 else if ( status == QUEST_STATUS_INCOMPLETE )
11952 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11953 else if (status == QUEST_STATUS_AVAILABLE )
11954 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11957 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11959 uint32 quest_id = i->second;
11960 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11961 if(!pQuest) continue;
11963 QuestStatus status = GetQuestStatus( quest_id );
11965 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11966 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11967 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11968 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11972 void Player::SendPreparedQuest( uint64 guid )
11974 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11975 if( questMenu.Empty() )
11976 return;
11978 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11980 uint32 status = qmi0.m_qIcon;
11982 // single element case
11983 if ( questMenu.MenuItemCount() == 1 )
11985 // Auto open -- maybe also should verify there is no greeting
11986 uint32 quest_id = qmi0.m_qId;
11987 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11989 if ( pQuest )
11991 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11992 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest, false), true );
11993 else if( status == DIALOG_STATUS_INCOMPLETE )
11994 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11995 // Send completable on repeatable quest if player don't have quest
11996 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11997 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11998 else
11999 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
12002 // multiply entries
12003 else
12005 QEmote qe;
12006 qe._Delay = 0;
12007 qe._Emote = 0;
12008 std::string title = "";
12010 // need pet case for some quests
12011 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12012 if( pCreature )
12014 uint32 textid = pCreature->GetNpcTextId();
12015 GossipText const* gossiptext = objmgr.GetGossipText(textid);
12016 if( !gossiptext )
12018 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12019 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12020 title = "";
12022 else
12024 qe = gossiptext->Options[0].Emotes[0];
12026 if(!gossiptext->Options[0].Text_0.empty())
12028 title = gossiptext->Options[0].Text_0;
12030 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12031 if (loc_idx >= 0)
12033 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12034 if (nl)
12036 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12037 title = nl->Text_0[0][loc_idx];
12041 else
12043 title = gossiptext->Options[0].Text_1;
12045 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12046 if (loc_idx >= 0)
12048 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12049 if (nl)
12051 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12052 title = nl->Text_1[0][loc_idx];
12058 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12062 bool Player::IsActiveQuest( uint32 quest_id ) const
12064 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12066 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12069 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12071 Object *pObject;
12072 QuestRelations* pObjectQR;
12073 QuestRelations* pObjectQIR;
12075 Creature *pCreature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid);
12076 if( pCreature )
12078 pObject = (Object*)pCreature;
12079 pObjectQR = &objmgr.mCreatureQuestRelations;
12080 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12082 else
12084 GameObject *pGameObject = GetMap()->GetGameObject(guid);
12085 if( pGameObject )
12087 pObject = (Object*)pGameObject;
12088 pObjectQR = &objmgr.mGOQuestRelations;
12089 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12091 else
12092 return NULL;
12095 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12096 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12098 if (itr->second == nextQuestID)
12099 return objmgr.GetQuestTemplate(nextQuestID);
12102 return NULL;
12105 bool Player::CanSeeStartQuest( Quest const *pQuest )
12107 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12108 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12109 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12110 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12112 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12115 return false;
12118 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12120 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12121 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12122 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12123 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12124 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12125 && SatisfyQuestDay( pQuest, msg );
12128 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12130 if( !SatisfyQuestLog( msg ) )
12131 return false;
12133 uint32 srcitem = pQuest->GetSrcItemId();
12134 if( srcitem > 0 )
12136 uint32 count = pQuest->GetSrcItemCount();
12137 ItemPosCountVec dest;
12138 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12140 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12141 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12142 return true;
12143 else if( msg2 != EQUIP_ERR_OK )
12145 SendEquipError( msg2, NULL, NULL );
12146 return false;
12149 return true;
12152 bool Player::CanCompleteQuest( uint32 quest_id )
12154 if( quest_id )
12156 QuestStatusData& q_status = mQuestStatus[quest_id];
12157 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12158 return false; // not allow re-complete quest
12160 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12162 if(!qInfo)
12163 return false;
12165 // auto complete quest
12166 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12167 return true;
12169 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12172 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12174 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12176 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12177 return false;
12181 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12183 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12185 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12186 continue;
12188 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12189 return false;
12193 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12194 return false;
12196 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12197 return false;
12199 if ( qInfo->GetRewOrReqMoney() < 0 )
12201 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12202 return false;
12205 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12206 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12207 return false;
12209 return true;
12212 return false;
12215 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12217 // Solve problem that player don't have the quest and try complete it.
12218 // if repeatable she must be able to complete event if player don't have it.
12219 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12220 if( !CanTakeQuest(pQuest, false) )
12221 return false;
12223 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12224 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12225 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12226 return false;
12228 if( !CanRewardQuest(pQuest, false) )
12229 return false;
12231 return true;
12234 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12236 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12237 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12238 return false;
12240 // daily quest can't be rewarded (25 daily quest already completed)
12241 if(!SatisfyQuestDay(pQuest,true))
12242 return false;
12244 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12245 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12246 return false;
12248 // prevent receive reward with quest items in bank
12249 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12251 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12253 if( pQuest->ReqItemCount[i]!= 0 &&
12254 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12256 if(msg)
12257 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12258 return false;
12263 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12264 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12265 return false;
12267 return true;
12270 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12272 // prevent receive reward with quest items in bank or for not completed quest
12273 if(!CanRewardQuest(pQuest,msg))
12274 return false;
12276 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12278 if( pQuest->RewChoiceItemId[reward] )
12280 ItemPosCountVec dest;
12281 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12282 if( res != EQUIP_ERR_OK )
12284 SendEquipError( res, NULL, NULL );
12285 return false;
12290 if ( pQuest->GetRewItemsCount() > 0 )
12292 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12294 if( pQuest->RewItemId[i] )
12296 ItemPosCountVec dest;
12297 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12298 if( res != EQUIP_ERR_OK )
12300 SendEquipError( res, NULL, NULL );
12301 return false;
12307 return true;
12310 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12312 uint16 log_slot = FindQuestSlot( 0 );
12313 assert(log_slot < MAX_QUEST_LOG_SIZE);
12315 uint32 quest_id = pQuest->GetQuestId();
12317 // if not exist then created with set uState==NEW and rewarded=false
12318 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12320 // check for repeatable quests status reset
12321 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12322 questStatusData.m_explored = false;
12324 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12326 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12327 questStatusData.m_itemcount[i] = 0;
12330 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12332 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12333 questStatusData.m_creatureOrGOcount[i] = 0;
12336 GiveQuestSourceItem( pQuest );
12337 AdjustQuestReqItemCount( pQuest, questStatusData );
12339 if( pQuest->GetRepObjectiveFaction() )
12340 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
12341 GetReputationMgr().SetVisible(factionEntry);
12343 uint32 qtime = 0;
12344 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12346 uint32 limittime = pQuest->GetLimitTime();
12348 // shared timed quest
12349 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12350 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
12352 AddTimedQuest( quest_id );
12353 questStatusData.m_timer = limittime * IN_MILISECONDS;
12354 qtime = static_cast<uint32>(time(NULL)) + limittime;
12356 else
12357 questStatusData.m_timer = 0;
12359 SetQuestSlot(log_slot, quest_id, qtime);
12361 if (questStatusData.uState != QUEST_NEW)
12362 questStatusData.uState = QUEST_CHANGED;
12364 //starting initial quest script
12365 if(questGiver && pQuest->GetQuestStartScript()!=0)
12366 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12368 // Some spells applied at quest activation
12369 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,true);
12370 if(saBounds.first != saBounds.second)
12372 uint32 zone, area;
12373 GetZoneAndAreaId(zone,area);
12375 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12376 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12377 if( !HasAura(itr->second->spellId,0) )
12378 CastSpell(this,itr->second->spellId,true);
12381 UpdateForQuestWorldObjects();
12384 void Player::CompleteQuest( uint32 quest_id )
12386 if( quest_id )
12388 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12390 uint16 log_slot = FindQuestSlot( quest_id );
12391 if( log_slot < MAX_QUEST_LOG_SIZE)
12392 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12394 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12396 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12397 RewardQuest(qInfo,0,this,false);
12398 else
12399 SendQuestComplete( quest_id );
12404 void Player::IncompleteQuest( uint32 quest_id )
12406 if( quest_id )
12408 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12410 uint16 log_slot = FindQuestSlot( quest_id );
12411 if( log_slot < MAX_QUEST_LOG_SIZE)
12412 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12416 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12418 uint32 quest_id = pQuest->GetQuestId();
12420 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i )
12422 if ( pQuest->ReqItemId[i] )
12423 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12426 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12427 // SetTimedQuest( 0 );
12428 m_timedquests.erase(pQuest->GetQuestId());
12430 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12432 if( pQuest->RewChoiceItemId[reward] )
12434 ItemPosCountVec dest;
12435 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12437 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12438 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12443 if ( pQuest->GetRewItemsCount() > 0 )
12445 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12447 if( pQuest->RewItemId[i] )
12449 ItemPosCountVec dest;
12450 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12452 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12453 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12459 RewardReputation( pQuest );
12461 if( pQuest->GetRewSpellCast() > 0 )
12462 CastSpell( this, pQuest->GetRewSpellCast(), true);
12463 else if( pQuest->GetRewSpell() > 0)
12464 CastSpell( this, pQuest->GetRewSpell(), true);
12466 uint16 log_slot = FindQuestSlot( quest_id );
12467 if( log_slot < MAX_QUEST_LOG_SIZE)
12468 SetQuestSlot(log_slot,0);
12470 QuestStatusData& q_status = mQuestStatus[quest_id];
12472 // Not give XP in case already completed once repeatable quest
12473 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12475 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12476 GiveXP( XP , NULL );
12477 else
12479 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
12480 ModifyMoney( money );
12481 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
12484 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12485 if(pQuest->GetRewOrReqMoney())
12487 ModifyMoney( pQuest->GetRewOrReqMoney() );
12489 if(pQuest->GetRewOrReqMoney() > 0)
12490 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
12493 // honor reward
12494 if(pQuest->GetRewHonorableKills())
12495 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12497 // title reward
12498 if(pQuest->GetCharTitleId())
12500 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12501 SetTitle(titleEntry);
12504 if(pQuest->GetBonusTalents())
12506 m_questRewardTalentCount+=pQuest->GetBonusTalents();
12507 InitTalentForLevel();
12510 // Send reward mail
12511 if(pQuest->GetRewMailTemplateId())
12513 MailMessageType mailType;
12514 uint32 senderGuidOrEntry;
12515 switch(questGiver->GetTypeId())
12517 case TYPEID_UNIT:
12518 mailType = MAIL_CREATURE;
12519 senderGuidOrEntry = questGiver->GetEntry();
12520 break;
12521 case TYPEID_GAMEOBJECT:
12522 mailType = MAIL_GAMEOBJECT;
12523 senderGuidOrEntry = questGiver->GetEntry();
12524 break;
12525 case TYPEID_ITEM:
12526 mailType = MAIL_ITEM;
12527 senderGuidOrEntry = questGiver->GetEntry();
12528 break;
12529 case TYPEID_PLAYER:
12530 mailType = MAIL_NORMAL;
12531 senderGuidOrEntry = questGiver->GetGUIDLow();
12532 break;
12533 default:
12534 mailType = MAIL_NORMAL;
12535 senderGuidOrEntry = GetGUIDLow();
12536 break;
12539 Loot questMailLoot;
12541 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this,true);
12543 // fill mail
12544 MailItemsInfo mi; // item list preparing
12546 uint32 max_slot = questMailLoot.GetMaxSlotInLootFor(this);
12547 for(uint32 i = 0; mi.size() < MAX_MAIL_ITEMS && i < max_slot; ++i)
12549 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12551 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12553 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12554 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12559 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12562 if(pQuest->IsDaily())
12564 SetDailyQuestStatus(quest_id);
12565 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12568 if ( !pQuest->IsRepeatable() )
12569 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12570 else
12571 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12573 q_status.m_rewarded = true;
12575 if(announce)
12576 SendQuestReward( pQuest, XP, questGiver );
12578 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12579 if (pQuest->GetZoneOrSort() > 0)
12580 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
12581 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12582 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
12584 uint32 zone = 0;
12585 uint32 area = 0;
12587 // remove auras from spells with quest reward state limitations
12588 SpellAreaForQuestMapBounds saEndBounds = spellmgr.GetSpellAreaForQuestEndMapBounds(quest_id);
12589 if(saEndBounds.first != saEndBounds.second)
12591 GetZoneAndAreaId(zone,area);
12593 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
12594 if(!itr->second->IsFitToRequirements(this,zone,area))
12595 RemoveAurasDueToSpell(itr->second->spellId);
12598 // Some spells applied at quest reward
12599 SpellAreaForQuestMapBounds saBounds = spellmgr.GetSpellAreaForQuestMapBounds(quest_id,false);
12600 if(saBounds.first != saBounds.second)
12602 if(!zone || !area)
12603 GetZoneAndAreaId(zone,area);
12605 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
12606 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
12607 if( !HasAura(itr->second->spellId,0) )
12608 CastSpell(this,itr->second->spellId,true);
12612 void Player::FailQuest( uint32 quest_id )
12614 if( quest_id )
12616 IncompleteQuest( quest_id );
12618 uint16 log_slot = FindQuestSlot( quest_id );
12619 if( log_slot < MAX_QUEST_LOG_SIZE)
12621 SetQuestSlotTimer(log_slot, 1 );
12622 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12624 SendQuestFailed( quest_id );
12628 void Player::FailTimedQuest( uint32 quest_id )
12630 if( quest_id )
12632 QuestStatusData& q_status = mQuestStatus[quest_id];
12634 q_status.m_timer = 0;
12635 if (q_status.uState != QUEST_NEW)
12636 q_status.uState = QUEST_CHANGED;
12638 IncompleteQuest( quest_id );
12640 uint16 log_slot = FindQuestSlot( quest_id );
12641 if( log_slot < MAX_QUEST_LOG_SIZE)
12643 SetQuestSlotTimer(log_slot, 1 );
12644 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12646 SendQuestTimerFailed( quest_id );
12650 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12652 int32 zoneOrSort = qInfo->GetZoneOrSort();
12653 int32 skillOrClass = qInfo->GetSkillOrClass();
12655 // skip zone zoneOrSort and 0 case skillOrClass
12656 if( zoneOrSort >= 0 && skillOrClass == 0 )
12657 return true;
12659 int32 questSort = -zoneOrSort;
12660 uint8 reqSortClass = ClassByQuestSort(questSort);
12662 // check class sort cases in zoneOrSort
12663 if( reqSortClass != 0 && getClass() != reqSortClass)
12665 if( msg )
12666 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12667 return false;
12670 // check class
12671 if( skillOrClass < 0 )
12673 uint8 reqClass = -int32(skillOrClass);
12674 if(getClass() != reqClass)
12676 if( msg )
12677 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12678 return false;
12681 // check skill
12682 else if( skillOrClass > 0 )
12684 uint32 reqSkill = skillOrClass;
12685 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12687 if( msg )
12688 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12689 return false;
12693 return true;
12696 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12698 if( getLevel() < qInfo->GetMinLevel() )
12700 if( msg )
12701 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12702 return false;
12704 return true;
12707 bool Player::SatisfyQuestLog( bool msg )
12709 // exist free slot
12710 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12711 return true;
12713 if( msg )
12715 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12716 GetSession()->SendPacket( &data );
12717 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12719 return false;
12722 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12724 // No previous quest (might be first quest in a series)
12725 if( qInfo->prevQuests.empty())
12726 return true;
12728 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12730 uint32 prevId = abs(*iter);
12732 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12733 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12735 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12737 // If any of the positive previous quests completed, return true
12738 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12740 // skip one-from-all exclusive group
12741 if(qPrevInfo->GetExclusiveGroup() >= 0)
12742 return true;
12744 // each-from-all exclusive group ( < 0)
12745 // can be start if only all quests in prev quest exclusive group completed and rewarded
12746 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12747 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12749 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12751 for(; iter2 != end; ++iter2)
12753 uint32 exclude_Id = iter2->second;
12755 // skip checked quest id, only state of other quests in group is interesting
12756 if(exclude_Id == prevId)
12757 continue;
12759 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12761 // alternative quest from group also must be completed and rewarded(reported)
12762 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12764 if( msg )
12765 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12766 return false;
12769 return true;
12771 // If any of the negative previous quests active, return true
12772 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12773 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12775 // skip one-from-all exclusive group
12776 if(qPrevInfo->GetExclusiveGroup() >= 0)
12777 return true;
12779 // each-from-all exclusive group ( < 0)
12780 // can be start if only all quests in prev quest exclusive group active
12781 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12782 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12784 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12786 for(; iter2 != end; ++iter2)
12788 uint32 exclude_Id = iter2->second;
12790 // skip checked quest id, only state of other quests in group is interesting
12791 if(exclude_Id == prevId)
12792 continue;
12794 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
12796 // alternative quest from group also must be active
12797 if( i_exstatus == mQuestStatus.end() ||
12798 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12799 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12801 if( msg )
12802 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12803 return false;
12806 return true;
12811 // Has only positive prev. quests in non-rewarded state
12812 // and negative prev. quests in non-active state
12813 if( msg )
12814 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12816 return false;
12819 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12821 uint32 reqraces = qInfo->GetRequiredRaces();
12822 if ( reqraces == 0 )
12823 return true;
12824 if( (reqraces & getRaceMask()) == 0 )
12826 if( msg )
12827 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12828 return false;
12830 return true;
12833 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12835 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12836 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12838 if( msg )
12839 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12840 return false;
12843 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12844 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12846 if( msg )
12847 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12848 return false;
12851 return true;
12854 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12856 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12857 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12859 if( msg )
12860 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12861 return false;
12863 return true;
12866 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12868 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12870 if( msg )
12871 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12872 return false;
12874 return true;
12877 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12879 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12880 if(qInfo->GetExclusiveGroup() <= 0)
12881 return true;
12883 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12884 ObjectMgr::ExclusiveQuestGroups::const_iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12886 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12888 for(; iter != end; ++iter)
12890 uint32 exclude_Id = iter->second;
12892 // skip checked quest id, only state of other quests in group is interesting
12893 if(exclude_Id == qInfo->GetQuestId())
12894 continue;
12896 // not allow have daily quest if daily quest from exclusive group already recently completed
12897 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12898 if( !SatisfyQuestDay(Nquest, false) )
12900 if( msg )
12901 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12902 return false;
12905 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12907 // alternative quest already started or completed
12908 if( i_exstatus != mQuestStatus.end()
12909 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12911 if( msg )
12912 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12913 return false;
12916 return true;
12919 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12921 if(!qInfo->GetNextQuestInChain())
12922 return true;
12924 // next quest in chain already started or completed
12925 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12926 if( itr != mQuestStatus.end()
12927 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12929 if( msg )
12930 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12931 return false;
12934 // check for all quests further up the chain
12935 // only necessary if there are quest chains with more than one quest that can be skipped
12936 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12937 return true;
12940 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12942 // No previous quest in chain
12943 if( qInfo->prevChainQuests.empty())
12944 return true;
12946 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12948 uint32 prevId = *iter;
12950 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
12952 if( i_prevstatus != mQuestStatus.end() )
12954 // If any of the previous quests in chain active, return false
12955 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12956 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12958 if( msg )
12959 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12960 return false;
12964 // check for all quests further down the chain
12965 // only necessary if there are quest chains with more than one quest that can be skipped
12966 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12967 // return false;
12970 // No previous quest in chain active
12971 return true;
12974 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12976 if(!qInfo->IsDaily())
12977 return true;
12979 bool have_slot = false;
12980 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12982 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12983 if(qInfo->GetQuestId()==id)
12984 return false;
12986 if(!id)
12987 have_slot = true;
12990 if(!have_slot)
12992 if( msg )
12993 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12994 return false;
12997 return true;
13000 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13002 uint32 srcitem = pQuest->GetSrcItemId();
13003 if( srcitem > 0 )
13005 uint32 count = pQuest->GetSrcItemCount();
13006 if( count <= 0 )
13007 count = 1;
13009 ItemPosCountVec dest;
13010 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13011 if( msg == EQUIP_ERR_OK )
13013 Item * item = StoreNewItem(dest, srcitem, true);
13014 SendNewItem(item, count, true, false);
13015 return true;
13017 // player already have max amount required item, just report success
13018 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13019 return true;
13020 else
13021 SendEquipError( msg, NULL, NULL );
13022 return false;
13025 return true;
13028 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13030 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13031 if( qInfo )
13033 uint32 srcitem = qInfo->GetSrcItemId();
13034 if( srcitem > 0 )
13036 uint32 count = qInfo->GetSrcItemCount();
13037 if( count <= 0 )
13038 count = 1;
13040 // exist one case when destroy source quest item not possible:
13041 // non un-equippable item (equipped non-empty bag, for example)
13042 uint8 res = CanUnequipItems(srcitem,count);
13043 if(res != EQUIP_ERR_OK)
13045 if(msg)
13046 SendEquipError( res, NULL, NULL );
13047 return false;
13050 DestroyItemCount(srcitem, count, true, true);
13053 return true;
13056 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13058 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13059 if( qInfo )
13061 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13062 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13063 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13064 && !qInfo->IsRepeatable() )
13065 return itr->second.m_rewarded;
13067 return false;
13069 return false;
13072 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13074 if( quest_id )
13076 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13077 if( itr != mQuestStatus.end() )
13078 return itr->second.m_status;
13080 return QUEST_STATUS_NONE;
13083 bool Player::CanShareQuest(uint32 quest_id) const
13085 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13086 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13088 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13089 if( itr != mQuestStatus.end() )
13090 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13092 return false;
13095 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13097 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13098 if( qInfo )
13100 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13102 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13103 m_timedquests.erase(qInfo->GetQuestId());
13106 QuestStatusData& q_status = mQuestStatus[quest_id];
13108 q_status.m_status = status;
13109 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13112 UpdateForQuestWorldObjects();
13115 // not used in MaNGOS, but used in scripting code
13116 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13118 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13119 if( !qInfo )
13120 return 0;
13122 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13123 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13124 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13126 return 0;
13129 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13131 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13133 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13135 uint32 reqitemcount = pQuest->ReqItemCount[i];
13136 if( reqitemcount != 0 )
13138 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13140 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13141 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13147 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13149 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13150 if ( GetQuestSlotQuestId(i) == quest_id )
13151 return i;
13153 return MAX_QUEST_LOG_SIZE;
13156 void Player::AreaExploredOrEventHappens( uint32 questId )
13158 if( questId )
13160 uint16 log_slot = FindQuestSlot( questId );
13161 if( log_slot < MAX_QUEST_LOG_SIZE)
13163 QuestStatusData& q_status = mQuestStatus[questId];
13165 if(!q_status.m_explored)
13167 q_status.m_explored = true;
13168 if (q_status.uState != QUEST_NEW)
13169 q_status.uState = QUEST_CHANGED;
13172 if( CanCompleteQuest( questId ) )
13173 CompleteQuest( questId );
13177 //not used in mangosd, function for external script library
13178 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13180 if( Group *pGroup = GetGroup() )
13182 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13184 Player *pGroupGuy = itr->getSource();
13186 // for any leave or dead (with not released body) group member at appropriate distance
13187 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13188 pGroupGuy->AreaExploredOrEventHappens(questId);
13191 else
13192 AreaExploredOrEventHappens(questId);
13195 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13197 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13199 uint32 questid = GetQuestSlotQuestId(i);
13200 if ( questid == 0 )
13201 continue;
13203 QuestStatusData& q_status = mQuestStatus[questid];
13205 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13206 continue;
13208 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13209 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13210 continue;
13212 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13214 uint32 reqitem = qInfo->ReqItemId[j];
13215 if ( reqitem == entry )
13217 uint32 reqitemcount = qInfo->ReqItemCount[j];
13218 uint32 curitemcount = q_status.m_itemcount[j];
13219 if ( curitemcount < reqitemcount )
13221 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13222 q_status.m_itemcount[j] += additemcount;
13223 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13225 SendQuestUpdateAddItem( qInfo, j, additemcount );
13227 if ( CanCompleteQuest( questid ) )
13228 CompleteQuest( questid );
13229 return;
13233 UpdateForQuestWorldObjects();
13236 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13238 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13240 uint32 questid = GetQuestSlotQuestId(i);
13241 if(!questid)
13242 continue;
13243 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13244 if ( !qInfo )
13245 continue;
13246 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13247 continue;
13249 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13251 uint32 reqitem = qInfo->ReqItemId[j];
13252 if ( reqitem == entry )
13254 QuestStatusData& q_status = mQuestStatus[questid];
13256 uint32 reqitemcount = qInfo->ReqItemCount[j];
13257 uint32 curitemcount;
13258 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13259 curitemcount = q_status.m_itemcount[j];
13260 else
13261 curitemcount = GetItemCount(entry,true);
13262 if ( curitemcount < reqitemcount + count )
13264 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13265 q_status.m_itemcount[j] = curitemcount - remitemcount;
13266 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13268 IncompleteQuest( questid );
13270 return;
13274 UpdateForQuestWorldObjects();
13277 void Player::KilledMonster( uint32 entry, uint64 guid )
13279 uint32 addkillcount = 1;
13280 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13281 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13283 uint32 questid = GetQuestSlotQuestId(i);
13284 if(!questid)
13285 continue;
13287 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13288 if( !qInfo )
13289 continue;
13290 // just if !ingroup || !noraidgroup || raidgroup
13291 QuestStatusData& q_status = mQuestStatus[questid];
13292 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13294 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13296 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13298 // skip GO activate objective or none
13299 if(qInfo->ReqCreatureOrGOId[j] <=0)
13300 continue;
13302 // skip Cast at creature objective
13303 if(qInfo->ReqSpell[j] !=0 )
13304 continue;
13306 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13308 if ( reqkill == entry )
13310 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13311 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13312 if ( curkillcount < reqkillcount )
13314 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13315 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13317 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13319 if ( CanCompleteQuest( questid ) )
13320 CompleteQuest( questid );
13322 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13323 continue;
13331 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13333 bool isCreature = IS_CREATURE_GUID(guid);
13335 uint32 addCastCount = 1;
13336 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
13338 uint32 questid = GetQuestSlotQuestId(i);
13339 if(!questid)
13340 continue;
13342 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13343 if ( !qInfo )
13344 continue;
13346 QuestStatusData& q_status = mQuestStatus[questid];
13348 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13350 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13352 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13354 // skip kill creature objective (0) or wrong spell casts
13355 if(qInfo->ReqSpell[j] != spell_id )
13356 continue;
13358 uint32 reqTarget = 0;
13360 if(isCreature)
13362 // creature activate objectives
13363 if(qInfo->ReqCreatureOrGOId[j] > 0)
13364 // checked at quest_template loading
13365 reqTarget = qInfo->ReqCreatureOrGOId[j];
13367 else
13369 // GO activate objective
13370 if(qInfo->ReqCreatureOrGOId[j] < 0)
13371 // checked at quest_template loading
13372 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13375 // other not this creature/GO related objectives
13376 if( reqTarget != entry )
13377 continue;
13379 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13380 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13381 if ( curCastCount < reqCastCount )
13383 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13384 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13386 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13389 if ( CanCompleteQuest( questid ) )
13390 CompleteQuest( questid );
13392 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13393 break;
13400 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13402 uint32 addTalkCount = 1;
13403 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13405 uint32 questid = GetQuestSlotQuestId(i);
13406 if(!questid)
13407 continue;
13409 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13410 if ( !qInfo )
13411 continue;
13413 QuestStatusData& q_status = mQuestStatus[questid];
13415 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13417 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13419 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13421 // skip spell casts and Gameobject objectives
13422 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13423 continue;
13425 uint32 reqTarget = 0;
13427 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13428 // checked at quest_template loading
13429 reqTarget = qInfo->ReqCreatureOrGOId[j];
13430 else
13431 continue;
13433 if ( reqTarget == entry )
13435 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13436 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13437 if ( curTalkCount < reqTalkCount )
13439 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13440 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13442 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13444 if ( CanCompleteQuest( questid ) )
13445 CompleteQuest( questid );
13447 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13448 continue;
13456 void Player::MoneyChanged( uint32 count )
13458 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13460 uint32 questid = GetQuestSlotQuestId(i);
13461 if (!questid)
13462 continue;
13464 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13465 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13467 QuestStatusData& q_status = mQuestStatus[questid];
13469 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13471 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13473 if ( CanCompleteQuest( questid ) )
13474 CompleteQuest( questid );
13477 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13479 if(int32(count) < -qInfo->GetRewOrReqMoney())
13480 IncompleteQuest( questid );
13486 void Player::ReputationChanged(FactionEntry const* factionEntry )
13488 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13490 if(uint32 questid = GetQuestSlotQuestId(i))
13492 if(Quest const* qInfo = objmgr.GetQuestTemplate(questid))
13494 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
13496 QuestStatusData& q_status = mQuestStatus[questid];
13497 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13499 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
13500 if ( CanCompleteQuest( questid ) )
13501 CompleteQuest( questid );
13503 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13505 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
13506 IncompleteQuest( questid );
13514 bool Player::HasQuestForItem( uint32 itemid ) const
13516 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13518 uint32 questid = GetQuestSlotQuestId(i);
13519 if ( questid == 0 )
13520 continue;
13522 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
13523 if(qs_itr == mQuestStatus.end())
13524 continue;
13526 QuestStatusData const& q_status = qs_itr->second;
13528 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13530 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
13531 if(!qinfo)
13532 continue;
13534 // hide quest if player is in raid-group and quest is no raid quest
13535 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13536 continue;
13538 // There should be no mixed ReqItem/ReqSource drop
13539 // This part for ReqItem drop
13540 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13542 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13543 return true;
13545 // This part - for ReqSource
13546 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
13548 // examined item is a source item
13549 if (qinfo->ReqSourceId[j] == itemid)
13551 ItemPrototype const *pProto = objmgr.GetItemPrototype(itemid);
13553 // 'unique' item
13554 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
13555 return true;
13557 // allows custom amount drop when not 0
13558 if (qinfo->ReqSourceCount[j])
13560 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13561 return true;
13562 } else if (GetItemCount(itemid,true) < pProto->Stackable)
13563 return true;
13568 return false;
13571 void Player::SendQuestComplete( uint32 quest_id )
13573 if( quest_id )
13575 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13576 data << uint32(quest_id);
13577 GetSession()->SendPacket( &data );
13578 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13582 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13584 uint32 questid = pQuest->GetQuestId();
13585 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13586 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13587 data << uint32(questid);
13589 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13591 data << uint32(XP);
13592 data << uint32(pQuest->GetRewOrReqMoney());
13594 else
13596 data << uint32(0);
13597 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13600 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13601 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13602 GetSession()->SendPacket( &data );
13604 if (pQuest->GetQuestCompleteScript() != 0)
13605 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13608 void Player::SendQuestFailed( uint32 quest_id )
13610 if( quest_id )
13612 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13613 data << quest_id;
13614 data << uint32(0); // failed reason (4 for inventory is full)
13615 GetSession()->SendPacket( &data );
13616 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13620 void Player::SendQuestTimerFailed( uint32 quest_id )
13622 if( quest_id )
13624 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13625 data << quest_id;
13626 GetSession()->SendPacket( &data );
13627 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13631 void Player::SendCanTakeQuestResponse( uint32 msg )
13633 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13634 data << uint32(msg);
13635 GetSession()->SendPacket( &data );
13636 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13639 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13641 if( pPlayer )
13643 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13644 data << uint64(pPlayer->GetGUID());
13645 data << uint8(msg); // valid values: 0-8
13646 GetSession()->SendPacket( &data );
13647 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13651 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13653 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13654 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13655 //data << pQuest->ReqItemId[item_idx];
13656 //data << count;
13657 GetSession()->SendPacket( &data );
13660 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13662 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13664 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13665 if (entry < 0)
13666 // client expected gameobject template id in form (id|0x80000000)
13667 entry = (-entry) | 0x80000000;
13669 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13670 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13671 data << uint32(pQuest->GetQuestId());
13672 data << uint32(entry);
13673 data << uint32(old_count + add_count);
13674 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13675 data << uint64(guid);
13676 GetSession()->SendPacket(&data);
13678 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13679 if( log_slot < MAX_QUEST_LOG_SIZE)
13680 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13683 /*********************************************************/
13684 /*** LOAD SYSTEM ***/
13685 /*********************************************************/
13687 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13689 bool delete_result = true;
13690 if (!result)
13692 // 0 1 2 3 4 5 6 7 8 9 10
13693 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);
13694 if (!result)
13695 return false;
13697 else
13698 delete_result = false;
13700 Field *fields = result->Fetch();
13702 if (!LoadValues( fields[1].GetString()))
13704 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid));
13705 if (delete_result)
13706 delete result;
13707 return false;
13710 // overwrite possible wrong/corrupted guid
13711 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13713 m_name = fields[2].GetCppString();
13715 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13716 SetMapId(fields[6].GetUInt32());
13717 // the instance id is not needed at character enum
13719 m_Played_time[0] = fields[7].GetUInt32();
13720 m_Played_time[1] = fields[8].GetUInt32();
13722 m_atLoginFlags = fields[9].GetUInt32();
13724 // I don't see these used anywhere ..
13725 /*_LoadGroup();
13727 _LoadBoundInstances();*/
13729 if (delete_result)
13730 delete result;
13732 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
13733 m_items[i] = NULL;
13735 if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
13736 m_deathState = DEAD;
13738 return true;
13741 void Player::_LoadDeclinedNames(QueryResult* result)
13743 if(!result)
13744 return;
13746 if(m_declinedname)
13747 delete m_declinedname;
13749 m_declinedname = new DeclinedName;
13750 Field *fields = result->Fetch();
13751 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13752 m_declinedname->name[i] = fields[i].GetCppString();
13754 delete result;
13757 void Player::_LoadArenaTeamInfo(QueryResult *result)
13759 // arenateamid, played_week, played_season, personal_rating
13760 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32)*18);
13761 if (!result)
13762 return;
13766 Field *fields = result->Fetch();
13768 uint32 arenateamid = fields[0].GetUInt32();
13769 uint32 played_week = fields[1].GetUInt32();
13770 uint32 played_season = fields[2].GetUInt32();
13771 uint32 personal_rating = fields[3].GetUInt32();
13773 ArenaTeam* aTeam = objmgr.GetArenaTeamById(arenateamid);
13774 if(!aTeam)
13776 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid, played_week, played_season, personal_rating);
13777 continue;
13779 uint8 arenaSlot = aTeam->GetSlot();
13781 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6] = arenateamid; // TeamID
13782 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 1] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
13783 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 2] = played_week; // Played Week
13784 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 3] = played_season; // Played Season
13785 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 4] = 0; // Unk
13786 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arenaSlot * 6 + 5] = personal_rating; // Personal Rating
13788 }while (result->NextRow());
13789 delete result;
13792 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13794 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13795 if(!result)
13796 return false;
13798 Field *fields = result->Fetch();
13800 x = fields[0].GetFloat();
13801 y = fields[1].GetFloat();
13802 z = fields[2].GetFloat();
13803 o = fields[3].GetFloat();
13804 mapid = fields[4].GetUInt32();
13805 in_flight = !fields[5].GetCppString().empty();
13807 delete result;
13808 return true;
13811 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13813 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13814 if( !result )
13815 return false;
13817 Field *fields = result->Fetch();
13819 data = StrSplit(fields[0].GetCppString(), " ");
13821 delete result;
13823 return true;
13826 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13828 if(index >= data.size())
13829 return 0;
13831 return (uint32)atoi(data[index].c_str());
13834 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13836 float result;
13837 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13838 memcpy(&result, &temp, sizeof(result));
13840 return result;
13843 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13845 Tokens data;
13846 if(!LoadValuesArrayFromDB(data,guid))
13847 return 0;
13849 return GetUInt32ValueFromArray(data,index);
13852 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13854 float result;
13855 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13856 memcpy(&result, &temp, sizeof(result));
13858 return result;
13861 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13863 //// 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
13864 //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);
13865 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13867 if(!result)
13869 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13870 return false;
13873 Field *fields = result->Fetch();
13875 uint32 dbAccountId = fields[1].GetUInt32();
13877 // check if the character's account in the db and the logged in account match.
13878 // player should be able to load/delete character only with correct account!
13879 if( dbAccountId != GetSession()->GetAccountId() )
13881 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13882 delete result;
13883 return false;
13886 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13888 m_name = fields[3].GetCppString();
13890 // check name limitations
13891 if(!ObjectMgr::IsValidName(m_name) || (GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name)))
13893 delete result;
13894 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13895 return false;
13898 if(!LoadValues( fields[2].GetString()))
13900 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
13901 delete result;
13902 return false;
13905 // overwrite possible wrong/corrupted guid
13906 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13908 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13909 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13911 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
13912 SetVisibleItemSlot(slot, NULL);
13914 if (m_items[slot])
13916 delete m_items[slot];
13917 m_items[slot] = NULL;
13921 // update money limits
13922 if(GetMoney() > MAX_MONEY_AMOUNT)
13923 SetMoney(MAX_MONEY_AMOUNT);
13925 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13926 outDebugValues();
13928 m_race = fields[4].GetUInt8();
13929 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13930 //Other way is to saves m_team into characters table.
13931 setFactionForRace(m_race);
13932 SetCharm(NULL);
13934 m_class = fields[5].GetUInt8();
13936 // load home bind and check in same time class/race pair, it used later for restore broken positions
13937 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13939 delete result;
13940 return false;
13943 InitPrimaryProffesions(); // to max set before any spell loaded
13945 // init saved position, and fix it later if problematic
13946 uint32 transGUID = fields[24].GetUInt32();
13947 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13948 SetMapId(fields[9].GetUInt32());
13949 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13951 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13953 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
13955 uint32 arena_currency = GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY) + fields[33].GetUInt32();
13956 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
13957 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
13959 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
13961 // check arena teams integrity
13962 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13964 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13965 if(!arena_team_id)
13966 continue;
13968 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13969 if(at->HaveMember(GetGUID()))
13970 continue;
13972 // arena team not exist or not member, cleanup fields
13973 for(int j =0; j < 6; ++j)
13974 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13977 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13979 if(!IsPositionValid())
13981 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());
13982 RelocateToHomebind();
13984 transGUID = 0;
13986 m_movementInfo.t_x = 0.0f;
13987 m_movementInfo.t_y = 0.0f;
13988 m_movementInfo.t_z = 0.0f;
13989 m_movementInfo.t_o = 0.0f;
13992 uint32 bgid = fields[34].GetUInt32();
13993 uint32 bgteam = fields[35].GetUInt32();
13995 if(bgid) //saved in BattleGround
13997 SetBattleGroundEntryPoint(fields[36].GetUInt32(),fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
13999 // check entry point and fix to homebind if need
14000 MapEntry const* mapEntry = sMapStore.LookupEntry(m_bgEntryPoint.mapid);
14001 if(!mapEntry || mapEntry->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint))
14002 SetBattleGroundEntryPoint(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ,0.0f);
14004 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(bgid, BATTLEGROUND_TYPE_NONE);
14006 if(currentBg && currentBg->IsPlayerInBattleGround(GetGUID()))
14008 BattleGroundQueueTypeId bgQueueTypeId = sBattleGroundMgr.BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14009 AddBattleGroundQueueId(bgQueueTypeId);
14011 SetBattleGroundId(currentBg->GetInstanceID(), currentBg->GetTypeID());
14012 SetBGTeam(bgteam);
14014 //join player to battleground group
14015 currentBg->EventPlayerLoggedIn(this, GetGUID());
14016 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam);
14018 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14020 else
14022 Relocate(GetBattleGroundEntryPoint());
14023 //RemoveArenaAuras(true);
14026 else
14028 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14029 // if server restart after player save in BG or area
14030 // player can have current coordinates in to BG/Arean map, fix this
14031 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14033 // return to BG master
14034 SetMapId(fields[36].GetUInt32());
14035 Relocate(fields[37].GetFloat(),fields[38].GetFloat(),fields[39].GetFloat(),fields[40].GetFloat());
14037 // check entry point and fix to homebind if need
14038 mapEntry = sMapStore.LookupEntry(GetMapId());
14039 if(!mapEntry || mapEntry->IsBattleGroundOrArena() || !IsPositionValid())
14040 RelocateToHomebind();
14044 if (transGUID != 0)
14046 m_movementInfo.t_x = fields[20].GetFloat();
14047 m_movementInfo.t_y = fields[21].GetFloat();
14048 m_movementInfo.t_z = fields[22].GetFloat();
14049 m_movementInfo.t_o = fields[23].GetFloat();
14051 if( !MaNGOS::IsValidMapCoord(
14052 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14053 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
14054 // transport size limited
14055 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
14057 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14058 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
14059 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
14061 RelocateToHomebind();
14063 m_movementInfo.t_x = 0.0f;
14064 m_movementInfo.t_y = 0.0f;
14065 m_movementInfo.t_z = 0.0f;
14066 m_movementInfo.t_o = 0.0f;
14068 transGUID = 0;
14072 if (transGUID != 0)
14074 for (MapManager::TransportSet::const_iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
14076 if( (*iter)->GetGUIDLow() == transGUID)
14078 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14079 // client without expansion support
14080 if(GetSession()->Expansion() < transMapEntry->Expansion())
14082 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14083 break;
14086 m_transport = *iter;
14087 m_transport->AddPassenger(this);
14088 SetMapId(m_transport->GetMapId());
14089 break;
14093 if(!m_transport)
14095 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14096 guid,transGUID);
14098 RelocateToHomebind();
14100 m_movementInfo.t_x = 0.0f;
14101 m_movementInfo.t_y = 0.0f;
14102 m_movementInfo.t_z = 0.0f;
14103 m_movementInfo.t_o = 0.0f;
14105 transGUID = 0;
14108 else // not transport case
14110 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14111 // client without expansion support
14112 if(GetSession()->Expansion() < mapEntry->Expansion())
14114 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14115 RelocateToHomebind();
14119 // NOW player must have valid map
14120 // load the player's map here if it's not already loaded
14121 Map *map = GetMap();
14123 // since the player may not be bound to the map yet, make sure subsequent
14124 // getmap calls won't create new maps
14125 SetInstanceId(map->GetInstanceId());
14127 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14128 if(GetInstanceId() && !sInstanceSaveManager.GetInstanceSave(GetInstanceId()))
14130 AreaTrigger const* at = objmgr.GetMapEntranceTrigger(GetMapId());
14131 if(at)
14132 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14133 else
14134 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());
14137 SaveRecallPosition();
14139 time_t now = time(NULL);
14140 time_t logoutTime = time_t(fields[16].GetUInt64());
14142 // since last logout (in seconds)
14143 uint64 time_diff = uint64(now - logoutTime);
14145 // set value, including drunk invisibility detection
14146 // calculate sobering. after 15 minutes logged out, the player will be sober again
14147 float soberFactor;
14148 if(time_diff > 15*MINUTE)
14149 soberFactor = 0;
14150 else
14151 soberFactor = 1-time_diff/(15.0f*MINUTE);
14152 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14153 SetDrunkValue(newDrunkenValue);
14155 m_rest_bonus = fields[15].GetFloat();
14156 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14157 float bubble0 = 0.031;
14158 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14159 float bubble1 = 0.125;
14161 if((int32)fields[16].GetUInt32() > 0)
14163 float bubble = fields[17].GetUInt32() > 0
14164 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14165 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14167 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14170 m_cinematic = fields[12].GetUInt32();
14171 m_Played_time[0]= fields[13].GetUInt32();
14172 m_Played_time[1]= fields[14].GetUInt32();
14174 m_resetTalentsCost = fields[18].GetUInt32();
14175 m_resetTalentsTime = time_t(fields[19].GetUInt64());
14177 // reserve some flags
14178 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14180 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14181 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14183 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
14185 uint32 extraflags = fields[25].GetUInt32();
14187 m_stableSlots = fields[26].GetUInt32();
14188 if(m_stableSlots > MAX_PET_STABLES)
14190 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14191 m_stableSlots = MAX_PET_STABLES;
14194 m_atLoginFlags = fields[27].GetUInt32();
14196 // Honor system
14197 // Update Honor kills data
14198 m_lastHonorUpdateTime = logoutTime;
14199 UpdateHonorFields();
14201 m_deathExpireTime = (time_t)fields[30].GetUInt64();
14202 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14203 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14205 std::string taxi_nodes = fields[31].GetCppString();
14207 delete result;
14209 // clear channel spell data (if saved at channel spell casting)
14210 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
14211 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14213 // clear charm/summon related fields
14214 SetCharm(NULL);
14215 SetPet(NULL);
14216 SetCharmerGUID(0);
14217 SetOwnerGUID(0);
14218 SetCreatorGUID(0);
14220 // reset some aura modifiers before aura apply
14221 SetFarSightGUID(0);
14222 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14223 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14225 _LoadSkills();
14227 // make sure the unit is considered out of combat for proper loading
14228 ClearInCombat();
14230 // make sure the unit is considered not in duel for proper loading
14231 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14232 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14234 // remember loaded power/health values to restore after stats initialization and modifier applying
14235 uint32 savedHealth = GetHealth();
14236 uint32 savedPower[MAX_POWERS];
14237 for(uint32 i = 0; i < MAX_POWERS; ++i)
14238 savedPower[i] = GetPower(Powers(i));
14240 // reset stats before loading any modifiers
14241 InitStatsForLevel();
14242 InitTaxiNodesForLevel();
14243 InitGlyphsForLevel();
14244 InitRunes();
14246 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14248 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14249 //_LoadMail();
14251 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14252 _LoadGlyphAuras();
14254 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14255 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14256 m_deathState = DEAD;
14258 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14260 // after spell load, learn rewarded spell if need also
14261 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14262 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14264 // after spell and quest load
14265 InitTalentForLevel();
14266 learnDefaultSpells();
14268 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14270 // must be before inventory (some items required reputation check)
14271 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14273 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14275 // update items with duration and realtime
14276 UpdateItemDuration(time_diff, true);
14278 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14280 // unread mails and next delivery time, actual mails not loaded
14281 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14283 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14285 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14286 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14287 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14289 if(!HasTitle(curTitle))
14290 SetUInt32Value(PLAYER_CHOSEN_TITLE, 0);
14293 // Not finish taxi flight path
14294 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
14296 // problems with taxi path loading
14297 TaxiNodesEntry const* nodeEntry = NULL;
14298 if(uint32 node_id = m_taxi.GetTaxiSource())
14299 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14301 if(!nodeEntry) // don't know taxi start node, to homebind
14303 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14304 RelocateToHomebind();
14305 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14307 else // have start node, to it
14309 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14310 SetMapId(nodeEntry->map_id);
14311 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14312 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14314 m_taxi.ClearTaxiDestinations();
14316 else if(uint32 node_id = m_taxi.GetTaxiSource())
14318 // save source node as recall coord to prevent recall and fall from sky
14319 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14320 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14321 m_recallMap = nodeEntry->map_id;
14322 m_recallX = nodeEntry->x;
14323 m_recallY = nodeEntry->y;
14324 m_recallZ = nodeEntry->z;
14326 // flight will started later
14329 // has to be called after last Relocate() in Player::LoadFromDB
14330 SetFallInformation(0, GetPositionZ());
14332 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14334 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14335 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14336 if(!isAlive())
14337 RemoveAllAurasOnDeath();
14339 //apply all stat bonuses from items and auras
14340 SetCanModifyStats(true);
14341 UpdateAllStats();
14343 // restore remembered power/health values (but not more max values)
14344 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14345 for(uint32 i = 0; i < MAX_POWERS; ++i)
14346 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14348 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14349 outDebugValues();
14351 // GM state
14352 if(GetSession()->GetSecurity() > SEC_PLAYER)
14354 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14356 default:
14357 case 0: break; // disable
14358 case 1: SetGameMaster(true); break; // enable
14359 case 2: // save state
14360 if(extraflags & PLAYER_EXTRA_GM_ON)
14361 SetGameMaster(true);
14362 break;
14365 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
14367 default:
14368 case 0: SetGMVisible(false); break; // invisible
14369 case 1: break; // visible
14370 case 2: // save state
14371 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
14372 SetGMVisible(false);
14373 break;
14376 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14378 default:
14379 case 0: break; // disable
14380 case 1: SetAcceptTicket(true); break; // enable
14381 case 2: // save state
14382 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14383 SetAcceptTicket(true);
14384 break;
14387 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14389 default:
14390 case 0: break; // disable
14391 case 1: SetGMChat(true); break; // enable
14392 case 2: // save state
14393 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14394 SetGMChat(true);
14395 break;
14398 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14400 default:
14401 case 0: break; // disable
14402 case 1: SetAcceptWhispers(true); break; // enable
14403 case 2: // save state
14404 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14405 SetAcceptWhispers(true);
14406 break;
14410 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14412 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14413 m_achievementMgr.CheckAllAchievementCriteria();
14414 return true;
14417 bool Player::isAllowedToLoot(Creature* creature)
14419 if(Player* recipient = creature->GetLootRecipient())
14421 if (recipient == this)
14422 return true;
14423 if( Group* otherGroup = recipient->GetGroup())
14425 Group* thisGroup = GetGroup();
14426 if(!thisGroup)
14427 return false;
14428 return thisGroup == otherGroup;
14430 return false;
14432 else
14433 // prevent other players from looting if the recipient got disconnected
14434 return !creature->hasLootRecipient();
14437 void Player::_LoadActions(QueryResult *result)
14439 m_actionButtons.clear();
14441 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14443 if(result)
14447 Field *fields = result->Fetch();
14449 uint8 button = fields[0].GetUInt8();
14451 if(addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8()))
14452 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14453 else
14455 sLog.outError( " ...at loading, and will deleted in DB also");
14457 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14458 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
14461 while( result->NextRow() );
14463 delete result;
14467 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14469 m_Auras.clear();
14470 for (int i = 0; i < TOTAL_AURAS; ++i)
14471 m_modAuras[i].clear();
14473 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14475 if(result)
14479 Field *fields = result->Fetch();
14480 uint64 caster_guid = fields[0].GetUInt64();
14481 uint32 spellid = fields[1].GetUInt32();
14482 uint32 effindex = fields[2].GetUInt32();
14483 uint32 stackcount = fields[3].GetUInt32();
14484 int32 damage = (int32)fields[4].GetUInt32();
14485 int32 maxduration = (int32)fields[5].GetUInt32();
14486 int32 remaintime = (int32)fields[6].GetUInt32();
14487 int32 remaincharges = (int32)fields[7].GetUInt32();
14489 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14490 if(!spellproto)
14492 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14493 continue;
14496 if(effindex >= 3)
14498 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14499 continue;
14502 // negative effects should continue counting down after logout
14503 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14505 if(remaintime <= int32(timediff))
14506 continue;
14508 remaintime -= timediff;
14511 // prevent wrong values of remaincharges
14512 if(spellproto->procCharges)
14514 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14515 remaincharges = spellproto->procCharges;
14517 else
14518 remaincharges = 0;
14521 for(uint32 i=0; i<stackcount; ++i)
14523 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14524 if(!damage)
14525 damage = aura->GetModifier()->m_amount;
14527 // reset stolen single target auras
14528 if (caster_guid != GetGUID() && aura->IsSingleTarget())
14529 aura->SetIsSingleTarget(false);
14531 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14532 AddAura(aura);
14533 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14536 while( result->NextRow() );
14538 delete result;
14541 if(m_class == CLASS_WARRIOR)
14542 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14545 void Player::_LoadGlyphAuras()
14547 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
14549 if (uint32 glyph = GetGlyph(i))
14551 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
14553 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
14555 if(gp->TypeFlags == gs->TypeFlags)
14557 CastSpell(this, gp->SpellId, true);
14558 continue;
14560 else
14561 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
14563 else
14564 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
14566 else
14567 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
14569 // On any error remove glyph
14570 SetGlyph(i, 0);
14575 void Player::LoadCorpse()
14577 if( isAlive() )
14579 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14581 else
14583 if(Corpse *corpse = GetCorpse())
14585 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14587 else
14589 //Prevent Dead Player login without corpse
14590 ResurrectPlayer(0.5f);
14595 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14597 //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());
14598 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14599 //NOTE: the "order by `bag`" is important because it makes sure
14600 //the bagMap is filled before items in the bags are loaded
14601 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14602 //expected to be equipped before offhand items (TODO: fixme)
14604 uint32 zone = GetZoneId();
14606 if (result)
14608 std::list<Item*> problematicItems;
14610 // prevent items from being added to the queue when stored
14611 m_itemUpdateQueueBlocked = true;
14614 Field *fields = result->Fetch();
14615 uint32 bag_guid = fields[1].GetUInt32();
14616 uint8 slot = fields[2].GetUInt8();
14617 uint32 item_guid = fields[3].GetUInt32();
14618 uint32 item_id = fields[4].GetUInt32();
14620 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14622 if(!proto)
14624 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14625 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14626 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14627 continue;
14630 Item *item = NewItemOrBag(proto);
14632 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14634 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14635 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14636 item->FSetState(ITEM_REMOVED);
14637 item->SaveToDB(); // it also deletes item object !
14638 continue;
14641 // not allow have in alive state item limited to another map/zone
14642 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14644 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14645 item->FSetState(ITEM_REMOVED);
14646 item->SaveToDB(); // it also deletes item object !
14647 continue;
14650 // "Conjured items disappear if you are logged out for more than 15 minutes"
14651 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14653 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14654 item->FSetState(ITEM_REMOVED);
14655 item->SaveToDB(); // it also deletes item object !
14656 continue;
14659 bool success = true;
14661 if (!bag_guid)
14663 // the item is not in a bag
14664 item->SetContainer( NULL );
14665 item->SetSlot(slot);
14667 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14669 ItemPosCountVec dest;
14670 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14671 item = StoreItem(dest, item, true);
14672 else
14673 success = false;
14675 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14677 uint16 dest;
14678 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14679 QuickEquipItem(dest, item);
14680 else
14681 success = false;
14683 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14685 ItemPosCountVec dest;
14686 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14687 item = BankItem(dest, item, true);
14688 else
14689 success = false;
14692 if(success)
14694 // store bags that may contain items in them
14695 if(item->IsBag() && IsBagPos(item->GetPos()))
14696 bagMap[item_guid] = (Bag*)item;
14699 else
14701 item->SetSlot(NULL_SLOT);
14702 // the item is in a bag, find the bag
14703 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
14704 if(itr != bagMap.end())
14705 itr->second->StoreItem(slot, item, true );
14706 else
14707 success = false;
14710 // item's state may have changed after stored
14711 if (success)
14712 item->SetState(ITEM_UNCHANGED, this);
14713 else
14715 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);
14716 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14717 problematicItems.push_back(item);
14719 } while (result->NextRow());
14721 delete result;
14722 m_itemUpdateQueueBlocked = false;
14724 // send by mail problematic items
14725 while(!problematicItems.empty())
14727 // fill mail
14728 MailItemsInfo mi; // item list preparing
14730 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14732 Item* item = problematicItems.front();
14733 problematicItems.pop_front();
14735 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14738 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14740 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14743 //if(isAlive())
14744 _ApplyAllItemMods();
14747 // load mailed item which should receive current player
14748 void Player::_LoadMailedItems(Mail *mail)
14750 // data needs to be at first place for Item::LoadFromDB
14751 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);
14752 if(!result)
14753 return;
14757 Field *fields = result->Fetch();
14758 uint32 item_guid_low = fields[1].GetUInt32();
14759 uint32 item_template = fields[2].GetUInt32();
14761 mail->AddItem(item_guid_low, item_template);
14763 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14765 if(!proto)
14767 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);
14768 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14769 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14770 continue;
14773 Item *item = NewItemOrBag(proto);
14775 if(!item->LoadFromDB(item_guid_low, 0, result))
14777 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14778 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14779 item->FSetState(ITEM_REMOVED);
14780 item->SaveToDB(); // it also deletes item object !
14781 continue;
14784 AddMItem(item);
14785 } while (result->NextRow());
14787 delete result;
14790 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14792 //set a count of unread mails
14793 //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);
14794 if (resultUnread)
14796 Field *fieldMail = resultUnread->Fetch();
14797 unReadMails = fieldMail[0].GetUInt8();
14798 delete resultUnread;
14801 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14802 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14803 if (resultDelivery)
14805 Field *fieldMail = resultDelivery->Fetch();
14806 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14807 delete resultDelivery;
14811 void Player::_LoadMail()
14813 m_mail.clear();
14814 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14815 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());
14816 if(result)
14820 Field *fields = result->Fetch();
14821 Mail *m = new Mail;
14822 m->messageID = fields[0].GetUInt32();
14823 m->messageType = fields[1].GetUInt8();
14824 m->sender = fields[2].GetUInt32();
14825 m->receiver = fields[3].GetUInt32();
14826 m->subject = fields[4].GetCppString();
14827 m->itemTextId = fields[5].GetUInt32();
14828 bool has_items = fields[6].GetBool();
14829 m->expire_time = (time_t)fields[7].GetUInt64();
14830 m->deliver_time = (time_t)fields[8].GetUInt64();
14831 m->money = fields[9].GetUInt32();
14832 m->COD = fields[10].GetUInt32();
14833 m->checked = fields[11].GetUInt32();
14834 m->stationery = fields[12].GetUInt8();
14835 m->mailTemplateId = fields[13].GetInt16();
14837 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14839 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14840 m->mailTemplateId = 0;
14843 m->state = MAIL_STATE_UNCHANGED;
14845 if (has_items)
14846 _LoadMailedItems(m);
14848 m_mail.push_back(m);
14849 } while( result->NextRow() );
14850 delete result;
14852 m_mailsLoaded = true;
14855 void Player::LoadPet()
14857 //fixme: the pet should still be loaded if the player is not in world
14858 // just not added to the map
14859 if(IsInWorld())
14861 Pet *pet = new Pet;
14862 if(!pet->LoadPetFromDB(this,0,0,true))
14863 delete pet;
14867 void Player::_LoadQuestStatus(QueryResult *result)
14869 mQuestStatus.clear();
14871 uint32 slot = 0;
14873 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14874 //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());
14876 if(result)
14880 Field *fields = result->Fetch();
14882 uint32 quest_id = fields[0].GetUInt32();
14883 // used to be new, no delete?
14884 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14885 if( pQuest )
14887 // find or create
14888 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14890 uint32 qstatus = fields[1].GetUInt32();
14891 if(qstatus < MAX_QUEST_STATUS)
14892 questStatusData.m_status = QuestStatus(qstatus);
14893 else
14895 questStatusData.m_status = QUEST_STATUS_NONE;
14896 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14899 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14900 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14902 time_t quest_time = time_t(fields[4].GetUInt64());
14904 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14906 AddTimedQuest( quest_id );
14908 if (quest_time <= sWorld.GetGameTime())
14909 questStatusData.m_timer = 1;
14910 else
14911 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
14913 else
14914 quest_time = 0;
14916 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14917 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14918 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14919 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14920 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14921 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14922 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14923 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14925 questStatusData.uState = QUEST_UNCHANGED;
14927 // add to quest log
14928 if( slot < MAX_QUEST_LOG_SIZE &&
14929 ( questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
14930 questStatusData.m_status == QUEST_STATUS_COMPLETE &&
14931 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14933 SetQuestSlot(slot, quest_id, quest_time);
14935 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14936 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
14938 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14939 if(questStatusData.m_creatureOrGOcount[idx])
14940 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
14942 ++slot;
14945 if(questStatusData.m_rewarded)
14947 // learn rewarded spell if unknown
14948 learnQuestRewardedSpells(pQuest);
14950 // set rewarded title if any
14951 if(pQuest->GetCharTitleId())
14953 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14954 SetTitle(titleEntry);
14957 if(pQuest->GetBonusTalents())
14958 m_questRewardTalentCount += pQuest->GetBonusTalents();
14961 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14964 while( result->NextRow() );
14966 delete result;
14969 // clear quest log tail
14970 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14971 SetQuestSlot(i, 0);
14974 void Player::_LoadDailyQuestStatus(QueryResult *result)
14976 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14977 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14979 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14981 if(result)
14983 uint32 quest_daily_idx = 0;
14987 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14989 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14990 break;
14993 Field *fields = result->Fetch();
14995 uint32 quest_id = fields[0].GetUInt32();
14997 // save _any_ from daily quest times (it must be after last reset anyway)
14998 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15000 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
15001 if( !pQuest )
15002 continue;
15004 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15005 ++quest_daily_idx;
15007 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15009 while( result->NextRow() );
15011 delete result;
15014 m_DailyQuestChanged = false;
15017 void Player::_LoadSpells(QueryResult *result)
15019 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15021 if(result)
15025 Field *fields = result->Fetch();
15027 addSpell(fields[0].GetUInt16(), fields[1].GetBool(), false, false, fields[2].GetBool());
15029 while( result->NextRow() );
15031 delete result;
15035 void Player::_LoadTutorials(QueryResult *result)
15037 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15039 if(result)
15043 Field *fields = result->Fetch();
15045 for (int iI=0; iI<8; ++iI)
15046 m_Tutorials[iI] = fields[iI].GetUInt32();
15048 while( result->NextRow() );
15050 delete result;
15053 m_TutorialsChanged = false;
15056 void Player::_LoadGroup(QueryResult *result)
15058 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15059 if(result)
15061 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
15062 delete result;
15063 Group* group = objmgr.GetGroupByLeader(leaderGuid);
15064 if(group)
15066 uint8 subgroup = group->GetMemberGroup(GetGUID());
15067 SetGroup(group, subgroup);
15068 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
15070 // the group leader may change the instance difficulty while the player is offline
15071 SetDifficulty(group->GetDifficulty());
15077 void Player::_LoadBoundInstances(QueryResult *result)
15079 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15080 m_boundInstances[i].clear();
15082 Group *group = GetGroup();
15084 //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));
15085 if(result)
15089 Field *fields = result->Fetch();
15090 bool perm = fields[1].GetBool();
15091 uint32 mapId = fields[2].GetUInt32();
15092 uint32 instanceId = fields[0].GetUInt32();
15093 uint8 difficulty = fields[3].GetUInt8();
15094 time_t resetTime = (time_t)fields[4].GetUInt64();
15095 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15096 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15097 // and in that case it is not used
15099 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15100 if(!mapEntry || !mapEntry->IsDungeon())
15102 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15103 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15104 continue;
15107 if(!perm && group)
15109 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);
15110 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15111 continue;
15114 // since non permanent binds are always solo bind, they can always be reset
15115 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
15116 if(save) BindToInstance(save, perm, true);
15117 } while(result->NextRow());
15118 delete result;
15122 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
15124 // some instances only have one difficulty
15125 const MapEntry* entry = sMapStore.LookupEntry(mapid);
15126 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
15128 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15129 if(itr != m_boundInstances[difficulty].end())
15130 return &itr->second;
15131 else
15132 return NULL;
15135 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
15137 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15138 UnbindInstance(itr, difficulty, unload);
15141 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
15143 if(itr != m_boundInstances[difficulty].end())
15145 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15146 itr->second.save->RemovePlayer(this); // save can become invalid
15147 m_boundInstances[difficulty].erase(itr++);
15151 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15153 if(save)
15155 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15156 if(bind.save)
15158 // update the save when the group kills a boss
15159 if(permanent != bind.perm || save != bind.save)
15160 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());
15162 else
15163 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15165 if(bind.save != save)
15167 if(bind.save) bind.save->RemovePlayer(this);
15168 save->AddPlayer(this);
15171 if(permanent) save->SetCanReset(false);
15173 bind.save = save;
15174 bind.perm = permanent;
15175 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());
15176 return &bind;
15178 else
15179 return NULL;
15182 void Player::SendRaidInfo()
15184 uint32 counter = 0;
15186 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15188 size_t p_counter = data.wpos();
15189 data << uint32(counter); // placeholder
15191 for(int i = 0; i < TOTAL_DIFFICULTIES; ++i)
15193 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15195 if(itr->second.perm)
15197 InstanceSave *save = itr->second.save;
15198 data << uint32(save->GetMapId());
15199 data << uint32(save->GetResetTime() - time(NULL));
15200 data << uint32(save->GetInstanceId());
15201 data << uint32(save->GetDifficulty());
15202 ++counter;
15206 data.put<uint32>(p_counter, counter);
15207 GetSession()->SendPacket(&data);
15211 - called on every successful teleportation to a map
15213 void Player::SendSavedInstances()
15215 bool hasBeenSaved = false;
15216 WorldPacket data;
15218 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15220 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15222 if(itr->second.perm) // only permanent binds are sent
15224 hasBeenSaved = true;
15225 break;
15230 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15231 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15232 data << uint32(hasBeenSaved);
15233 GetSession()->SendPacket(&data);
15235 if(!hasBeenSaved)
15236 return;
15238 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15240 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15242 if(itr->second.perm)
15244 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15245 data << uint32(itr->second.save->GetMapId());
15246 GetSession()->SendPacket(&data);
15252 /// convert the player's binds to the group
15253 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15255 bool has_binds = false;
15256 bool has_solo = false;
15258 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15259 assert(player_guid);
15261 // copy all binds to the group, when changing leader it's assumed the character
15262 // will not have any solo binds
15264 if(player)
15266 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; ++i)
15268 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15270 has_binds = true;
15271 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15272 // permanent binds are not removed
15273 if(!itr->second.perm)
15275 player->UnbindInstance(itr, i, true); // increments itr
15276 has_solo = true;
15278 else
15279 ++itr;
15284 // if the player's not online we don't know what binds it has
15285 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));
15286 // the following should not get executed when changing leaders
15287 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15290 bool Player::_LoadHomeBind(QueryResult *result)
15292 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15293 if(!info)
15295 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
15296 return false;
15299 bool ok = false;
15300 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15301 if (result)
15303 Field *fields = result->Fetch();
15304 m_homebindMapId = fields[0].GetUInt32();
15305 m_homebindZoneId = fields[1].GetUInt16();
15306 m_homebindX = fields[2].GetFloat();
15307 m_homebindY = fields[3].GetFloat();
15308 m_homebindZ = fields[4].GetFloat();
15309 delete result;
15311 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
15313 // accept saved data only for valid position (and non instanceable), and accessable
15314 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15315 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
15317 ok = true;
15319 else
15320 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15323 if(!ok)
15325 m_homebindMapId = info->mapId;
15326 m_homebindZoneId = info->zoneId;
15327 m_homebindX = info->positionX;
15328 m_homebindY = info->positionY;
15329 m_homebindZ = info->positionZ;
15331 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);
15334 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15335 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15337 return true;
15340 /*********************************************************/
15341 /*** SAVE SYSTEM ***/
15342 /*********************************************************/
15344 void Player::SaveToDB()
15346 // delay auto save at any saves (manual, in code, or autosave)
15347 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15349 // first save/honor gain after midnight will also update the player's honor fields
15350 UpdateHonorFields();
15352 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15353 //save, far from tavern/city
15354 //save, but in tavern/city
15355 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15356 outDebugValues();
15358 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15359 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15360 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15361 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15362 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15363 uint32 tmp_displayid = GetDisplayId();
15365 // Set player sit state to standing on save, also stealth and shifted form
15366 SetByteValue(UNIT_FIELD_BYTES_1, 0, UNIT_STAND_STATE_STAND);
15367 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15368 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15369 SetDisplayId(GetNativeDisplayId());
15371 bool inworld = IsInWorld();
15373 CharacterDatabase.BeginTransaction();
15375 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15377 std::string sql_name = m_name;
15378 CharacterDatabase.escape_string(sql_name);
15380 std::ostringstream ss;
15381 ss << "INSERT INTO characters (guid,account,name,race,class,"
15382 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15383 "taximask, online, cinematic, "
15384 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15385 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15386 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15387 << GetGUIDLow() << ", "
15388 << GetSession()->GetAccountId() << ", '"
15389 << sql_name << "', "
15390 << m_race << ", "
15391 << m_class << ", ";
15393 if(!IsBeingTeleported())
15395 ss << GetMapId() << ", "
15396 << (uint32)GetDifficulty() << ", "
15397 << finiteAlways(GetPositionX()) << ", "
15398 << finiteAlways(GetPositionY()) << ", "
15399 << finiteAlways(GetPositionZ()) << ", "
15400 << finiteAlways(GetOrientation()) << ", '";
15402 else
15404 ss << GetTeleportDest().mapid << ", "
15405 << (uint32)GetDifficulty() << ", "
15406 << finiteAlways(GetTeleportDest().x) << ", "
15407 << finiteAlways(GetTeleportDest().y) << ", "
15408 << finiteAlways(GetTeleportDest().z) << ", "
15409 << finiteAlways(GetTeleportDest().o) << ", '";
15412 uint16 i;
15413 for( i = 0; i < m_valuesCount; ++i )
15415 ss << GetUInt32Value(i) << " ";
15418 ss << "', ";
15420 ss << m_taxi; // string with TaxiMaskSize numbers
15422 ss << ", ";
15423 ss << (inworld ? 1 : 0);
15425 ss << ", ";
15426 ss << m_cinematic;
15428 ss << ", ";
15429 ss << m_Played_time[0];
15430 ss << ", ";
15431 ss << m_Played_time[1];
15433 ss << ", ";
15434 ss << finiteAlways(m_rest_bonus);
15435 ss << ", ";
15436 ss << (uint64)time(NULL);
15437 ss << ", ";
15438 ss << is_save_resting;
15439 ss << ", ";
15440 ss << m_resetTalentsCost;
15441 ss << ", ";
15442 ss << (uint64)m_resetTalentsTime;
15444 ss << ", ";
15445 ss << finiteAlways(m_movementInfo.t_x);
15446 ss << ", ";
15447 ss << finiteAlways(m_movementInfo.t_y);
15448 ss << ", ";
15449 ss << finiteAlways(m_movementInfo.t_z);
15450 ss << ", ";
15451 ss << finiteAlways(m_movementInfo.t_o);
15452 ss << ", ";
15453 if (m_transport)
15454 ss << m_transport->GetGUIDLow();
15455 else
15456 ss << "0";
15458 ss << ", ";
15459 ss << m_ExtraFlags;
15461 ss << ", ";
15462 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15464 ss << ", ";
15465 ss << uint32(m_atLoginFlags);
15467 ss << ", ";
15468 ss << GetZoneId();
15470 ss << ", ";
15471 ss << (uint64)m_deathExpireTime;
15473 ss << ", '";
15474 ss << m_taxi.SaveTaxiDestinationsToString();
15475 ss << "', '0', ";
15476 ss << GetBattleGroundId();
15477 ss << ", ";
15478 ss << GetBGTeam();
15479 ss << ", ";
15480 ss << m_bgEntryPoint.mapid << ", "
15481 << finiteAlways(m_bgEntryPoint.x) << ", "
15482 << finiteAlways(m_bgEntryPoint.y) << ", "
15483 << finiteAlways(m_bgEntryPoint.z) << ", "
15484 << finiteAlways(m_bgEntryPoint.o);
15485 ss << ")";
15487 CharacterDatabase.Execute( ss.str().c_str() );
15489 if(m_mailsUpdated) //save mails only when needed
15490 _SaveMail();
15492 _SaveInventory();
15493 _SaveQuestStatus();
15494 _SaveDailyQuestStatus();
15495 _SaveTutorials();
15496 _SaveSpells();
15497 _SaveSpellCooldowns();
15498 _SaveActions();
15499 _SaveAuras();
15500 m_achievementMgr.SaveToDB();
15501 m_reputationMgr.SaveToDB();
15503 CharacterDatabase.CommitTransaction();
15505 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15506 SetDisplayId(tmp_displayid);
15507 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15508 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15509 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15510 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15512 // save pet (hunter pet level and experience and all type pets health/mana).
15513 if(Pet* pet = GetPet())
15514 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15517 // fast save function for item/money cheating preventing - save only inventory and money state
15518 void Player::SaveInventoryAndGoldToDB()
15520 _SaveInventory();
15521 //money is in data field
15522 SaveDataFieldToDB();
15525 void Player::_SaveActions()
15527 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15529 switch (itr->second.uState)
15531 case ACTIONBUTTON_NEW:
15532 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15533 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15534 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15535 ++itr;
15536 break;
15537 case ACTIONBUTTON_CHANGED:
15538 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15539 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15540 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15541 ++itr;
15542 break;
15543 case ACTIONBUTTON_DELETED:
15544 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15545 m_actionButtons.erase(itr++);
15546 break;
15547 default:
15548 ++itr;
15549 break;
15554 void Player::_SaveAuras()
15556 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15558 AuraMap const& auras = GetAuras();
15560 if (auras.empty())
15561 return;
15563 spellEffectPair lastEffectPair = auras.begin()->first;
15564 uint32 stackCounter = 1;
15566 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15568 if(itr == auras.end() || lastEffectPair != itr->first)
15570 AuraMap::const_iterator itr2 = itr;
15571 // save previous spellEffectPair to db
15572 itr2--;
15574 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15576 //skip all auras from spells that are passive or need a shapeshift
15577 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15579 //do not save single target auras (unless they were cast by the player)
15580 if (!(itr2->second->GetCasterGUID() != GetGUID() && itr2->second->IsSingleTarget()))
15582 uint8 i;
15583 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15584 for (i = 0; i < 3; ++i)
15585 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15586 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15587 break;
15589 if (i == 3)
15591 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15592 "VALUES ('%u', '" UI64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15593 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()));
15598 if(itr == auras.end())
15599 break;
15602 if (lastEffectPair == itr->first)
15603 stackCounter++;
15604 else
15606 lastEffectPair = itr->first;
15607 stackCounter = 1;
15612 void Player::_SaveInventory()
15614 // force items in buyback slots to new state
15615 // and remove those that aren't already
15616 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
15618 Item *item = m_items[i];
15619 if (!item || item->GetState() == ITEM_NEW) continue;
15620 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15621 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15622 m_items[i]->FSetState(ITEM_NEW);
15625 // update enchantment durations
15626 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15628 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15631 // if no changes
15632 if (m_itemUpdateQueue.empty()) return;
15634 // do not save if the update queue is corrupt
15635 bool error = false;
15636 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15638 Item *item = m_itemUpdateQueue[i];
15639 if(!item || item->GetState() == ITEM_REMOVED) continue;
15640 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15642 if (test == NULL)
15644 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
15645 error = true;
15647 else if (test != item)
15649 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());
15650 error = true;
15654 if (error)
15656 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15657 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15658 return;
15661 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
15663 Item *item = m_itemUpdateQueue[i];
15664 if(!item) continue;
15666 Bag *container = item->GetContainer();
15667 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15669 switch(item->GetState())
15671 case ITEM_NEW:
15672 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());
15673 break;
15674 case ITEM_CHANGED:
15675 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());
15676 break;
15677 case ITEM_REMOVED:
15678 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15679 break;
15680 case ITEM_UNCHANGED:
15681 break;
15684 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15686 m_itemUpdateQueue.clear();
15689 void Player::_SaveMail()
15691 if (!m_mailsLoaded)
15692 return;
15694 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15696 Mail *m = (*itr);
15697 if (m->state == MAIL_STATE_CHANGED)
15699 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'",
15700 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15701 if(m->removedItems.size())
15703 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15704 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15705 m->removedItems.clear();
15707 m->state = MAIL_STATE_UNCHANGED;
15709 else if (m->state == MAIL_STATE_DELETED)
15711 if (m->HasItems())
15712 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15713 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15714 if (m->itemTextId)
15715 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15716 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15717 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15721 //deallocate deleted mails...
15722 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15724 if ((*itr)->state == MAIL_STATE_DELETED)
15726 Mail* m = *itr;
15727 m_mail.erase(itr);
15728 delete m;
15729 itr = m_mail.begin();
15731 else
15732 ++itr;
15735 m_mailsUpdated = false;
15738 void Player::_SaveQuestStatus()
15740 // we don't need transactions here.
15741 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15743 switch (i->second.uState)
15745 case QUEST_NEW :
15746 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15747 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15748 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]);
15749 break;
15750 case QUEST_CHANGED :
15751 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' ",
15752 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 );
15753 break;
15754 case QUEST_UNCHANGED:
15755 break;
15757 i->second.uState = QUEST_UNCHANGED;
15761 void Player::_SaveDailyQuestStatus()
15763 if(!m_DailyQuestChanged)
15764 return;
15766 m_DailyQuestChanged = false;
15768 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15770 // we don't need transactions here.
15771 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15772 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15773 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15774 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
15775 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15778 void Player::_SaveSpells()
15780 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
15782 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15783 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15785 // add only changed/new not dependent spells
15786 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
15787 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);
15789 if (itr->second->state == PLAYERSPELL_REMOVED)
15791 delete itr->second;
15792 m_spells.erase(itr++);
15794 else
15796 itr->second->state = PLAYERSPELL_UNCHANGED;
15797 ++itr;
15803 void Player::_SaveTutorials()
15805 if(!m_TutorialsChanged)
15806 return;
15808 uint32 Rows=0;
15809 // it's better than rebuilding indexes multiple times
15810 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15811 if(result)
15813 Rows = result->Fetch()[0].GetUInt32();
15814 delete result;
15817 if (Rows)
15819 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'",
15820 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 );
15822 else
15824 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]);
15827 m_TutorialsChanged = false;
15830 void Player::outDebugValues() const
15832 if(!sLog.IsOutDebug()) // optimize disabled debug output
15833 return;
15835 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15836 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15837 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15838 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15839 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15840 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15841 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15842 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15843 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15844 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15845 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15846 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15849 /*********************************************************/
15850 /*** FLOOD FILTER SYSTEM ***/
15851 /*********************************************************/
15853 void Player::UpdateSpeakTime()
15855 // ignore chat spam protection for GMs in any mode
15856 if(GetSession()->GetSecurity() > SEC_PLAYER)
15857 return;
15859 time_t current = time (NULL);
15860 if(m_speakTime > current)
15862 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15863 if(!max_count)
15864 return;
15866 ++m_speakCount;
15867 if(m_speakCount >= max_count)
15869 // prevent overwrite mute time, if message send just before mutes set, for example.
15870 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15871 if(GetSession()->m_muteTime < new_mute)
15872 GetSession()->m_muteTime = new_mute;
15874 m_speakCount = 0;
15877 else
15878 m_speakCount = 0;
15880 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15883 bool Player::CanSpeak() const
15885 return GetSession()->m_muteTime <= time (NULL);
15888 /*********************************************************/
15889 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15890 /*********************************************************/
15892 void Player::SendAttackSwingNotInRange()
15894 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15895 GetSession()->SendPacket( &data );
15898 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15900 std::ostringstream ss;
15901 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15902 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15903 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15904 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15905 sLog.outDebug(ss.str().c_str());
15906 CharacterDatabase.Execute(ss.str().c_str());
15909 void Player::SaveDataFieldToDB()
15911 std::ostringstream ss;
15912 ss<<"UPDATE characters SET data='";
15914 for(uint16 i = 0; i < m_valuesCount; ++i )
15916 ss << GetUInt32Value(i) << " ";
15918 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15920 CharacterDatabase.Execute(ss.str().c_str());
15923 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15925 std::ostringstream ss2;
15926 ss2<<"UPDATE characters SET data='";
15927 int i=0;
15928 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15930 ss2<<tokens[i]<<" ";
15932 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15934 return CharacterDatabase.Execute(ss2.str().c_str());
15937 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15939 char buf[11];
15940 snprintf(buf,11,"%u",value);
15942 if(index >= tokens.size())
15943 return;
15945 tokens[index] = buf;
15948 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15950 Tokens tokens;
15951 if(!LoadValuesArrayFromDB(tokens,guid))
15952 return;
15954 if(index >= tokens.size())
15955 return;
15957 char buf[11];
15958 snprintf(buf,11,"%u",value);
15959 tokens[index] = buf;
15961 SaveValuesArrayInDB(tokens,guid);
15964 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15966 uint32 temp;
15967 memcpy(&temp, &value, sizeof(value));
15968 Player::SetUInt32ValueInDB(index, temp, guid);
15971 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15973 Tokens tokens;
15974 if(!LoadValuesArrayFromDB(tokens, guid))
15975 return;
15977 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15978 uint8 race = unit_bytes0 & 0xFF;
15979 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15981 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15982 if(!info)
15983 return;
15985 unit_bytes0 &= ~(0xFF << 16);
15986 unit_bytes0 |= (gender << 16);
15987 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15989 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15990 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15992 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15994 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15995 player_bytes2 &= ~0xFF;
15996 player_bytes2 |= facialHair;
15997 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15999 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
16000 player_bytes3 &= ~0xFF;
16001 player_bytes3 |= gender;
16002 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
16004 SaveValuesArrayInDB(tokens, guid);
16007 void Player::SendAttackSwingNotStanding()
16009 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
16010 GetSession()->SendPacket( &data );
16013 void Player::SendAttackSwingDeadTarget()
16015 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16016 GetSession()->SendPacket( &data );
16019 void Player::SendAttackSwingCantAttack()
16021 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16022 GetSession()->SendPacket( &data );
16025 void Player::SendAttackSwingCancelAttack()
16027 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16028 GetSession()->SendPacket( &data );
16031 void Player::SendAttackSwingBadFacingAttack()
16033 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16034 GetSession()->SendPacket( &data );
16037 void Player::SendAutoRepeatCancel()
16039 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
16040 data.append(GetPackGUID()); // may be it's target guid
16041 GetSession()->SendPacket( &data );
16044 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16046 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16047 data << Area;
16048 data << Experience;
16049 GetSession()->SendPacket(&data);
16052 void Player::SendDungeonDifficulty(bool IsInGroup)
16054 uint8 val = 0x00000001;
16055 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16056 data << (uint32)GetDifficulty();
16057 data << uint32(val);
16058 data << uint32(IsInGroup);
16059 GetSession()->SendPacket(&data);
16062 void Player::SendResetFailedNotify(uint32 mapid)
16064 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16065 data << uint32(mapid);
16066 GetSession()->SendPacket(&data);
16069 /// Reset all solo instances and optionally send a message on success for each
16070 void Player::ResetInstances(uint8 method)
16072 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16074 // we assume that when the difficulty changes, all instances that can be reset will be
16075 uint8 dif = GetDifficulty();
16077 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
16079 InstanceSave *p = itr->second.save;
16080 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16081 if(!entry || !p->CanReset())
16083 ++itr;
16084 continue;
16087 if(method == INSTANCE_RESET_ALL)
16089 // the "reset all instances" method can only reset normal maps
16090 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
16092 ++itr;
16093 continue;
16097 // if the map is loaded, reset it
16098 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
16099 if(map && map->IsDungeon())
16100 ((InstanceMap*)map)->Reset(method);
16102 // since this is a solo instance there should not be any players inside
16103 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16104 SendResetInstanceSuccess(p->GetMapId());
16106 p->DeleteFromDB();
16107 m_boundInstances[dif].erase(itr++);
16109 // the following should remove the instance save from the manager and delete it as well
16110 p->RemovePlayer(this);
16114 void Player::SendResetInstanceSuccess(uint32 MapId)
16116 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16117 data << MapId;
16118 GetSession()->SendPacket(&data);
16121 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16123 // TODO: find what other fail reasons there are besides players in the instance
16124 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16125 data << reason;
16126 data << MapId;
16127 GetSession()->SendPacket(&data);
16130 /*********************************************************/
16131 /*** Update timers ***/
16132 /*********************************************************/
16134 ///checks the 15 afk reports per 5 minutes limit
16135 void Player::UpdateAfkReport(time_t currTime)
16137 if(m_bgAfkReportedTimer <= currTime)
16139 m_bgAfkReportedCount = 0;
16140 m_bgAfkReportedTimer = currTime+5*MINUTE;
16144 void Player::UpdateContestedPvP(uint32 diff)
16146 if(!m_contestedPvPTimer||isInCombat())
16147 return;
16148 if(m_contestedPvPTimer <= diff)
16150 ResetContestedPvP();
16152 else
16153 m_contestedPvPTimer -= diff;
16156 void Player::UpdatePvPFlag(time_t currTime)
16158 if(!IsPvP())
16159 return;
16160 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16161 return;
16163 UpdatePvP(false);
16166 void Player::UpdateDuelFlag(time_t currTime)
16168 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16169 return;
16171 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16172 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16174 duel->startTimer = 0;
16175 duel->startTime = currTime;
16176 duel->opponent->duel->startTimer = 0;
16177 duel->opponent->duel->startTime = currTime;
16180 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16182 if(!pet)
16183 pet = GetPet();
16185 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
16187 //returning of reagents only for players, so best done here
16188 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16189 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16191 if(spellInfo)
16193 for(uint32 i = 0; i < 7; ++i)
16195 if(spellInfo->Reagent[i] > 0)
16197 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16198 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16199 if( msg == EQUIP_ERR_OK )
16201 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16202 if(IsInWorld())
16203 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16208 m_temporaryUnsummonedPetNumber = 0;
16211 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16212 return;
16214 // only if current pet in slot
16215 switch(pet->getPetType())
16217 case MINI_PET:
16218 m_miniPet = 0;
16219 break;
16220 case GUARDIAN_PET:
16221 m_guardianPets.erase(pet->GetGUID());
16222 break;
16223 default:
16224 if(GetPetGUID() == pet->GetGUID())
16225 SetPet(NULL);
16226 break;
16229 pet->CombatStop();
16231 if(returnreagent)
16233 switch(pet->GetEntry())
16235 //warlock pets except imp are removed(?) when logging out
16236 case 1860:
16237 case 1863:
16238 case 417:
16239 case 17252:
16240 mode = PET_SAVE_NOT_IN_SLOT;
16241 break;
16245 pet->SavePetToDB(mode);
16247 pet->CleanupsBeforeDelete();
16248 pet->AddObjectToRemoveList();
16249 pet->m_removed = true;
16251 if(pet->isControlled())
16253 WorldPacket data(SMSG_PET_SPELLS, 8+4);
16254 data << uint64(0);
16255 data << uint32(0);
16256 GetSession()->SendPacket(&data);
16258 if(GetGroup())
16259 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16263 void Player::RemoveMiniPet()
16265 if(Pet* pet = GetMiniPet())
16267 pet->Remove(PET_SAVE_AS_DELETED);
16268 m_miniPet = 0;
16272 Pet* Player::GetMiniPet()
16274 if(!m_miniPet)
16275 return NULL;
16276 return ObjectAccessor::GetPet(m_miniPet);
16279 void Player::RemoveGuardians()
16281 while(!m_guardianPets.empty())
16283 uint64 guid = *m_guardianPets.begin();
16284 if(Pet* pet = ObjectAccessor::GetPet(guid))
16285 pet->Remove(PET_SAVE_AS_DELETED);
16287 m_guardianPets.erase(guid);
16291 bool Player::HasGuardianWithEntry(uint32 entry)
16293 // pet guid middle part is entry (and creature also)
16294 // and in guardian list must be guardians with same entry _always_
16295 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16297 if(Pet* pet = ObjectAccessor::GetPet(*itr))
16298 if (pet->GetEntry() == entry)
16299 return true;
16302 return false;
16305 void Player::Uncharm()
16307 Unit* charm = GetCharm();
16308 if(!charm)
16309 return;
16311 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16312 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16315 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16317 *data << (uint8)msgtype;
16318 *data << (uint32)language;
16319 *data << (uint64)GetGUID();
16320 *data << (uint32)language; //language 2.1.0 ?
16321 *data << (uint64)GetGUID();
16322 *data << (uint32)(text.length()+1);
16323 *data << text;
16324 *data << (uint8)chatTag();
16327 void Player::Say(const std::string& text, const uint32 language)
16329 WorldPacket data(SMSG_MESSAGECHAT, 200);
16330 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16331 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16334 void Player::Yell(const std::string& text, const uint32 language)
16336 WorldPacket data(SMSG_MESSAGECHAT, 200);
16337 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16338 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16341 void Player::TextEmote(const std::string& text)
16343 WorldPacket data(SMSG_MESSAGECHAT, 200);
16344 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16345 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16348 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16350 if (language != LANG_ADDON) // if not addon data
16351 language = LANG_UNIVERSAL; // whispers should always be readable
16353 Player *rPlayer = objmgr.GetPlayer(receiver);
16355 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16356 if(!rPlayer->isDND() || isGameMaster())
16358 WorldPacket data(SMSG_MESSAGECHAT, 200);
16359 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16360 rPlayer->GetSession()->SendPacket(&data);
16362 data.Initialize(SMSG_MESSAGECHAT, 200);
16363 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16364 GetSession()->SendPacket(&data);
16366 else
16368 // announce to player that player he is whispering to is dnd and cannot receive his message
16369 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16372 if(!isAcceptWhispers())
16374 SetAcceptWhispers(true);
16375 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16378 // announce to player that player he is whispering to is afk
16379 if(rPlayer->isAFK())
16380 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16382 // if player whisper someone, auto turn of dnd to be able to receive an answer
16383 if(isDND() && !rPlayer->isGameMaster())
16384 ToggleDND();
16387 void Player::PetSpellInitialize()
16389 Pet* pet = GetPet();
16391 if(!pet)
16392 return;
16394 sLog.outDebug("Pet Spells Groups");
16396 CharmInfo *charmInfo = pet->GetCharmInfo();
16398 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
16399 data << uint64(pet->GetGUID());
16400 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16401 data << uint32(0);
16402 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16404 // action bar loop
16405 charmInfo->BuildActionBar(&data);
16407 size_t spellsCountPos = data.wpos();
16409 // spells count
16410 uint8 addlist = 0;
16411 data << uint8(addlist); // placeholder
16413 if (pet->IsPermanentPetFor(this))
16415 // spells loop
16416 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16418 if(itr->second.state == PETSPELL_REMOVED)
16419 continue;
16421 data << uint16(itr->first);
16422 data << uint16(itr->second.active); // pet spell active state isn't boolean
16423 ++addlist;
16427 data.put<uint8>(spellsCountPos, addlist);
16429 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16430 data << uint8(cooldownsCount);
16432 time_t curTime = time(NULL);
16434 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16436 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
16438 data << uint16(itr->first); // spellid
16439 data << uint16(0); // spell category?
16440 data << uint32(cooldown); // cooldown
16441 data << uint32(0); // category cooldown
16444 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.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(0); // cooldown
16451 data << uint32(cooldown); // category cooldown
16454 GetSession()->SendPacket(&data);
16457 void Player::PossessSpellInitialize()
16459 Unit* charm = GetCharm();
16461 if(!charm)
16462 return;
16464 CharmInfo *charmInfo = charm->GetCharmInfo();
16466 if(!charmInfo)
16468 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16469 return;
16472 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
16473 data << uint64(charm->GetGUID());
16474 data << uint32(0);
16475 data << uint32(0);
16476 data << uint32(0);
16478 charmInfo->BuildActionBar(&data);
16480 data << uint8(0); // spells count
16481 data << uint8(0); // cooldowns count
16483 GetSession()->SendPacket(&data);
16486 void Player::CharmSpellInitialize()
16488 Unit* charm = GetCharm();
16490 if(!charm)
16491 return;
16493 CharmInfo *charmInfo = charm->GetCharmInfo();
16494 if(!charmInfo)
16496 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
16497 return;
16500 uint8 addlist = 0;
16502 if(charm->GetTypeId() != TYPEID_PLAYER)
16504 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16506 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16508 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16510 if(charmInfo->GetCharmSpell(i)->spellId)
16511 ++addlist;
16516 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+4*addlist+1);
16517 data << uint64(charm->GetGUID());
16518 data << uint32(0);
16519 data << uint32(0);
16521 if(charm->GetTypeId() != TYPEID_PLAYER)
16522 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16523 else
16524 data << uint8(0) << uint8(0) << uint16(0);
16526 charmInfo->BuildActionBar(&data);
16528 data << uint8(addlist);
16530 if(addlist)
16532 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16534 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16535 if(cspell->spellId)
16537 data << uint16(cspell->spellId);
16538 data << uint16(cspell->active);
16543 data << uint8(0); // cooldowns count
16545 GetSession()->SendPacket(&data);
16548 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16550 if (!mod || !spellInfo)
16551 return false;
16553 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16555 // prevent apply to any spell except spell that trigger expire
16556 if(spell)
16558 if(mod->lastAffected != spell)
16559 return false;
16561 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16562 return false;
16565 return spellmgr.IsAffectedByMod(spellInfo, mod);
16568 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16570 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16572 for(int eff=0;eff<96;++eff)
16574 uint64 _mask = 0;
16575 uint64 _mask2= 0;
16576 if (eff<64) _mask = uint64(1) << (eff- 0);
16577 else _mask2= uint64(1) << (eff-64);
16578 if ( mod->mask & _mask || mod->mask2 & _mask2)
16580 int32 val = 0;
16581 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16583 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16584 val += (*itr)->value;
16586 val += apply ? mod->value : -(mod->value);
16587 WorldPacket data(Opcode, (1+1+4));
16588 data << uint8(eff);
16589 data << uint8(mod->op);
16590 data << int32(val);
16591 SendDirectMessage(&data);
16595 if (apply)
16596 m_spellMods[mod->op].push_back(mod);
16597 else
16599 if (mod->charges == -1)
16600 --m_SpellModRemoveCount;
16601 m_spellMods[mod->op].remove(mod);
16602 delete mod;
16606 void Player::RemoveSpellMods(Spell const* spell)
16608 if(!spell || (m_SpellModRemoveCount == 0))
16609 return;
16611 for(int i=0;i<MAX_SPELLMOD;++i)
16613 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16615 SpellModifier *mod = *itr;
16616 ++itr;
16618 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16620 RemoveAurasDueToSpell(mod->spellId);
16621 if (m_spellMods[i].empty())
16622 break;
16623 else
16624 itr = m_spellMods[i].begin();
16630 // send Proficiency
16631 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16633 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16634 data << pr1 << pr2;
16635 GetSession()->SendPacket (&data);
16638 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16640 QueryResult *result = NULL;
16641 if(type==10)
16642 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16643 else
16644 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16645 if(result)
16647 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.
16648 { // and SendPetitionQueryOpcode reads data from the DB
16649 Field *fields = result->Fetch();
16650 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16651 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16653 // send update if charter owner in game
16654 Player* owner = objmgr.GetPlayer(ownerguid);
16655 if(owner)
16656 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16658 } while ( result->NextRow() );
16660 delete result;
16662 if(type==10)
16663 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16664 else
16665 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16668 CharacterDatabase.BeginTransaction();
16669 if(type == 10)
16671 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16672 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16674 else
16676 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16677 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16679 CharacterDatabase.CommitTransaction();
16682 void Player::LeaveAllArenaTeams(uint64 guid)
16684 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));
16685 if(!result)
16686 return;
16690 Field *fields = result->Fetch();
16691 uint32 at_id = fields[0].GetUInt32();
16692 if(at_id != 0)
16694 ArenaTeam * at = objmgr.GetArenaTeamById(at_id);
16695 if(at)
16696 at->DelMember(guid);
16698 } while (result->NextRow());
16700 delete result;
16703 void Player::SetRestBonus (float rest_bonus_new)
16705 // Prevent resting on max level
16706 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16707 rest_bonus_new = 0;
16709 if(rest_bonus_new < 0)
16710 rest_bonus_new = 0;
16712 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16714 if(rest_bonus_new > rest_bonus_max)
16715 m_rest_bonus = rest_bonus_max;
16716 else
16717 m_rest_bonus = rest_bonus_new;
16719 // update data for client
16720 if(m_rest_bonus>10)
16721 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16722 else if(m_rest_bonus<=1)
16723 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16725 //RestTickUpdate
16726 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16729 void Player::HandleStealthedUnitsDetection()
16731 std::list<Unit*> stealthedUnits;
16733 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16734 Cell cell(p);
16735 cell.data.Part.reserved = ALL_DISTRICT;
16736 cell.SetNoCreate();
16738 MaNGOS::AnyStealthedCheck u_check;
16739 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
16741 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16742 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16744 CellLock<GridReadGuard> cell_lock(cell, p);
16745 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16746 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16748 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16750 if((*i)==this)
16752 i = stealthedUnits.erase(i);
16753 continue;
16756 if ((*i)->isVisibleForOrDetect(this,true))
16759 (*i)->SendUpdateToPlayer(this);
16760 m_clientGUIDs.insert((*i)->GetGUID());
16762 #ifdef MANGOS_DEBUG
16763 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16764 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16765 #endif
16767 // target aura duration for caster show only if target exist at caster client
16768 // send data at target visibility change (adding to client)
16769 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16770 SendAurasForTarget(*i);
16772 i = stealthedUnits.erase(i);
16773 continue;
16776 ++i;
16780 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
16782 if(nodes.size() < 2)
16783 return false;
16785 // 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
16786 if(GetSession()->isLogingOut() || isInCombat())
16788 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16789 data << uint32(ERR_TAXIPLAYERBUSY);
16790 GetSession()->SendPacket(&data);
16791 return false;
16794 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16795 return false;
16797 // taximaster case
16798 if(npc)
16800 // not let cheating with start flight mounted
16801 if(IsMounted())
16803 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16804 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16805 GetSession()->SendPacket(&data);
16806 return false;
16809 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16811 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16812 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16813 GetSession()->SendPacket(&data);
16814 return false;
16817 // 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
16818 if(IsNonMeleeSpellCasted(false))
16820 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16821 data << uint32(ERR_TAXIPLAYERBUSY);
16822 GetSession()->SendPacket(&data);
16823 return false;
16826 // cast case or scripted call case
16827 else
16829 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
16831 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16832 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
16834 if(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id != spellid)
16835 InterruptSpell(CURRENT_GENERIC_SPELL,false);
16837 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
16839 if(m_currentSpells[CURRENT_CHANNELED_SPELL] && m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id != spellid)
16840 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
16843 uint32 sourcenode = nodes[0];
16845 // starting node too far away (cheat?)
16846 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16847 if (!node)
16849 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16850 data << uint32(ERR_TAXINOSUCHPATH);
16851 GetSession()->SendPacket(&data);
16852 return false;
16855 // check node starting pos data set case if provided
16856 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
16858 if (node->map_id != GetMapId() ||
16859 (node->x - GetPositionX())*(node->x - GetPositionX())+
16860 (node->y - GetPositionY())*(node->y - GetPositionY())+
16861 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16862 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
16864 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16865 data << uint32(ERR_TAXITOOFARAWAY);
16866 GetSession()->SendPacket(&data);
16867 return false;
16870 // node must have pos if taxi master case (npc != NULL)
16871 else if (npc)
16873 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16874 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16875 GetSession()->SendPacket(&data);
16876 return false;
16879 // Prepare to flight start now
16881 // stop combat at start taxi flight if any
16882 CombatStop();
16884 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16885 TradeCancel(true);
16887 // clean not finished taxi path if any
16888 m_taxi.ClearTaxiDestinations();
16890 // 0 element current node
16891 m_taxi.AddTaxiDestination(sourcenode);
16893 // fill destinations path tail
16894 uint32 sourcepath = 0;
16895 uint32 totalcost = 0;
16897 uint32 prevnode = sourcenode;
16898 uint32 lastnode = 0;
16900 for(uint32 i = 1; i < nodes.size(); ++i)
16902 uint32 path, cost;
16904 lastnode = nodes[i];
16905 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16907 if(!path)
16909 m_taxi.ClearTaxiDestinations();
16910 return false;
16913 totalcost += cost;
16915 if(prevnode == sourcenode)
16916 sourcepath = path;
16918 m_taxi.AddTaxiDestination(lastnode);
16920 prevnode = lastnode;
16923 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
16924 uint16 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam(), npc == NULL);
16926 // in spell case allow 0 model
16927 if (mount_id == 0 && spellid == 0 || sourcepath == 0)
16929 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16930 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16931 GetSession()->SendPacket(&data);
16932 m_taxi.ClearTaxiDestinations();
16933 return false;
16936 uint32 money = GetMoney();
16938 if (npc)
16939 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16941 if(money < totalcost)
16943 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16944 data << uint32(ERR_TAXINOTENOUGHMONEY);
16945 GetSession()->SendPacket(&data);
16946 m_taxi.ClearTaxiDestinations();
16947 return false;
16950 //Checks and preparations done, DO FLIGHT
16951 ModifyMoney(-(int32)totalcost);
16952 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
16953 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
16955 // prevent stealth flight
16956 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16958 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16959 data << uint32(ERR_TAXIOK);
16960 GetSession()->SendPacket(&data);
16962 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16964 GetSession()->SendDoFlight(mount_id, sourcepath);
16966 return true;
16969 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
16971 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
16972 if(!entry)
16973 return false;
16975 std::vector<uint32> nodes;
16977 nodes.resize(2);
16978 nodes[0] = entry->from;
16979 nodes[1] = entry->to;
16981 return ActivateTaxiPathTo(nodes,NULL,spellid);
16984 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16986 // last check 2.0.10
16987 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16988 data << GetGUID();
16989 data << uint8(0x0); // flags (0x1, 0x2)
16990 time_t curTime = time(NULL);
16991 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16993 if (itr->second->state == PLAYERSPELL_REMOVED)
16994 continue;
16995 uint32 unSpellId = itr->first;
16996 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16997 if (!spellInfo)
16999 ASSERT(spellInfo);
17000 continue;
17003 // Not send cooldown for this spells
17004 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17005 continue;
17007 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17009 data << uint32(unSpellId);
17010 data << uint32(unTimeMs); // in m.secs
17011 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17014 GetSession()->SendPacket(&data);
17017 void Player::InitDataForForm(bool reapplyMods)
17019 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17020 if(ssEntry && ssEntry->attackSpeed)
17022 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17023 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17024 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17026 else
17027 SetRegularAttackTime();
17029 switch(m_form)
17031 case FORM_CAT:
17033 if(getPowerType()!=POWER_ENERGY)
17034 setPowerType(POWER_ENERGY);
17035 break;
17037 case FORM_BEAR:
17038 case FORM_DIREBEAR:
17040 if(getPowerType()!=POWER_RAGE)
17041 setPowerType(POWER_RAGE);
17042 break;
17044 default: // 0, for example
17046 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17047 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17048 setPowerType(Powers(cEntry->powerType));
17049 break;
17053 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17054 if (!reapplyMods)
17055 UpdateEquipSpellsAtFormChange();
17057 UpdateAttackPowerAndDamage();
17058 UpdateAttackPowerAndDamage(true);
17061 // Return true is the bought item has a max count to force refresh of window by caller
17062 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
17064 // cheating attempt
17065 if(count < 1) count = 1;
17067 if(!isAlive())
17068 return false;
17070 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
17071 if( !pProto )
17073 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17074 return false;
17077 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17078 if (!pCreature)
17080 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17081 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17082 return false;
17085 VendorItemData const* vItems = pCreature->GetVendorItems();
17086 if(!vItems || vItems->Empty())
17088 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17089 return false;
17092 size_t vendor_slot = vItems->FindItemSlot(item);
17093 if(vendor_slot >= vItems->GetItemCount())
17095 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17096 return false;
17099 VendorItem const* crItem = vItems->m_items[vendor_slot];
17101 // check current item amount if it limited
17102 if( crItem->maxcount != 0 )
17104 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17106 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17107 return false;
17111 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17113 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17114 return false;
17117 if(crItem->ExtendedCost)
17119 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17120 if(!iece)
17122 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17123 return false;
17126 // honor points price
17127 if(GetHonorPoints() < (iece->reqhonorpoints * count))
17129 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17130 return false;
17133 // arena points price
17134 if(GetArenaPoints() < (iece->reqarenapoints * count))
17136 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17137 return false;
17140 // item base price
17141 for (uint8 i = 0; i < 5; ++i)
17143 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17145 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17146 return false;
17150 // check for personal arena rating requirement
17151 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
17153 // probably not the proper equip err
17154 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17155 return false;
17159 uint32 price = pProto->BuyPrice * count;
17161 // reputation discount
17162 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17164 if( GetMoney() < price )
17166 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17167 return false;
17170 uint8 bag = 0; // init for case invalid bagGUID
17172 if (bagguid != NULL_BAG && slot != NULL_SLOT)
17174 Bag *pBag;
17175 if( bagguid == GetGUID() )
17177 bag = INVENTORY_SLOT_BAG_0;
17179 else
17181 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;++i)
17183 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
17184 if( pBag )
17186 if( bagguid == pBag->GetGUID() )
17188 bag = i;
17189 break;
17196 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
17198 ItemPosCountVec dest;
17199 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17200 if( msg != EQUIP_ERR_OK )
17202 SendEquipError( msg, NULL, NULL );
17203 return false;
17206 ModifyMoney( -(int32)price );
17207 if(crItem->ExtendedCost) // case for new honor system
17209 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17210 if(iece->reqhonorpoints)
17211 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17212 if(iece->reqarenapoints)
17213 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17214 for (uint8 i = 0; i < 5; ++i)
17216 if(iece->reqitem[i])
17217 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
17221 if(Item *it = StoreNewItem( dest, item, true ))
17223 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17225 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17226 data << pCreature->GetGUID();
17227 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17228 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17229 data << (uint32)count;
17230 GetSession()->SendPacket(&data);
17232 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17235 else if( IsEquipmentPos( bag, slot ) )
17237 if(pProto->BuyCount * count != 1)
17239 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
17240 return false;
17243 uint16 dest;
17244 uint8 msg = CanEquipNewItem( slot, dest, item, false );
17245 if( msg != EQUIP_ERR_OK )
17247 SendEquipError( msg, NULL, NULL );
17248 return false;
17251 ModifyMoney( -(int32)price );
17252 if(crItem->ExtendedCost) // case for new honor system
17254 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17255 if(iece->reqhonorpoints)
17256 ModifyHonorPoints( - int32(iece->reqhonorpoints));
17257 if(iece->reqarenapoints)
17258 ModifyArenaPoints( - int32(iece->reqarenapoints));
17259 for (uint8 i = 0; i < 5; ++i)
17261 if(iece->reqitem[i])
17262 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17266 if(Item *it = EquipNewItem( dest, item, true ))
17268 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17270 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17271 data << pCreature->GetGUID();
17272 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17273 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17274 data << (uint32)count;
17275 GetSession()->SendPacket(&data);
17277 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17279 AutoUnequipOffhandIfNeed();
17282 else
17284 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17285 return false;
17288 return crItem->maxcount!=0;
17291 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17293 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17294 // the personal rating of the arena team must match the required limit as well
17295 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17296 uint32 max_personal_rating = 0;
17297 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17299 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17301 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17302 uint32 t_rating = at->GetRating();
17303 p_rating = p_rating<t_rating? p_rating : t_rating;
17304 if(max_personal_rating < p_rating)
17305 max_personal_rating = p_rating;
17308 return max_personal_rating;
17311 void Player::UpdateHomebindTime(uint32 time)
17313 // GMs never get homebind timer online
17314 if (m_InstanceValid || isGameMaster())
17316 if(m_HomebindTimer) // instance valid, but timer not reset
17318 // hide reminder
17319 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17320 data << uint32(0);
17321 data << uint32(0);
17322 GetSession()->SendPacket(&data);
17324 // instance is valid, reset homebind timer
17325 m_HomebindTimer = 0;
17327 else if (m_HomebindTimer > 0)
17329 if (time >= m_HomebindTimer)
17331 // teleport to homebind location
17332 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17334 else
17335 m_HomebindTimer -= time;
17337 else
17339 // instance is invalid, start homebind timer
17340 m_HomebindTimer = 60000;
17341 // send message to player
17342 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17343 data << m_HomebindTimer;
17344 data << uint32(1);
17345 GetSession()->SendPacket(&data);
17346 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17350 void Player::UpdatePvP(bool state, bool ovrride)
17352 if(!state || ovrride)
17354 SetPvP(state);
17355 pvpInfo.endTimer = 0;
17357 else
17359 if(pvpInfo.endTimer != 0)
17360 pvpInfo.endTimer = time(NULL);
17361 else
17362 SetPvP(state);
17366 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
17368 // init cooldown values
17369 uint32 cat = 0;
17370 int32 rec = -1;
17371 int32 catrec = -1;
17373 // some special item spells without correct cooldown in SpellInfo
17374 // cooldown information stored in item prototype
17375 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17377 if(itemId)
17379 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
17381 for(int idx = 0; idx < 5; ++idx)
17383 if(proto->Spells[idx].SpellId == spellInfo->Id)
17385 cat = proto->Spells[idx].SpellCategory;
17386 rec = proto->Spells[idx].SpellCooldown;
17387 catrec = proto->Spells[idx].SpellCategoryCooldown;
17388 break;
17394 // if no cooldown found above then base at DBC data
17395 if(rec < 0 && catrec < 0)
17397 cat = spellInfo->Category;
17398 rec = spellInfo->RecoveryTime;
17399 catrec = spellInfo->CategoryRecoveryTime;
17402 time_t curTime = time(NULL);
17404 time_t catrecTime;
17405 time_t recTime;
17407 // overwrite time for selected category
17408 if(infinityCooldown)
17410 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17411 // but not allow ignore until reset or re-login
17412 catrecTime = catrec > 0 ? curTime+MONTH : 0;
17413 recTime = rec > 0 ? curTime+MONTH : catrecTime;
17415 else
17417 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17418 // prevent 0 cooldowns set by another way
17419 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
17420 rec = GetAttackTime(RANGED_ATTACK);
17422 // Now we have cooldown data (if found any), time to apply mods
17423 if(rec > 0)
17424 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
17426 if(catrec > 0)
17427 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
17429 // replace negative cooldowns by 0
17430 if (rec < 0) rec = 0;
17431 if (catrec < 0) catrec = 0;
17433 // no cooldown after applying spell mods
17434 if( rec == 0 && catrec == 0)
17435 return;
17437 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
17438 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
17441 // self spell cooldown
17442 if(recTime > 0)
17443 AddSpellCooldown(spellInfo->Id, itemId, recTime);
17445 // category spells
17446 if (cat && catrec > 0)
17448 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
17449 if(i_scstore != sSpellCategoryStore.end())
17451 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
17453 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
17454 continue;
17456 AddSpellCooldown(*i_scset, itemId, catrecTime);
17462 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17464 SpellCooldown sc;
17465 sc.end = end_time;
17466 sc.itemid = itemid;
17467 m_spellCooldowns[spellid] = sc;
17470 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
17472 // start cooldowns at server side, if any
17473 AddSpellAndCategoryCooldowns(spellInfo,itemId,spell);
17475 // Send activate cooldown timer (possible 0) at client side
17476 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17477 data << spellInfo->Id;
17478 data << GetGUID();
17479 SendDirectMessage(&data);
17482 void Player::UpdatePotionCooldown(Spell* spell)
17484 // no potion used i combat or still in combat
17485 if(!m_lastPotionId || isInCombat())
17486 return;
17488 // Call not from spell cast, send cooldown event for item spells if no in combat
17489 if(!spell)
17491 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17492 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
17493 for(int idx = 0; idx < 5; ++idx)
17494 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
17495 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
17496 SendCooldownEvent(spellInfo,m_lastPotionId);
17498 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17499 else
17500 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
17502 m_lastPotionId = 0;
17505 //slot to be excluded while counting
17506 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17508 if(!enchantmentcondition)
17509 return true;
17511 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17513 if(!Condition)
17514 return true;
17516 uint8 curcount[4] = {0, 0, 0, 0};
17518 //counting current equipped gem colors
17519 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17521 if(i == slot)
17522 continue;
17523 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17524 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17526 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17528 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17529 if(!enchant_id)
17530 continue;
17532 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17533 if(!enchantEntry)
17534 continue;
17536 uint32 gemid = enchantEntry->GemID;
17537 if(!gemid)
17538 continue;
17540 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17541 if(!gemProto)
17542 continue;
17544 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17545 if(!gemProperty)
17546 continue;
17548 uint8 GemColor = gemProperty->color;
17550 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17552 if(tmpcolormask & GemColor)
17553 ++curcount[b];
17559 bool activate = true;
17561 for(int i = 0; i < 5; ++i)
17563 if(!Condition->Color[i])
17564 continue;
17566 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17568 // if have <CompareColor> use them as count, else use <value> from Condition
17569 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17571 switch(Condition->Comparator[i])
17573 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17574 activate &= (_cur_gem < _cmp_gem) ? true : false;
17575 break;
17576 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17577 activate &= (_cur_gem > _cmp_gem) ? true : false;
17578 break;
17579 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17580 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17581 break;
17585 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");
17587 return activate;
17590 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17592 //cycle all equipped items
17593 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17595 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17596 if(slot == exceptslot)
17597 continue;
17599 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17601 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17602 continue;
17604 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17606 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17607 if(!enchant_id)
17608 continue;
17610 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17611 if(!enchantEntry)
17612 continue;
17614 uint32 condition = enchantEntry->EnchantmentCondition;
17615 if(condition)
17617 //was enchant active with/without item?
17618 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17619 //should it now be?
17620 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17622 // ignore item gem conditions
17623 //if state changed, (dis)apply enchant
17624 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17631 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17632 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17634 //cycle all equipped items
17635 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17637 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17638 if(slot == exceptslot)
17639 continue;
17641 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17643 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17644 continue;
17646 //cycle all (gem)enchants
17647 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17649 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17650 if(!enchant_id) //if no enchant go to next enchant(slot)
17651 continue;
17653 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17654 if(!enchantEntry)
17655 continue;
17657 //only metagems to be (de)activated, so only enchants with condition
17658 uint32 condition = enchantEntry->EnchantmentCondition;
17659 if(condition)
17660 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17665 void Player::LeaveBattleground(bool teleportToEntryPoint)
17667 if(BattleGround *bg = GetBattleGround())
17669 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17671 // call after remove to be sure that player resurrected for correct cast
17672 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
17674 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
17675 CastSpell(this, 26013, true); // Deserter
17680 bool Player::CanJoinToBattleground() const
17682 // check Deserter debuff
17683 if(GetDummyAura(26013))
17684 return false;
17686 return true;
17689 bool Player::CanReportAfkDueToLimit()
17691 // a player can complain about 15 people per 5 minutes
17692 if(m_bgAfkReportedCount >= 15)
17693 return false;
17694 ++m_bgAfkReportedCount;
17695 return true;
17698 ///This player has been blamed to be inactive in a battleground
17699 void Player::ReportedAfkBy(Player* reporter)
17701 BattleGround *bg = GetBattleGround();
17702 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17703 return;
17705 // check if player has 'Idle' or 'Inactive' debuff
17706 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17708 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17709 // 3 players have to complain to apply debuff
17710 if(m_bgAfkReporter.size() >= 3)
17712 // cast 'Idle' spell
17713 CastSpell(this, 43680, true);
17714 m_bgAfkReporter.clear();
17719 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17721 // gamemaster in GM mode see all, including ghosts
17722 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17723 return true;
17725 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17726 if (InBattleGround())
17728 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17729 return false;
17730 return true;
17733 // Live player see live player or dead player with not realized corpse
17734 if(pl->isAlive() || pl->m_deathTimer > 0)
17736 return isAlive() || m_deathTimer > 0;
17739 // Ghost see other friendly ghosts, that's for sure
17740 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17741 return true;
17743 // Dead player see live players near own corpse
17744 if(isAlive())
17746 Corpse *corpse = pl->GetCorpse();
17747 if(corpse)
17749 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17750 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17751 return true;
17755 // and not see any other
17756 return false;
17759 bool Player::IsVisibleGloballyFor( Player* u ) const
17761 if(!u)
17762 return false;
17764 // Always can see self
17765 if (u==this)
17766 return true;
17768 // Visible units, always are visible for all players
17769 if (GetVisibility() == VISIBILITY_ON)
17770 return true;
17772 // GMs are visible for higher gms (or players are visible for gms)
17773 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17774 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17776 // non faction visibility non-breakable for non-GMs
17777 if (GetVisibility() == VISIBILITY_OFF)
17778 return false;
17780 // non-gm stealth/invisibility not hide from global player lists
17781 return true;
17784 void Player::UpdateVisibilityOf(WorldObject* target)
17786 if(HaveAtClient(target))
17788 if(!target->isVisibleForInState(this,true))
17790 target->DestroyForPlayer(this);
17791 m_clientGUIDs.erase(target->GetGUID());
17793 #ifdef MANGOS_DEBUG
17794 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17795 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17796 #endif
17799 else
17801 if(target->isVisibleForInState(this,false))
17803 target->SendUpdateToPlayer(this);
17804 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17805 m_clientGUIDs.insert(target->GetGUID());
17807 #ifdef MANGOS_DEBUG
17808 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17809 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17810 #endif
17812 // target aura duration for caster show only if target exist at caster client
17813 // send data at target visibility change (adding to client)
17814 if(target!=this && target->isType(TYPEMASK_UNIT))
17815 SendAurasForTarget((Unit*)target);
17817 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17818 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17823 template<class T>
17824 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17826 s64.insert(target->GetGUID());
17829 template<>
17830 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17832 if(!target->IsTransport())
17833 s64.insert(target->GetGUID());
17836 template<class T>
17837 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17839 if(HaveAtClient(target))
17841 if(!target->isVisibleForInState(this,true))
17843 target->BuildOutOfRangeUpdateBlock(&data);
17844 m_clientGUIDs.erase(target->GetGUID());
17846 #ifdef MANGOS_DEBUG
17847 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17848 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));
17849 #endif
17852 else
17854 if(target->isVisibleForInState(this,false))
17856 visibleNow.insert(target);
17857 target->BuildUpdate(data_updates);
17858 target->BuildCreateUpdateBlockForPlayer(&data, this);
17859 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17861 #ifdef MANGOS_DEBUG
17862 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17863 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));
17864 #endif
17869 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17870 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17871 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17872 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17873 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17875 void Player::InitPrimaryProffesions()
17877 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17880 void Player::SendComboPoints()
17882 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17883 if (combotarget)
17885 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17886 data.append(combotarget->GetPackGUID());
17887 data << uint8(m_comboPoints);
17888 GetSession()->SendPacket(&data);
17892 void Player::AddComboPoints(Unit* target, int8 count)
17894 if(!count)
17895 return;
17897 // without combo points lost (duration checked in aura)
17898 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17900 if(target->GetGUID() == m_comboTarget)
17902 m_comboPoints += count;
17904 else
17906 if(m_comboTarget)
17907 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
17908 target2->RemoveComboPointHolder(GetGUIDLow());
17910 m_comboTarget = target->GetGUID();
17911 m_comboPoints = count;
17913 target->AddComboPointHolder(GetGUIDLow());
17916 if (m_comboPoints > 5) m_comboPoints = 5;
17917 if (m_comboPoints < 0) m_comboPoints = 0;
17919 SendComboPoints();
17922 void Player::ClearComboPoints()
17924 if(!m_comboTarget)
17925 return;
17927 // without combopoints lost (duration checked in aura)
17928 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17930 m_comboPoints = 0;
17932 SendComboPoints();
17934 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17935 target->RemoveComboPointHolder(GetGUIDLow());
17937 m_comboTarget = 0;
17940 void Player::SetGroup(Group *group, int8 subgroup)
17942 if(group == NULL)
17943 m_group.unlink();
17944 else
17946 // never use SetGroup without a subgroup unless you specify NULL for group
17947 assert(subgroup >= 0);
17948 m_group.link(group, this);
17949 m_group.setSubGroup((uint8)subgroup);
17953 void Player::SendInitialPacketsBeforeAddToMap()
17955 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17956 data << uint32(0); // unknown, may be rest state time or experience
17957 GetSession()->SendPacket(&data);
17959 // Homebind
17960 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17961 data << m_homebindX << m_homebindY << m_homebindZ;
17962 data << (uint32) m_homebindMapId;
17963 data << (uint32) m_homebindZoneId;
17964 GetSession()->SendPacket(&data);
17966 // SMSG_SET_PROFICIENCY
17967 // SMSG_UPDATE_AURA_DURATION
17969 // tutorial stuff
17970 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17971 for (int i = 0; i < 8; ++i)
17972 data << uint32( GetTutorialInt(i) );
17973 GetSession()->SendPacket(&data);
17975 SendInitialSpells();
17977 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17978 data << uint32(0); // count, for(count) uint32;
17979 GetSession()->SendPacket(&data);
17981 SendInitialActionButtons();
17982 m_reputationMgr.SendInitialReputations();
17983 m_achievementMgr.SendAllAchievementData();
17985 // update zone
17986 uint32 newzone, newarea;
17987 GetZoneAndAreaId(newzone,newarea);
17988 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
17990 // SMSG_SET_AURA_SINGLE
17992 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17993 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17994 data << (float)0.01666667f; // game speed
17995 GetSession()->SendPacket( &data );
17997 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17998 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17999 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
18001 m_mover = this;
18004 void Player::SendInitialPacketsAfterAddToMap()
18006 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18007 data << uint32(0x00000000); // on blizz it increments periodically
18008 GetSession()->SendPacket(&data);
18010 CastSpell(this, 836, true); // LOGINEFFECT
18012 // set some aura effects that send packet to player client after add player to map
18013 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18014 // same auras state lost at far teleport, send it one more time in this case also
18015 static const AuraType auratypes[] =
18017 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18018 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18019 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18021 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18023 Unit::AuraList const& auraList = GetAurasByType(*itr);
18024 if(!auraList.empty())
18025 auraList.front()->ApplyModifier(true,true);
18028 if(HasAuraType(SPELL_AURA_MOD_STUN))
18029 SetMovement(MOVE_ROOT);
18031 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18032 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18034 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18035 data2.append(GetPackGUID());
18036 data2 << (uint32)2;
18037 SendMessageToSet(&data2,true);
18040 SendAurasForTarget(this);
18041 SendEnchantmentDurations(); // must be after add to map
18042 SendItemDurations(); // must be after add to map
18045 void Player::SendUpdateToOutOfRangeGroupMembers()
18047 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18048 return;
18049 if(Group* group = GetGroup())
18050 group->UpdatePlayerOutOfRange(this);
18052 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18053 m_auraUpdateMask = 0;
18054 if(Pet *pet = GetPet())
18055 pet->ResetAuraUpdateMask();
18058 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18060 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18061 data << uint32(mapid);
18062 data << uint8(reason); // transfer abort reason
18063 switch(reason)
18065 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18066 case TRANSFER_ABORT_DIFFICULTY:
18067 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18068 data << uint8(arg);
18069 break;
18071 GetSession()->SendPacket(&data);
18074 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
18076 // type of warning, based on the time remaining until reset
18077 uint32 type;
18078 if(time > 3600)
18079 type = RAID_INSTANCE_WELCOME;
18080 else if(time > 900 && time <= 3600)
18081 type = RAID_INSTANCE_WARNING_HOURS;
18082 else if(time > 300 && time <= 900)
18083 type = RAID_INSTANCE_WARNING_MIN;
18084 else
18085 type = RAID_INSTANCE_WARNING_MIN_SOON;
18086 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
18087 data << uint32(type);
18088 data << uint32(mapid);
18089 data << uint32(time);
18090 GetSession()->SendPacket(&data);
18093 void Player::ApplyEquipCooldown( Item * pItem )
18095 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18097 _Spell const& spellData = pItem->GetProto()->Spells[i];
18099 // no spell
18100 if( !spellData.SpellId )
18101 continue;
18103 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18104 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18105 continue;
18107 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18109 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18110 data << pItem->GetGUID();
18111 data << uint32(spellData.SpellId);
18112 GetSession()->SendPacket(&data);
18116 void Player::resetSpells()
18118 // not need after this call
18119 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
18121 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
18122 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
18125 // make full copy of map (spells removed and marked as deleted at another spell remove
18126 // and we can't use original map for safe iterative with visit each spell at loop end
18127 PlayerSpellMap smap = GetSpellMap();
18129 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
18130 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
18132 learnDefaultSpells();
18133 learnQuestRewardedSpells();
18136 void Player::learnDefaultSpells()
18138 // learn default race/class spells
18139 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
18140 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
18142 uint32 tspell = *itr;
18143 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
18144 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18145 addSpell(tspell,true,true,true,false);
18146 else // but send in normal spell in game learn case
18147 learnSpell(tspell,true);
18151 void Player::learnQuestRewardedSpells(Quest const* quest)
18153 uint32 spell_id = quest->GetRewSpellCast();
18155 // skip quests without rewarded spell
18156 if( !spell_id )
18157 return;
18159 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
18160 if(!spellInfo)
18161 return;
18163 // check learned spells state
18164 bool found = false;
18165 for(int i=0; i < 3; ++i)
18167 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
18169 found = true;
18170 break;
18174 // skip quests with not teaching spell or already known spell
18175 if(!found)
18176 return;
18178 // prevent learn non first rank unknown profession and second specialization for same profession)
18179 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
18180 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
18182 // not have first rank learned (unlearned prof?)
18183 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
18184 if( !HasSpell(first_spell) )
18185 return;
18187 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
18188 if(!learnedInfo)
18189 return;
18191 // specialization
18192 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
18194 // search other specialization for same prof
18195 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
18197 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
18198 continue;
18200 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
18201 if(!itrInfo)
18202 return;
18204 // compare only specializations
18205 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
18206 continue;
18208 // compare same chain spells
18209 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
18210 continue;
18212 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18213 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
18214 return;
18219 CastSpell( this, spell_id, true);
18222 void Player::learnQuestRewardedSpells()
18224 // learn spells received from quest completing
18225 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
18227 // skip no rewarded quests
18228 if(!itr->second.m_rewarded)
18229 continue;
18231 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
18232 if( !quest )
18233 continue;
18235 learnQuestRewardedSpells(quest);
18239 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
18241 uint32 raceMask = getRaceMask();
18242 uint32 classMask = getClassMask();
18243 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
18245 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
18246 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
18247 continue;
18248 // Check race if set
18249 if (pAbility->racemask && !(pAbility->racemask & raceMask))
18250 continue;
18251 // Check class if set
18252 if (pAbility->classmask && !(pAbility->classmask & classMask))
18253 continue;
18255 if (sSpellStore.LookupEntry(pAbility->spellId))
18257 // need unlearn spell
18258 if (skill_value < pAbility->req_skill_value)
18259 removeSpell(pAbility->spellId);
18260 // need learn
18261 else if (!IsInWorld())
18262 addSpell(pAbility->spellId,true,true,true,false);
18263 else
18264 learnSpell(pAbility->spellId,true);
18269 void Player::SendAurasForTarget(Unit *target)
18271 if(target->GetVisibleAuras()->empty()) // speedup things
18272 return;
18274 WorldPacket data(SMSG_AURA_UPDATE_ALL);
18275 data.append(target->GetPackGUID());
18277 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
18278 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
18280 for(uint32 j = 0; j < 3; ++j)
18282 if(Aura *aura = target->GetAura(itr->second, j))
18284 data << uint8(aura->GetAuraSlot());
18285 data << uint32(aura->GetId());
18287 if(aura->GetId())
18289 uint8 auraFlags = aura->GetAuraFlags();
18290 // flags
18291 data << uint8(auraFlags);
18292 // level
18293 data << uint8(aura->GetAuraLevel());
18294 // charges
18295 data << uint8(aura->GetAuraCharges());
18297 if(!(auraFlags & AFLAG_NOT_CASTER))
18299 data << uint8(0); // packed GUID of someone (caster?)
18302 if(auraFlags & AFLAG_DURATION) // include aura duration
18304 data << uint32(aura->GetAuraMaxDuration());
18305 data << uint32(aura->GetAuraDuration());
18308 break;
18313 GetSession()->SendPacket(&data);
18316 void Player::SetDailyQuestStatus( uint32 quest_id )
18318 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18320 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
18322 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
18323 m_lastDailyQuestTime = time(NULL); // last daily quest time
18324 m_DailyQuestChanged = true;
18325 break;
18330 void Player::ResetDailyQuestStatus()
18332 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
18333 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
18335 // DB data deleted in caller
18336 m_DailyQuestChanged = false;
18337 m_lastDailyQuestTime = 0;
18340 BattleGround* Player::GetBattleGround() const
18342 if(GetBattleGroundId()==0)
18343 return NULL;
18345 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgTypeID);
18348 bool Player::InArena() const
18350 BattleGround *bg = GetBattleGround();
18351 if(!bg || !bg->isArena())
18352 return false;
18354 return true;
18357 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
18359 // get a template bg instead of running one
18360 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18361 if(!bg)
18362 return false;
18364 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18365 return false;
18367 return true;
18370 BGQueueIdBasedOnLevel Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId) const
18372 //returned to hardcoded version of this function, because there is no way to code it dynamic
18373 uint32 level = getLevel();
18374 if( bgTypeId == BATTLEGROUND_AV )
18375 level--;
18377 uint32 queue_id = (level / 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18378 if( queue_id >= MAX_BATTLEGROUND_QUEUES )
18380 sLog.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id);
18381 return QUEUE_ID_MAX_LEVEL_80;
18383 return BGQueueIdBasedOnLevel(queue_id);
18386 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18388 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18389 if(!vendor_faction || !vendor_faction->faction)
18390 return 1.0f;
18392 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18393 if(rank <= REP_NEUTRAL)
18394 return 1.0f;
18396 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18399 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18401 uint32 racemask = getRaceMask();
18402 uint32 classmask = getClassMask();
18404 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18405 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18406 if(lower==upper)
18407 return true;
18409 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18411 // skip wrong race skills
18412 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18413 continue;
18415 // skip wrong class skills
18416 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18417 continue;
18419 return true;
18422 return false;
18425 bool Player::HasQuestForGO(int32 GOId) const
18427 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
18429 uint32 questid = GetQuestSlotQuestId(i);
18430 if ( questid == 0 )
18431 continue;
18433 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
18434 if(qs_itr == mQuestStatus.end())
18435 continue;
18437 QuestStatusData const& qs = qs_itr->second;
18439 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18441 Quest const* qinfo = objmgr.GetQuestTemplate(questid);
18442 if(!qinfo)
18443 continue;
18445 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18446 continue;
18448 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
18450 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18451 continue;
18453 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18454 return true;
18458 return false;
18461 void Player::UpdateForQuestWorldObjects()
18463 if(m_clientGUIDs.empty())
18464 return;
18466 UpdateData udata;
18467 WorldPacket packet;
18468 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18470 if(IS_GAMEOBJECT_GUID(*itr))
18472 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18473 if(obj)
18474 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18476 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
18478 Creature *obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
18479 if(!obj)
18480 continue;
18481 // check if this unit requires quest specific flags
18483 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
18484 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(obj->GetEntry()); itr != map.upper_bound(obj->GetEntry()); ++itr)
18486 if(itr->second.questId != 0)
18488 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
18489 break;
18495 udata.BuildPacket(&packet);
18496 GetSession()->SendPacket(&packet);
18499 void Player::SummonIfPossible(bool agree)
18501 if(!agree)
18503 m_summon_expire = 0;
18504 return;
18507 // expire and auto declined
18508 if(m_summon_expire < time(NULL))
18509 return;
18511 // stop taxi flight at summon
18512 if(isInFlight())
18514 GetMotionMaster()->MovementExpired();
18515 m_taxi.ClearTaxiDestinations();
18518 // drop flag at summon
18519 // 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
18520 if(BattleGround *bg = GetBattleGround())
18521 bg->EventPlayerDroppedFlag(this);
18523 m_summon_expire = 0;
18525 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
18527 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18530 void Player::RemoveItemDurations( Item *item )
18532 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18534 if(*itr==item)
18536 m_itemDuration.erase(itr);
18537 break;
18542 void Player::AddItemDurations( Item *item )
18544 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18546 m_itemDuration.push_back(item);
18547 item->SendTimeUpdate(this);
18551 void Player::AutoUnequipOffhandIfNeed()
18553 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18554 if(!offItem)
18555 return;
18557 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18558 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
18559 return;
18561 ItemPosCountVec off_dest;
18562 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18563 if( off_msg == EQUIP_ERR_OK )
18565 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18566 StoreItem( off_dest, offItem, true );
18568 else
18570 MailItemsInfo mi;
18571 mi.AddItem(offItem->GetGUIDLow(), offItem->GetEntry(), offItem);
18572 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18573 CharacterDatabase.BeginTransaction();
18574 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
18575 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18576 CharacterDatabase.CommitTransaction();
18578 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
18579 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
18583 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18585 if(spellInfo->EquippedItemClass < 0)
18586 return true;
18588 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18589 // for optimize check 2 used cases only
18590 switch(spellInfo->EquippedItemClass)
18592 case ITEM_CLASS_WEAPON:
18594 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18595 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18596 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18597 return true;
18598 break;
18600 case ITEM_CLASS_ARMOR:
18602 // tabard not have dependent spells
18603 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18604 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18605 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18606 return true;
18608 // shields can be equipped to offhand slot
18609 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18610 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18611 return true;
18613 // ranged slot can have some armor subclasses
18614 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18615 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18616 return true;
18618 break;
18620 default:
18621 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18622 break;
18625 return false;
18628 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
18630 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18631 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
18632 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
18633 return true;
18635 // Check no reagent use mask
18636 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
18637 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
18638 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
18639 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
18640 return true;
18642 return false;
18645 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18647 AuraMap& auras = GetAuras();
18648 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
18650 Aura* aura = itr->second;
18652 // skip passive (passive item dependent spells work in another way) and not self applied auras
18653 SpellEntry const* spellInfo = aura->GetSpellProto();
18654 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18656 ++itr;
18657 continue;
18660 // skip if not item dependent or have alternative item
18661 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18663 ++itr;
18664 continue;
18667 // no alt item, remove aura, restart check
18668 RemoveAurasDueToSpell(aura->GetId());
18669 itr = auras.begin();
18672 // currently casted spells can be dependent from item
18673 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
18675 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18676 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18677 InterruptSpell(i);
18681 uint32 Player::GetResurrectionSpellId()
18683 // search priceless resurrection possibilities
18684 uint32 prio = 0;
18685 uint32 spell_id = 0;
18686 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18687 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18689 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18690 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18692 switch((*itr)->GetId())
18694 case 20707: spell_id = 3026; break; // rank 1
18695 case 20762: spell_id = 20758; break; // rank 2
18696 case 20763: spell_id = 20759; break; // rank 3
18697 case 20764: spell_id = 20760; break; // rank 4
18698 case 20765: spell_id = 20761; break; // rank 5
18699 case 27239: spell_id = 27240; break; // rank 6
18700 case 47883: spell_id = 47882; break; // rank 7
18701 default:
18702 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
18703 continue;
18706 prio = 3;
18708 // Twisting Nether // prio: 2 (max)
18709 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18711 prio = 2;
18712 spell_id = 23700;
18716 // Reincarnation (passive spell) // prio: 1
18717 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18718 spell_id = 21169;
18720 return spell_id;
18723 // Used in triggers for check "Only to targets that grant experience or honor" req
18724 bool Player::isHonorOrXPTarget(Unit* pVictim)
18726 uint32 v_level = pVictim->getLevel();
18727 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
18729 // Victim level less gray level
18730 if(v_level<=k_grey)
18731 return false;
18733 if(pVictim->GetTypeId() == TYPEID_UNIT)
18735 if (((Creature*)pVictim)->isTotem() ||
18736 ((Creature*)pVictim)->isPet() ||
18737 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
18738 return false;
18740 return true;
18743 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18745 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18747 // prepare data for near group iteration (PvP and !PvP cases)
18748 uint32 xp = 0;
18749 bool honored_kill = false;
18751 if(Group *pGroup = GetGroup())
18753 uint32 count = 0;
18754 uint32 sum_level = 0;
18755 Player* member_with_max_level = NULL;
18756 Player* not_gray_member_with_max_level = NULL;
18758 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18760 if(member_with_max_level)
18762 /// not get Xp in PvP or no not gray players in group
18763 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18765 /// skip in check PvP case (for speed, not used)
18766 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18767 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18768 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18770 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18772 Player* pGroupGuy = itr->getSource();
18773 if(!pGroupGuy)
18774 continue;
18776 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18777 continue; // member (alive or dead) or his corpse at req. distance
18779 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18780 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18781 honored_kill = true;
18783 // xp and reputation only in !PvP case
18784 if(!PvP)
18786 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18788 // if is in dungeon then all receive full reputation at kill
18789 // rewarded any alive/dead/near_corpse group member
18790 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18792 // XP updated only for alive group member
18793 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18794 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18796 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18798 pGroupGuy->GiveXP(itr_xp, pVictim);
18799 if(Pet* pet = pGroupGuy->GetPet())
18800 pet->GivePetXP(itr_xp/2);
18803 // quest objectives updated only for alive group member or dead but with not released body
18804 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18806 // normal creature (not pet/etc) can be only in !PvP case
18807 if(pVictim->GetTypeId()==TYPEID_UNIT)
18808 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18814 else // if (!pGroup)
18816 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18818 // honor can be in PvP and !PvP (racial leader) cases
18819 if(RewardHonor(pVictim,1))
18820 honored_kill = true;
18822 // xp and reputation only in !PvP case
18823 if(!PvP)
18825 RewardReputation(pVictim,1);
18826 GiveXP(xp, pVictim);
18828 if(Pet* pet = GetPet())
18829 pet->GivePetXP(xp);
18831 // normal creature (not pet/etc) can be only in !PvP case
18832 if(pVictim->GetTypeId()==TYPEID_UNIT)
18833 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18836 return xp || honored_kill;
18839 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
18841 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
18843 // prepare data for near group iteration
18844 if(Group *pGroup = GetGroup())
18846 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18848 Player* pGroupGuy = itr->getSource();
18849 if(!pGroupGuy)
18850 continue;
18852 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
18853 continue; // member (alive or dead) or his corpse at req. distance
18855 // quest objectives updated only for alive group member or dead but with not released body
18856 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18857 pGroupGuy->KilledMonster(creature_id, creature_guid);
18860 else // if (!pGroup)
18861 KilledMonster(creature_id, creature_guid);
18864 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18866 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
18867 return true;
18869 if (isAlive())
18870 return false;
18872 Corpse* corpse = GetCorpse();
18873 if (!corpse)
18874 return false;
18876 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
18879 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18881 Item* item = GetWeaponForAttack(attType,true);
18883 // unarmed only with base attack
18884 if(attType != BASE_ATTACK && !item)
18885 return 0;
18887 // weapon skill or (unarmed for base attack)
18888 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
18889 return GetBaseSkillValue(skill);
18892 void Player::ResurectUsingRequestData()
18894 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
18895 if(IS_PLAYER_GUID(m_resurrectGUID))
18896 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18898 ResurrectPlayer(0.0f,false);
18900 if(GetMaxHealth() > m_resurrectHealth)
18901 SetHealth( m_resurrectHealth );
18902 else
18903 SetHealth( GetMaxHealth() );
18905 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18906 SetPower(POWER_MANA, m_resurrectMana );
18907 else
18908 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18910 SetPower(POWER_RAGE, 0 );
18912 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18914 SpawnCorpseBones();
18917 void Player::SetClientControl(Unit* target, uint8 allowMove)
18919 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18920 data.append(target->GetPackGUID());
18921 data << uint8(allowMove);
18922 GetSession()->SendPacket(&data);
18925 void Player::UpdateZoneDependentAuras( uint32 newZone )
18927 // remove new continent flight forms
18928 if( !IsAllowUseFlyMountsHere() )
18930 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18931 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18934 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18935 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newZone);
18936 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18937 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
18938 if( !HasAura(itr->second->spellId,0) )
18939 CastSpell(this,itr->second->spellId,true);
18942 void Player::UpdateAreaDependentAuras( uint32 newArea )
18944 // remove auras from spells with area limitations
18945 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18947 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18948 if(spellmgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
18949 RemoveAura(iter);
18950 else
18951 ++iter;
18954 // some auras applied at subzone enter
18955 SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAreaMapBounds(newArea);
18956 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
18957 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
18958 if( !HasAura(itr->second->spellId,0) )
18959 CastSpell(this,itr->second->spellId,true);
18962 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18964 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18965 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18967 return copseReclaimDelay[0];
18970 time_t now = time(NULL);
18971 // 0..2 full period
18972 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18973 return copseReclaimDelay[count];
18976 void Player::UpdateCorpseReclaimDelay()
18978 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18980 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18981 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18982 return;
18984 time_t now = time(NULL);
18985 if(now < m_deathExpireTime)
18987 // full and partly periods 1..3
18988 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18989 if(count < MAX_DEATH_COUNT)
18990 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18991 else
18992 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18994 else
18995 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18998 void Player::SendCorpseReclaimDelay(bool load)
19000 Corpse* corpse = GetCorpse();
19001 if(!corpse)
19002 return;
19004 uint32 delay;
19005 if(load)
19007 if(corpse->GetGhostTime() > m_deathExpireTime)
19008 return;
19010 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19012 uint32 count;
19013 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19014 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19016 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19017 if(count>=MAX_DEATH_COUNT)
19018 count = MAX_DEATH_COUNT-1;
19020 else
19021 count=0;
19023 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19025 time_t now = time(NULL);
19026 if(now >= expected_time)
19027 return;
19029 delay = expected_time-now;
19031 else
19032 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19034 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19035 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19036 data << uint32(delay*IN_MILISECONDS);
19037 GetSession()->SendPacket( &data );
19040 Player* Player::GetNextRandomRaidMember(float radius)
19042 Group *pGroup = GetGroup();
19043 if(!pGroup)
19044 return NULL;
19046 std::vector<Player*> nearMembers;
19047 nearMembers.reserve(pGroup->GetMembersCount());
19049 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19051 Player* Target = itr->getSource();
19053 // IsHostileTo check duel and controlled by enemy
19054 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19055 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19056 nearMembers.push_back(Target);
19059 if (nearMembers.empty())
19060 return NULL;
19062 uint32 randTarget = urand(0,nearMembers.size()-1);
19063 return nearMembers[randTarget];
19066 PartyResult Player::CanUninviteFromGroup() const
19068 const Group* grp = GetGroup();
19069 if(!grp)
19070 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19072 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19073 return PARTY_RESULT_YOU_NOT_LEADER;
19075 if(InBattleGround())
19076 return PARTY_RESULT_INVITE_RESTRICTED;
19078 return PARTY_RESULT_OK;
19081 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19083 //we must move references from m_group to m_originalGroup
19084 SetOriginalGroup(GetGroup(), GetSubGroup());
19086 m_group.unlink();
19087 m_group.link(group, this);
19088 m_group.setSubGroup((uint8)subgroup);
19091 void Player::RemoveFromBattleGroundRaid()
19093 //remove existing reference
19094 m_group.unlink();
19095 if( Group* group = GetOriginalGroup() )
19097 m_group.link(group, this);
19098 m_group.setSubGroup(GetOriginalSubGroup());
19100 SetOriginalGroup(NULL);
19103 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19105 if( group == NULL )
19106 m_originalGroup.unlink();
19107 else
19109 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19110 assert(subgroup >= 0);
19111 m_originalGroup.link(group, this);
19112 m_originalGroup.setSubGroup((uint8)subgroup);
19116 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19118 LiquidData liquid_status;
19119 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19120 if (!res)
19122 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19123 // Small hack for enable breath in WMO
19124 if (IsInWater())
19125 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19126 return;
19129 // All liquids type - check under water position
19130 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
19132 if ( res & LIQUID_MAP_UNDER_WATER)
19133 m_MirrorTimerFlags |= UNDERWATER_INWATER;
19134 else
19135 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
19138 // Allow travel in dark water on taxi or transport
19139 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
19140 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
19141 else
19142 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
19144 // in lava check, anywhere in lava level
19145 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
19147 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19148 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
19149 else
19150 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
19152 // in slime check, anywhere in slime level
19153 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
19155 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
19156 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
19157 else
19158 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
19162 void Player::SetCanParry( bool value )
19164 if(m_canParry==value)
19165 return;
19167 m_canParry = value;
19168 UpdateParryPercentage();
19171 void Player::SetCanBlock( bool value )
19173 if(m_canBlock==value)
19174 return;
19176 m_canBlock = value;
19177 UpdateBlockPercentage();
19180 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
19182 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
19183 if(itr->pos == pos)
19184 return true;
19186 return false;
19189 bool Player::CanUseBattleGroundObject()
19191 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19192 // maybe gameobject code should handle that ForceReaction usage
19193 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19194 return ( //InBattleGround() && // in battleground - not need, check in other cases
19195 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19196 //player cannot use object when he is invulnerable (immune)
19197 !isTotalImmune() && // not totally immune
19198 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19199 !HasStealthAura() && // not stealthed
19200 !HasInvisibilityAura() && // not invisible
19201 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
19202 isAlive() // live player
19206 bool Player::CanCaptureTowerPoint()
19208 return ( !HasStealthAura() && // not stealthed
19209 !HasInvisibilityAura() && // not invisible
19210 isAlive() // live player
19214 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
19216 uint32 level = getLevel();
19218 if(level > GT_MAX_LEVEL)
19219 level = GT_MAX_LEVEL; // max level in this dbc
19221 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
19222 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
19223 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
19225 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
19226 return 0;
19228 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
19230 if(!bsc) // shouldn't happen
19231 return 0xFFFFFFFF;
19233 float cost = 0;
19235 if(hairstyle != newhairstyle)
19236 cost += bsc->cost; // full price
19238 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
19239 cost += bsc->cost * 0.5f; // +1/2 of price
19241 if(facialhair != newfacialhair)
19242 cost += bsc->cost * 0.75f; // +3/4 of price
19244 return uint32(cost);
19247 void Player::InitGlyphsForLevel()
19249 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
19250 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
19251 if(gs->Order)
19252 SetGlyphSlot(gs->Order - 1, gs->Id);
19254 uint32 level = getLevel();
19255 uint32 value = 0;
19257 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19258 if(level >= 15)
19259 value |= (0x01 | 0x02);
19260 if(level >= 30)
19261 value |= 0x08;
19262 if(level >= 50)
19263 value |= 0x04;
19264 if(level >= 70)
19265 value |= 0x10;
19266 if(level >= 80)
19267 value |= 0x20;
19269 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
19272 void Player::EnterVehicle(Vehicle *vehicle)
19274 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
19275 if(!ve)
19276 return;
19278 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
19279 if(!veSeat)
19280 return;
19282 vehicle->SetCharmerGUID(GetGUID());
19283 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19284 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19285 vehicle->setFaction(getFaction());
19287 SetCharm(vehicle); // charm
19288 SetFarSightGUID(vehicle->GetGUID()); // set view
19290 SetClientControl(vehicle, 1); // redirect controls to vehicle
19292 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
19293 GetSession()->SendPacket(&data);
19295 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
19296 data.append(GetPackGUID());
19297 data << uint32(0); // counter?
19298 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
19299 data << uint16(0); // special flags
19300 data << uint32(getMSTime()); // time
19301 data << vehicle->GetPositionX(); // x
19302 data << vehicle->GetPositionY(); // y
19303 data << vehicle->GetPositionZ(); // z
19304 data << vehicle->GetOrientation(); // o
19305 // transport part, TODO: load/calculate seat offsets
19306 data << uint64(vehicle->GetGUID()); // transport guid
19307 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
19308 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
19309 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
19310 data << float(0); // transport orientation
19311 data << uint32(getMSTime()); // transport time
19312 data << uint8(0); // seat
19313 // end of transport part
19314 data << uint32(0); // fall time
19315 GetSession()->SendPacket(&data);
19317 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
19318 data << uint64(vehicle->GetGUID());
19319 data << uint32(0);
19320 data << uint32(0);
19321 data << uint32(0x00000101);
19323 for(uint32 i = 0; i < 10; ++i)
19324 data << uint16(0) << uint8(0) << uint8(i+8);
19326 data << uint8(0);
19327 data << uint8(0);
19328 GetSession()->SendPacket(&data);
19331 void Player::ExitVehicle(Vehicle *vehicle)
19333 vehicle->SetCharmerGUID(0);
19334 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
19335 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_24);
19336 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
19338 SetCharm(NULL);
19339 SetFarSightGUID(0);
19341 SetClientControl(vehicle, 0);
19343 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
19344 data.append(GetPackGUID());
19345 data << uint32(0); // counter?
19346 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
19347 data << uint16(0x40); // special flags
19348 data << uint32(getMSTime()); // time
19349 data << vehicle->GetPositionX(); // x
19350 data << vehicle->GetPositionY(); // y
19351 data << vehicle->GetPositionZ(); // z
19352 data << vehicle->GetOrientation(); // o
19353 data << uint32(0); // fall time
19354 GetSession()->SendPacket(&data);
19356 data.Initialize(SMSG_PET_SPELLS, 8+4);
19357 data << uint64(0);
19358 data << uint32(0);
19359 GetSession()->SendPacket(&data);
19361 // maybe called at dummy aura remove?
19362 // CastSpell(this, 45472, true); // Parachute
19365 bool Player::isTotalImmune()
19367 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
19369 uint32 immuneMask = 0;
19370 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
19372 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
19373 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
19374 return true;
19376 return false;
19379 bool Player::HasTitle(uint32 bitIndex)
19381 if (bitIndex > 128)
19382 return false;
19384 uint32 fieldIndexOffset = bitIndex / 32;
19385 uint32 flag = 1 << (bitIndex % 32);
19386 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19389 void Player::SetTitle(CharTitlesEntry const* title)
19391 uint32 fieldIndexOffset = title->bit_index / 32;
19392 uint32 flag = 1 << (title->bit_index % 32);
19393 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
19396 void Player::ConvertRune(uint8 index, uint8 newType)
19398 SetCurrentRune(index, newType);
19400 WorldPacket data(SMSG_CONVERT_RUNE, 2);
19401 data << uint8(index);
19402 data << uint8(newType);
19403 GetSession()->SendPacket(&data);
19406 void Player::ResyncRunes(uint8 count)
19408 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
19409 for(uint32 i = 0; i < count; ++i)
19411 data << uint8(GetCurrentRune(i)); // rune type
19412 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
19414 GetSession()->SendPacket(&data);
19417 void Player::AddRunePower(uint8 index)
19419 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
19420 data << uint32(1 << index); // mask (0x00-0x3F probably)
19421 GetSession()->SendPacket(&data);
19424 void Player::InitRunes()
19426 if(getClass() != CLASS_DEATH_KNIGHT)
19427 return;
19429 m_runes = new Runes;
19431 m_runes->runeState = 0;
19433 for(uint32 i = 0; i < MAX_RUNES; ++i)
19435 SetBaseRune(i, i / 2); // init base types
19436 SetCurrentRune(i, i / 2); // init current types
19437 SetRuneCooldown(i, 0); // reset cooldowns
19438 m_runes->SetRuneState(i);
19441 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
19442 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
19445 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
19447 Loot loot;
19448 loot.FillLoot (loot_id,store,this,true);
19450 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
19451 for(uint32 i = 0; i < max_slot; ++i)
19453 LootItem* lootItem = loot.LootItemInSlot(i,this);
19455 ItemPosCountVec dest;
19456 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
19457 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
19458 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19459 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
19460 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
19461 if(msg != EQUIP_ERR_OK)
19463 SendEquipError( msg, NULL, NULL );
19464 continue;
19467 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
19468 SendNewItem(pItem, lootItem->count, false, false, broadcast);
19472 uint32 Player::CalculateTalentsPoints() const
19474 uint32 base_talent = getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld.getRate(RATE_TALENT));
19476 if(getClass() != CLASS_DEATH_KNIGHT)
19477 return base_talent;
19479 uint32 talentPointsForLevel =
19480 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld.getRate(RATE_TALENT)))
19481 + m_questRewardTalentCount;
19483 if(talentPointsForLevel > base_talent)
19484 talentPointsForLevel = base_talent;
19486 return talentPointsForLevel;
19489 bool Player::IsAllowUseFlyMountsHere() const
19491 if (isGameMaster())
19492 return true;
19494 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19495 return v_map == 530 || v_map == 571 && HasSpell(54197);
19498 void Player::learnSpellHighRank(uint32 spellid)
19500 learnSpell(spellid,false);
19502 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
19503 for(SpellChainMapNext::const_iterator itr = nextMap.lower_bound(spellid); itr != nextMap.upper_bound(spellid); ++itr)
19504 learnSpellHighRank(itr->second);
19507 void Player::_LoadSkills()
19509 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19511 // reset skill modifiers and set correct unlearn flags
19512 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
19514 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
19516 // set correct unlearn bit
19517 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
19518 if(!id) continue;
19520 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
19521 if(!pSkill) continue;
19523 // enable unlearn button for primary professions only
19524 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
19525 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
19526 else
19527 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
19529 // set fixed skill ranges
19530 switch(GetSkillRangeType(pSkill,false))
19532 case SKILL_RANGE_LANGUAGE: // 300..300
19533 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(300,300));
19534 break;
19535 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
19536 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(1,1));
19537 break;
19538 default:
19539 break;
19542 uint32 vskill = SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
19543 learnSkillRewardedSpells(id, vskill);
19546 // special settings
19547 if(getClass()==CLASS_DEATH_KNIGHT)
19549 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
19550 if(base_level < 1)
19551 base_level = 1;
19552 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
19553 if(base_skill < 1)
19554 base_skill = 1; // skill mast be known and then > 0 in any case
19556 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
19557 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
19558 if(GetPureSkillValue (SKILL_AXES) < base_skill)
19559 SetSkill(SKILL_AXES, base_skill,base_skill);
19560 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
19561 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
19562 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
19563 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
19564 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
19565 SetSkill(SKILL_SWORDS, base_skill,base_skill);
19566 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
19567 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
19568 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
19569 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
19570 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
19571 SetSkill(SKILL_UNARMED, base_skill,base_skill);
19575 uint32 Player::GetPhaseMaskForSpawn() const
19577 uint32 phase = PHASEMASK_NORMAL;
19578 if(!isGameMaster())
19579 phase = GetPhaseMask();
19580 else
19582 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
19583 if(!phases.empty())
19584 phase = phases.front()->GetMiscValue();
19587 // some aura phases include 1 normal map in addition to phase itself
19588 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
19589 return n_phase;
19591 return PHASEMASK_NORMAL;
19594 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
19596 ItemPrototype const* pProto = pItem->GetProto();
19598 // proto based limitations
19599 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
19600 return res;
19602 // check unique-equipped on gems
19603 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
19605 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
19606 if(!enchant_id)
19607 continue;
19608 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
19609 if(!enchantEntry)
19610 continue;
19612 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
19613 if(!pGem)
19614 continue;
19616 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19617 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
19618 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
19620 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
19621 return res;
19624 return EQUIP_ERR_OK;
19627 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
19629 // check unique-equipped on item
19630 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
19632 // there is an equip limit on this item
19633 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
19634 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19637 // check unique-equipped limit
19638 if (itemProto->ItemLimitCategory)
19640 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
19641 if(!limitEntry)
19642 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19644 if(limit_count > limitEntry->maxCount)
19645 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
19647 // there is an equip limit on this item
19648 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
19649 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
19652 return EQUIP_ERR_OK;
19655 void Player::HandleFall(MovementInfo const& movementInfo)
19657 // calculate total z distance of the fall
19658 float z_diff = m_lastFallZ - movementInfo.z;
19659 sLog.outDebug("zDiff = %f", z_diff);
19661 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19662 // 14.57 can be calculated by resolving damageperc formula below to 0
19663 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
19664 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
19665 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
19667 //Safe fall, fall height reduction
19668 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
19670 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
19672 if(damageperc >0 )
19674 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
19676 float height = movementInfo.z;
19677 UpdateGroundPositionZ(movementInfo.x,movementInfo.y,height);
19679 if (damage > 0)
19681 //Prevent fall damage from being more than the player maximum health
19682 if (damage > GetMaxHealth())
19683 damage = GetMaxHealth();
19685 // Gust of Wind
19686 if (GetDummyAura(43621))
19687 damage = GetMaxHealth()/2;
19689 EnvironmentalDamage(DAMAGE_FALL, damage);
19691 // recheck alive, might have died of EnvironmentalDamage
19692 if (isAlive())
19693 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
19696 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19697 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);
19702 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
19704 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
19707 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
19709 uint32 CurTalentPoints = GetFreeTalentPoints();
19711 if(CurTalentPoints == 0)
19712 return;
19714 if (talentRank >= MAX_TALENT_RANK)
19715 return;
19717 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
19719 if(!talentInfo)
19720 return;
19722 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
19724 if(!talentTabInfo)
19725 return;
19727 // prevent learn talent for different class (cheating)
19728 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
19729 return;
19731 // find current max talent rank
19732 int32 curtalent_maxrank = 0;
19733 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19735 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
19737 curtalent_maxrank = k + 1;
19738 break;
19742 // we already have same or higher talent rank learned
19743 if(curtalent_maxrank >= (talentRank + 1))
19744 return;
19746 // check if we have enough talent points
19747 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19748 return;
19750 // Check if it requires another talent
19751 if (talentInfo->DependsOn > 0)
19753 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19755 bool hasEnoughRank = false;
19756 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19758 if (depTalentInfo->RankID[i] != 0)
19759 if (HasSpell(depTalentInfo->RankID[i]))
19760 hasEnoughRank = true;
19762 if (!hasEnoughRank)
19763 return;
19767 // Find out how many points we have in this field
19768 uint32 spentPoints = 0;
19770 uint32 tTab = talentInfo->TalentTab;
19771 if (talentInfo->Row > 0)
19773 unsigned int numRows = sTalentStore.GetNumRows();
19774 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19776 // Someday, someone needs to revamp
19777 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19778 if (tmpTalent) // the way talents are tracked
19780 if (tmpTalent->TalentTab == tTab)
19782 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19784 if (tmpTalent->RankID[j] != 0)
19786 if (HasSpell(tmpTalent->RankID[j]))
19788 spentPoints += j + 1;
19797 // not have required min points spent in talent tree
19798 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
19799 return;
19801 // spell not set in talent.dbc
19802 uint32 spellid = talentInfo->RankID[talentRank];
19803 if( spellid == 0 )
19805 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19806 return;
19809 // already known
19810 if(HasSpell(spellid))
19811 return;
19813 // learn! (other talent ranks will unlearned at learning)
19814 learnSpell(spellid, false);
19815 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19817 // update free talent points
19818 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19821 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
19823 Pet *pet = GetPet();
19825 if(!pet)
19826 return;
19828 if(petGuid != pet->GetGUID())
19829 return;
19831 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
19833 if(CurTalentPoints == 0)
19834 return;
19836 if (talentRank >= MAX_PET_TALENT_RANK)
19837 return;
19839 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
19841 if(!talentInfo)
19842 return;
19844 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
19846 if(!talentTabInfo)
19847 return;
19849 CreatureInfo const *ci = pet->GetCreatureInfo();
19851 if(!ci)
19852 return;
19854 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
19856 if(!pet_family)
19857 return;
19859 if(pet_family->petTalentType < 0) // not hunter pet
19860 return;
19862 // prevent learn talent for different family (cheating)
19863 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
19864 return;
19866 // find current max talent rank
19867 int32 curtalent_maxrank = 0;
19868 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
19870 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
19872 curtalent_maxrank = k + 1;
19873 break;
19877 // we already have same or higher talent rank learned
19878 if(curtalent_maxrank >= (talentRank + 1))
19879 return;
19881 // check if we have enough talent points
19882 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
19883 return;
19885 // Check if it requires another talent
19886 if (talentInfo->DependsOn > 0)
19888 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
19890 bool hasEnoughRank = false;
19891 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
19893 if (depTalentInfo->RankID[i] != 0)
19894 if (pet->HasSpell(depTalentInfo->RankID[i]))
19895 hasEnoughRank = true;
19897 if (!hasEnoughRank)
19898 return;
19902 // Find out how many points we have in this field
19903 uint32 spentPoints = 0;
19905 uint32 tTab = talentInfo->TalentTab;
19906 if (talentInfo->Row > 0)
19908 unsigned int numRows = sTalentStore.GetNumRows();
19909 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
19911 // Someday, someone needs to revamp
19912 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
19913 if (tmpTalent) // the way talents are tracked
19915 if (tmpTalent->TalentTab == tTab)
19917 for (int j = 0; j < MAX_TALENT_RANK; ++j)
19919 if (tmpTalent->RankID[j] != 0)
19921 if (pet->HasSpell(tmpTalent->RankID[j]))
19923 spentPoints += j + 1;
19932 // not have required min points spent in talent tree
19933 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
19934 return;
19936 // spell not set in talent.dbc
19937 uint32 spellid = talentInfo->RankID[talentRank];
19938 if( spellid == 0 )
19940 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
19941 return;
19944 // already known
19945 if(pet->HasSpell(spellid))
19946 return;
19948 // learn! (other talent ranks will unlearned at learning)
19949 pet->learnSpell(spellid);
19950 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
19952 // update free talent points
19953 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
19956 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
19958 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
19960 if(apply)
19961 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19962 else
19963 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES,(UI64LIT(1) << (ctEntry->BitIndex-1)));
19967 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
19969 if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <=minfo.z || opcode == MSG_MOVE_FALL_LAND)
19970 SetFallInformation(minfo.fallTime, minfo.z);
19973 void Player::UnsummonPetTemporaryIfAny()
19975 Pet* pet = GetPet();
19976 if(!pet)
19977 return;
19979 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
19981 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
19982 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
19985 RemovePet(pet, PET_SAVE_AS_CURRENT);
19988 void Player::ResummonPetTemporaryUnSummonedIfAny()
19990 if(!m_temporaryUnsummonedPetNumber)
19991 return;
19993 // not resummon in not appropriate state
19994 if(IsPetNeedBeTemporaryUnsummoned())
19995 return;
19997 if(GetPetGUID())
19998 return;
20000 Pet* NewPet = new Pet;
20001 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20002 delete NewPet;
20004 m_temporaryUnsummonedPetNumber = 0;
20007 bool Player::canSeeSpellClickOn(Creature const *c) const
20009 SpellClickInfoMap const& map = objmgr.mSpellClickInfoMap;
20010 for(SpellClickInfoMap::const_iterator itr = map.lower_bound(c->GetEntry()); itr != map.upper_bound(c->GetEntry()); ++itr)
20012 if(itr->second.questId == 0 || GetQuestStatus(itr->second.questId) == QUEST_STATUS_INCOMPLETE)
20013 return true;
20015 return false;